Search code examples
restapiapi-design

How to handle two resources that are generally going to be requested with each other in REST?


So say I have three models/tables: note, shipment and users. And I want to request pages of the shipments but I will need information from the associated notes (text, image, etc.) of a particular user.

What is the best way to handle this?

Should I create a nested resource like /api/shipment/note and add query parameters to it to specify the user id, pagesize, etc.? (Is nesting resources like /api/shipment/note valid REST? I have seen something like /api/note/{noteid}/shipment is valid but what about teaming up get alls)

Or should I request all the shipments from /api/shipment (specifying user in query parameters) and request the note information for each shipment from /api/note/{noteid}?

Or should I use /api/user/{userid}/shipment/note?

Or because I am very rarely going to be requesting the shipment resource without the information from the note, should I just add in the note info into the /api/shipment endpoint?


Solution

  • If your use case has you querying both the shipment and the note together, it would be more efficient to combine the calls. This is also assuming that both sets of data come from the same data store.

    To handle the cases where you don't need the note data, you can introduce a verbosity level or an include query string parameter to identify the extra data that should be included.

    api/shipment?include=note|foo|bar

    OR

    api/shipment/{id}?include=note