Subscribe to PHP Freaks RSS

201 Created

syndicated from planet-php.net on July 10, 2018

201 Created, just like 200 OK, means that the request was successful, but it also resulted in a new resource being created.



In the case of a PUT request, it means that a new resource was created on the actual url that was specified in the request.



Example



PUT /new-resource HTTP/1.1
Content-Type: text/html
Host: example.org

...


HTTP/1.1 201 Created
ETag: "foo-bar"


POST requests



If you got a 201 in response to a POST request, it means that a new resource was created at a different endpoint. For those cases, a Location header must be included to indicate where the new resource lives.



In the following example, we’re creating a new resource via POST, and the server responds with the new location and the ETag of the new resource.



POST /collection/add-member HTTP/1.1
Content-Type: application/json
Host: example.org

{ "foo": "bar" }


HTTP/1.1 201 Created
ETag: "gir-zim"
Location: /collection/546


It’s common misconception that POST is generally for creating new resources, and PUT is strictly for updating them. However, the real difference is that PUT should be the preferred method if the client can determine the url of the resource it wants to create.



In practice most servers do want control over the url, perhaps because it’s tied to an auto-incrementing database id.