Home > Enterprise >  REST API Best Practices for Hierarchical JSON Objects
REST API Best Practices for Hierarchical JSON Objects

Time:09-16

Imagine a simple example like 'Vehicle Make and Model' REST API with CRUD methods implemented.

The relation between Vehicle Make to Model is 1:N. One vehicle make can have N models in it, but, one model is assosiated with just one make.

Our CRUD methods:

  • POST/PUT vehicles/makes: To create or update basic info about one vehicle make.
  • GET vehicles/makes: To get a list of vehicle makes.
  • GET vehicles/makes/{id}: To get a specific vehicle make with their info.
  • POST/PUT vehicles/makes/{id}/models: To create or update basic info about one vehicle model.
  • GET vehicles/makes/{id}/models: To get a list of vehicle models of a specific make.
  • GET vehicles/makes/{id}/models/{id}: To get a specific vehicle model of a specific make.

The question is:

Should the GET makes or makes/{id} return in it a list of theirs models? Or maybe, should the models be returned only in a specific request?

What must I consider to return or not a nested info in my API?


The example is a quite simple, but the scenario can be expanded in a way with a lot of hierarchical dependencies, like:

vehicle
├── vehicle_make
│   ├── vehicle_model
│   └── ...
├── tires
│   └── tire_brand
│       ├── tire_model
│       └── ...
└── ...
└── ...

CodePudding user response:

Well, it depends.

Who is the consumer of those APIs ? If its your own UI, another service or direct customers ?

Aim is to reduce the number of server calls. If consumer of the service is making multiple calls every time to get the required data, then it should be nested into single response. If your UI is using lazy loading, or other consumers need those data conditionally, then segregate into multiple APIs.

CodePudding user response:

Should the GET makes or makes/{id} return in it a list of theirs models? Or maybe, should the models be returned only in a specific request?

/makes should return the list of makes object (name of make).

/makes/{id} should also just return a single make object.

/makes/{id}/models should return all the models for that the make with the {id}.

I am aware of Swagger that allows to provide links to the models in the first two cases which would make it easy to browse the data.

https://swagger.io/docs/specification/links/

From what I can understand from your information, in your case the user will most likely select only one of the makes, so it makes no sense to preload them all in the client. If the user was adding multiple makes in an order it might make sense to cache them in the client.

  • Related