The 201 Created
status code is a part of the Hypertext Transfer Protocol (HTTP) response status codes. This status code indicates that a request has been successfully processed, and as a result, a new resource has been created on the server. The newly created resource’s URI is typically provided in the response’s Location
header. This status code is commonly used in response to POST
and PUT
requests.
When to Use 201 Created
You should use the 201 Created
status code when a request has successfully led to the creation of a new resource. This is most commonly encountered with POST
requests that create new resources on the server, such as adding a new user or creating a new blog post. The 201 Created
status code can also be used with PUT
requests when the request results in a new resource being created, rather than updating an existing one.
Example: 201 Created with POST Request
Consider a scenario where you are sending a POST
request to create a new user account on a web application. The request and response would look like the following:
Request
POST /users HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 81
{
"username": "newuser",
"email": "newuser@example.com",
"password": "securepassword"
}
Response
HTTP/1.1 201 Created
Content-Type: application/json
Location: /users/123
Content-Length: 110
{
"id": 123,
"username": "newuser",
"email": "newuser@example.com",
"created_at": "2021-09-01T12:00:00Z"
}
In this example, the server has successfully created a new user account and returns a 201 Created
status code. The Location
header in the response contains the URI of the newly created resource (/users/123
).
Example: 201 Created with PUT Request
In some cases, a PUT
request can also result in a 201 Created
status code. Consider a scenario where you are sending a PUT
request to create or replace a resource at a specific URI.
Request
PUT /users/123/profile HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 61
{
"bio": "Software Developer",
"location": "New York, NY"
}
Response
HTTP/1.1 201 Created
Content-Type: application/json
Location: /users/123/profile
Content-Length: 84
{
"id": 123,
"bio": "Software Developer",
"location": "New York, NY"
}
In this example, the server has successfully created or replaced the user’s profile resource and returns a 201 Created
status code. The Location
header in the response contains the URI of the newly created or updated resource (/users/123/profile
).
Summary
In summary, the 201 Created
status code is used to indicate that a request has been successfully processed, resulting in the creation of a new resource on the server. It is commonly used with POST
and PUT
requests. When sending a response with a 201 Created
status code, it is important to include the Location
header containing the URI of the newly created resource.