I want to follow the best practice to implement a REST API. There is a resource I want to expose and I can think of two ways of doing it as an endpoint.
I want to give the user the opportunity to receive all the payments for a certain campaign.
I can expose /campaigns/{id}/payment
that returns a paginated list of payments with all the data for each (name, address, date...). Where /campaign/{id}
in turn returns all the data of the campaign (name, description..., array of paymentId
with a route to get them one by one).
Or I can expose /payments/campaigns/{campaignsId}
.
What is the best approach and why?
I would use /campaigns/{id}/payments
because it communicates the contents of the response that the client can expect when querying this URL with a GET
most clearly and according to common practice.
GET /camapaigns/{id}/payments
reads much like "give me all the payments for the campaign with id = {id}
". So this follows the principle of least astonishment. Also, the client then gets exactly what's requested.
There's a nice API design guide for RESTful APIs from Microsoft, if you'd like to read more about this.