Using the correct HTTP methods and status codes in your RESTful API

Guillaume Viguier-Just
2 min readMar 16, 2018

Third article in the series of “ Pragmatic decisions for your RESTful API”, this post talks about using the correct HTTP methods and status codes for your RESTful API.

Doing something with your resources: use HTTP methods

You will need to do 4 basic operations with your resources: Create, Read, Update and Delete. In order to do so, use HTTP methods:

  • POST: creates a new resource
  • GET: reads one or more resources
  • PUT / PATCH: updates a resource
  • DELETE: deletes a resources

PUT vs PATCH

As a sidenote, PUT requests expect the client to send the whole resource to be modified, while PATCH requests are used to modify some attributes of a resource only.

For example, let’s say you want to modify the email address of a user resource.

With PUT:

PUT /user/123{
id: "123",
email: "guillaume@gvj-web.com",
first_name: "Guillaume",
last_name: "Viguier"
}

With PATCH:

PATCH /user/123{
email: "guillaume@gvj-web.com"
}

Handling responses: use proper HTTP status codes

Do not forget that the main response of your RESTful API should be, before the data, a meaningful HTTP status code, informing the client whether everything went well or not, and if not, for which reason.

Here is a list of the most important ones:

  • 200 OK: the request succeeded, and data is being returned.
  • 201 Created: A new resource has been created, as a result of a call to this request. The Location header points to the URI of the new resource
  • 204 No Content: the request was successful, but no data is being returned (used for example after a DELETE request)
  • 400 Bad Request: the request could not be understood by the server due to wrong syntax (for example and attribute was in the wrong format)
  • 401 Unauthorized: the request requires authentication. The request COULD eventually be fulfilled with proper user authentication.
  • 403 Forbidden: the user is authenticated, but does not have permission to fulfill this request
  • 404 Not Found: the resource could not be found
  • 429 Too Many Requests: returned when a rate limit has been reached
  • 500 Internal server error: something is wrong with the server or the implementation

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 defining your endpoints and responding to GET, POST, PUT and PATCH requests.

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 16, 2018.

--

--