Enterprise Java

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

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
9
HTTP/1.1 201 Created
Location: /projects/123
Content-Type: application/json
 
{
    "id" 123,
    "name""My cool project",
    "description""Bla bla .."
}

Published on Java Code Geeks with permission by Michael Scharhag, partner at our JCG program. See the original article here: REST: Creating resources

Opinions expressed by Java Code Geeks contributors are their own.

Michael Scharhag

Michael Scharhag is a Java Developer, Blogger and technology enthusiast. Particularly interested in Java related technologies including Java EE, Spring, Groovy and Grails.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button