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

  • POST /users: creates a new user
  • GET /users: reads a list of users
  • GET /users/123: reads user with ID 123
  • PUT /users/123: updates user with ID 123
  • PATCH /users/123: partially updates user with ID 123
  • DELETE /users/123: deletes user with ID 123

Responding to GET requests: do not use envelopes

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

  • 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store