Lothre1
Lothre1

Reputation: 3853

REST response patterns on basic CRUD operations?

What are the REST response patterns on basic CRUD operations?

If I want to insert a new entry into a particular resource I just send a POST with the necessary data in JSON to the server. The server responds with { 'id': xx } where xx is the id of the new entry. The same goes for successful update requests.

On failure I always send a 404 with a json object having an idError and a description like below.

{idError:'100', errorDesc: 'SQL error'}
{idError:'101', errorDesc: 'Missing resource identifier'}

But because I'm not aware of any pattern i would like to get some tips on how to properly return the json on failure and if it is a good practice of setting up the HTTP statuscode along with the response.

Upvotes: 1

Views: 2956

Answers (2)

Kiren S
Kiren S

Reputation: 3097

You can stick with any standard like JSON API.

Abstract from their site:

If you’ve ever argued with your team about the way your JSON responses should be formatted, JSON:API can help you stop the bikeshedding and focus on what matters: your application

Check this for the spec https://jsonapi.org/format/

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

On success you should use the 200 status codes (as you seem to be doing):

  • 200 -- Generic success. Returns content. You should use this for update and get operations.
  • 201 -- Created. Use this for post. Return the created resource.
  • 204 -- Success. No content is returned. You can use this with delete, but if you want to return something (such as the resouce that was deleted) use 200.

If you are going to process the data later, use 202. It's unlikely that you will use this, but just be aware of it.


The error status you want to use depends on the type of error. 400 is client error such as them sending you the wrong information. 500 is server error -- an error on your end.

You probably won't use 404 since this means that the resource is not found. If the error is due to an invalid input you should use 400 -- bad request. Be aware of the HTTP status codes, and try to use the appropriate one.

Upvotes: 6

Related Questions