Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design a simple CRUD REST API

I'm designing a simple CRUD REST API. This is my first time so I wanted to get some feedback on whether my design makes sense.

I'm utilizing the HTTP methods: GET, POST, DELETE, and UPDATE . The API will consume and fetch data in JSON format. The sample URL will be such as this:

GET (list): curl http://<domain>/myapp/rest/v1/colors
POST: curl -XPOST http://<domain>/myapp/rest/v1/colors -d '{
       "name": "red",
       "shade": "light"
      }'
GET (single item): curl http://<domain>/myapp/rest/v1/colors/2
DELETE: curl -XDELETE http://<domain>/myapp/rest/v1/colors/2
etc...

Question

After the POST request a record will be created in the database. So, should the POST request return the ID of the newly created record? So that ID can be used in UPDATE, DELETE and GET (single item)?

like image 902
birdy Avatar asked May 08 '13 10:05

birdy


2 Answers

The HTTP specification defines the following for POST:

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).

So this essentially means:

  • You should return 201 Created as status code
  • You should return a Location header, pointing to the URI of the newly created resource
  • You can optionally include a representation of the resource in the POST response body to free the client from having to issue another GET request against the value obtained from the Location header.
like image 151
Oliver Drotbohm Avatar answered Oct 23 '22 08:10

Oliver Drotbohm


The POST should return a redirect to the new url for the single item.

You probably want to loose the version identifier of the urls.

Instead design your representations and the clients in a way that handles various versions gracefully. For example a client should not depend on a specific format, but only on the attributes it actually needs.

What is kind of missing from your description is the HATEOAS principle, i.e. the client shouldn't hard code any URLs, but find the URLs for further actions inside the representation of other entities. Since you don't show an example document for the results returned by the URLs, we can't tell if you did that in a nice way.

Check out this presentation, it explains the topic and also mentions some Spring Library helpful for implementing it.

like image 1
Jens Schauder Avatar answered Oct 23 '22 10:10

Jens Schauder