Good practices for Rest services [closed]

2

When I made my first API rest, I defined my JSON structure and it always returned the same structure even the pair having given it or not. I talked to a new co-worker and he introduced me to another perspective. If the pair has not given it, it is issued to save traffic on the network. My question is: is this a good practice?

    
asked by anonymous 16.02.2018 / 12:38

2 answers

2

Well, as I understand it, you're talking about omitting a null attribute. For example, instead of returning:

{
    atributo1: "Hello",
    atributo2: null,
}

Your colleague recommends:

{
    atributo1: "Hello"
}

This is not recommended and I believe data economy is insignificant in most cases.

Your API contract should always return the same fields, omitting one of them leads to contract breach, and may cause a number of API understanding issues. In sending ( request >) you may be more flexible, yes, but looking at API flexibility (to avoid an API versioning, for example) and not data saving.

Finally, according to the principle of robustness (or Postel's Law) alert us :

  

Postel's Law states that you should be liberal in what you   accept and conservative in what you send.

    
16.02.2018 / 16:07
3

Forget about this good practice business. It uses only two types of programmers: one who does not understand what he is doing and will use everything wrong, or the very experienced programmer and understands how a good practice should be used, that he is only a guide, often with bias, that does not take into account the context where it is being applied, and should only give an idea of what to observe, never blindly follow it.

In this case you have no way of knowing what to do because we do not have the context. We do not know if it gives any problem to omit (I imagine that it is, it would not make sense to be "emit" as it is in the question) the field key that has no value. There are cases where the interpretation of not having the element may be different from it having no value. It can give versioning problem, for example.

If you want to save traffic you can think of another format. You can use a format that you do not need to send the key repeatedly, just a header. This gives an absurdly greater gain. But it can not be used in all cases. It can make some kind of compression, in some cases it can be useful, in others it can be innocuous and have other costs that does not compensate the use.

    
16.02.2018 / 15:28