Doubts about best practices for API Rest (object - json)

0

I have questions regarding the practical improvements in json / object conversion between server (api rest) and client (javascript framework). My question is is regarding the objects referenced by the main entity, should I send only IDs or complete object? As an example (simple) I have the following relationship:

{
    "id":2,
    "nome":"SÃO GONÇALO",
    "cep":"24030103",
    "estado":{
                "id":1,
                "nome":"RIO DE JANEIRO",
                "sigla":"RJ"
            }
}

This structure represents the relationship between CITY and STATE. When registering a new city (POST) should I send the complete "state" object or just its ID to the server? Example:

  • Sending complete "status" object (POST):
     {
            "nome":"SÃO GONÇALO",
            "cep":"24030103",
            "estado":{
                        "id":1,
                        "nome":"RIO DE JANEIRO",
                        "sigla":"RJ"
                    }
     }
  • Sending only status ID (POST):
    {
        "nome":"SÃO GONÇALO",
        "cep":"24030103",
        "idEstado": 1
     }

Which of these approaches should be followed?

Regarding queries (GET), should I return to the full state reference or just your ID? The return only ID approach has the "problem" of needing a new query (javascript) to be able to display the state name to the user.

I believe that just passing the ID on the POST is the best, it does not traffic unnecessary data. If it is best to follow the ID line, what best practice is to convert these IDs on the server to objects (do I need the complete object on the server to validate business before it persists)?

This was a simple example, I have templates in my business where the number of references is quite large. I work with java on the server and angular on the frontend.

    
asked by anonymous 17.07.2018 / 15:18

1 answer

0

Regarding POST , the biggest problem when sending the complete object is data consistency. If for example, for some reason, the state comes with the following structure:

 "estado":{
      "id":1,
      "nome": "SÃO PAULO",
      "sigla": "RJ"
  }

What to do?

We do not know if the frontend made a mistake in assembling the request, or if someone changed the request "in the arm". It also has the issue of redundant data, since only with ID you can get the complete object reference.

When we talk about a GET , the story is reversed. As you mentioned, if we only traffic ID , we will need another request to fetch the state information.

  

If it is best to follow the ID line, what best practice is to convert these IDs on the server to objects?

Perform a query that returns the entire object, searching for ID . So yes, apply the business rules.

    
17.07.2018 / 16:46