Is it worth to exclude null fields from a JSON server response in a web application to reduce traffic?

后端 未结 3 1457
离开以前
离开以前 2021-02-01 17:36

Lets say that the API is well documented and every possible response field is described.

Should web application\'s server API exclude null fields in a JSON response to l

3条回答
  •  借酒劲吻你
    2021-02-01 17:54

    The question is on a wrong side - JSON is not the best format to compress or reduce traffic, but something like google protobuffers or bson is.

    I am carefully re-evaluating nullables in the API scheme right now. We use swagger (Open API) and json scheme does not really have something like nullable type and I think there is a good reason for this.

    If you have a JSON response that maps a DB integer field which is suddenly NULL (or can be according to DB scheme), well it is indeed ok for relational DB but not at all healthy for your API.

    I suggest to adopt and follow a much more elegant approach, and that would be to make better use of "required" also for the response.

    If the field is optional in the response API scheme and it has null value in the DB do not return this field.

    We have enabled strict scheme checks also for the API responses, and this gives us a much better control of our data and force us not to rely on states in the API.

    For the API client that of course means doing checks like:

    if ("key" in response) {
        console.log("Optional key value:" + response[key]);
    } else {
        console.log("Optional key not found");
    }
    

提交回复
热议问题