Defining your endpoints and responding to requests in your RESTful API
Fourth article in the series of “Pragmatic decisions for your RESTful API”, this post talks about how to define your endpoints and how you should respond to GET, POST, PUT and PATCH requests in your RESTful API.
Defining your endpoints: use plural
Your endpoints should be defined using plural, not singular, as it will avoid odd pluralization (such as person/people, country/countries etc…). For users, for example, this is the list of endpoints you could have:
POST /users
: creates a new userGET /users
: reads a list of usersGET /users/123
: reads user with ID 123PUT /users/123
: updates user with ID 123PATCH /users/123
: partially updates user with ID 123DELETE /users/123
: deletes user with ID 123
Responding to GET requests: do not use envelopes
When you read multiple results, such as via, for example, a call to the endpoint:
some APIs will send the following JSON representation (or approaching), wrapping data in an envelope:
{
metadata: { ... },
data: { ... }
}
Unless you have a lot of really specific metadata or specific requirements, I do not recommend the above representation, for the following reasons:
- It makes the output a bit harder to read for the client
- Envelopes are, in the vast majority of cases, not necessary
- Metadata can, if needed, be returned in HTTP headers
Responding to POST, PUT and PATCH: return the resource representation
When responding to a POST, PUT or PATCH request, for a resource creation or update, make sure you return the full resource representation in your response, for mainly 2 reasons:
- A call to a POST, PUT or PATCH request may make modifications not only on the fields that were changed as part of the request, but also to other fields (for example, the created_at and updated_at timestamps)
- Returning the resource representation in the response will save one HTTP request, because the client will not need to do a GET request on the modified or newly created resource to get the new resource representation.
If you want to read all of the articles of the series “ Pragmatic decisions for your RESTful API”, you can start here. The next article will focus on paging, sorting, filtering and searching your results.
This series of articles about Restful API design is also available as an eBook on Amazon, if you need it in a handy format.
Originally published at https://www.gvj-web.com on March 23, 2018.