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 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.
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.