HTTP PUT - Response Codes Explained

HTTP PUT - Response Codes Explained

In today's software development world, APIs have become the norm of communication between any two systems. Communication between two microservices, communication between frontend and backend of an application, etc.

When APIs are all the buzz, in the software development world, I can confidently say that you will run into APIs even if you are in the administrator roles and don't work on developing APIs directly. So given that, having a basic understanding of APIs is become necessary like oxygen.

I recently had to develop a bunch of REST APIs in Springboot which are exposed for consumption anyway a developer seems fit. However, this is the first time I started writing an application almost from the scratch, every small detail needed to be verified, unlike the other times where you can just see other similar parts in the code.

One of my biggest concerns was returning appropriate HTTP status codes, especially for a PUT call. In general, I would prefer to use POST for adding new data and using PUT for updating existing data. However, if you take idempotency into consideration, PUT is preferred to both creating new data and also updating existing data. PUT is idempotent and POST is not.

Now that using PUT is finalized, the next thing you need to think about what response codes to send back. Should you send 200? or 201? or 202? or 204? Well, this is how I like to define them:

200 OK

When a PUT call is made and an existing resource is updated successfully, I would like to send the response with data back because it may have additional information that the user didn't send like "ID" which is auto-generated at the creation of a resource.

201 Created

This is returned when a new resource is created. Most do use POST to create a new resource but there are situations like when an ID is not generated automatically and is provided by the API call, you must use PUT API call idempotency.

204 No Content

However, if the existing resource is being updated, I would like to return 204 with No Content because there is no new information that a user doesn't already know.

These are my personal preferences and am sure there is a lot of debate on the response codes. Read more about other response codes here.

I hope this was helpful and feel free to let me know your suggestions or comments.

Note: This is my first article on HashNode. Please excuse me if there are any mistakes. You can follow me on Twitter for more updates.

Credits: Cover image of the article is from realpython.com