mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Monday, 22 June, 2020

REST: Creating resources

Resource creation is a common REST API operation. In this post we will see how single resource can be created.

The client request

Resources are typically created by sending a POST request to the parent collection resource. This creates a new subordinate resources with a newly generated id.

For example, a POST request to /projects might be used to create a new project resource at /projects/123.

POST is not idempotent, so it is fine to create multiple resources if the same request is issued multiple times. (If you don't know what idempotency is, have a look at my post about idempotency and safety).

In rare cases, where the client is able to generate a resource id it might also be possible to use PUT for resource creation. For example, in this case we can use PUT /projects/<id> to create a new project.

Clients must also send the following headers:

  • Content-Type to specify the media type of the request body
  • Accept to define supported response formats. Even if the server does not return the newly created resource, this header should be sent. It allows the server to send detailed error information if resource creation fails.

Example request

POST /projects
Content-Type: application/json
Accept: application/json

    "name": "My cool project",
    "description": "Bla bla .."

The server response

After a resource has been created successfully, the server should respond with HTTP 201 (Created). The response should also have a Location header that contains the URI of the newly created resource. When needed, the response body can contain the created resource. In this case, a Content-Type header is also required.

Example response

HTTP/1.1 201 Created
Location: /projects/123
Content-Type: application/json

    "id" : 123,
    "name": "My cool project",
    "description": "Bla bla .."


  • dev/affe - Friday, 26 June, 2020

    There's an error in the text: POST is NOT idempotent (as you correctly explain on the linked page)

  • Tavi - Friday, 26 June, 2020

    It would be interesting to also include more complex use cases, like a proper REST API for uploading a file...

  • Wesley - Friday, 26 June, 2020

    POST isn't an idempotent request.

    Looks like the table you have in your linked article is correct. Though the information here is sketchy.

  • mscharhag - Sunday, 28 June, 2020

    Of course you are correct, POST is idempotent. I missed a "not" in the sentence, fixed it. Thanks.

Leave a reply