We know to return a 200 OK when things are good, but there are some differences of opinions as to when to return other HTTP codes.
A 200 OK should come back when a collection or a resource responds as expected
A query like /collection?filter=something that returns no records should still return a 200 OK - the collection exists, which is OK, but the response should indicate that there are no elements.
We use this rather than a 204 No Content to provide a consistent experience to the App developer and to allow the API to return meta data if necessary about why no content was returned.
The body response of a 201 Created should be the same as the response of a GET - if there is any orchestration involved in the GET response (such as calculated fields or a a mashup of two resources to give a more detailed response) that same orchestration should be performed on the 201 Created response to a POST or PUT as it would be performed on a 200 OK GET response.
If you move an item, or merge it with another, the response should use 303 See other (as opposed to 301 Moved Permanently or 302 Found). The payload should then contain information about where to find the new content.
HTTP/1.1 303 See Other
Date: Mon, 01 Jan 2018 18:40:26 GMT
"timestamp" : 1514832028,
"status" : 303,
"error" : "See Other",
"exception" : "org.myco.profile.SeeOtherPersonException",
"message" : "See Other - 0f52e80c-4fc5-11e8-9c2d-fa7ae01bbebc",
"path" : "/email@example.com"
Say I get confused and I look for itemIdentifier instead of itemId, you should return an error message, 400 Bad Request because the handler doesn't know anything about itemIdentifier
"error": "Bad Request",
"message": "query parameter itemIdentifier is not recognized",
If you can get as detailed as to actually say what wasn't recognized, great, but at a minimum, throw the 400 and "one or more query parameters is not recognized"
Technically, if bad credentials are offered, you should return a 401 Unauthorized but when valid credentials are presented for a resource that you aren't allowed to access, you should return a 403 Forbidden. This makes it easier for the application developer to understand why they are getting the error (bad keys vs bad request).
If you are unable to return a contextual 401 vs 403, you should default to the 403.
The 404 response should be presented when the resource simply does not exist. This allows the consumer of the API to differentiate between trying to access something they aren't allowed to see (403) versus having simply misspelled something.
If the API requires the consumer to submit a unique identifier (such as an email address in a User Store) and that identifier exists, the response should be 409 Conflict as in
"message": "This email address already exist: firstname.lastname@example.org",
Be sure to see my blog over at Cloudenity. This week's topic:
Identity Isn't Just for Users Anymore