How to create a simple CRUD REST API

I am developing a simple CRUD REST API. This is my first time, so I wanted to get some feedback on whether my design makes sense.

I use HTTP methods: GET, POST, DELETE and UPDATE. The API will use and receive data in JSON format. An example URL would be:

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 a POST request, a record will be created in the database. So, should the POST request return the identifier of the newly created record? So the identifier can be used in UPDATE, DELETE and GET (single item) ?

+7
source share
2 answers

The HTTP specification defines the following for POST:

If the resource was created on the source server, the response should be 201 (created) and contain an object that describes the status of the request and refers to the new resource and the Location header (see section 14.30).

Thus, this essentially means:

  • You must return 201 Created as a status code
  • You must return the Location header by pointing to the URI of the newly created resource
  • You can optionally include the resource representation in the POST response body to free the client from having to issue another GET request to the value obtained from the Location header.
+5
source

POST should return a redirect to the new URL for the individual element.

You probably want to lose the URL version identifier.

Instead, create your views and clients in a way that gracefully handles different versions. For example, the client should not depend on a specific format, but only on the attributes that it really needs.

Some drawback in your description is the HATEOAS principle, that is, the client does not have to hard-code any URLs, but find URLs for further actions inside the representation of other objects. Since you are not showing a sample document for the results returned by URLs, we cannot say if you did it beautifully.

Check out this presentation , it explains this topic, and also mentions some Spring library useful for implementing it.

+1
source

All Articles