Wednesday, November 21, 2018

HTTP Response Codes and REST Service Responses

Had an interesting IM exchange today regarding a REST service GET URI performing a database look up for user account information by email address and what HTTP response codes are appropriate for different response conditions.

The simple, successful "Here's the user info for that address" is easy-- HTTP 200 OK with the user info in a JSON payload. What about the other possibilities though?

The question prompting the conversation was "What happens when the email address isn't tied to any user? Is that a 404?" My assertion was no, a 404 means something else and there's a better existing HTTP response code.

This got me thinking about different scenarios and what HTTP response codes are appropriate for a simple GET request. Just as a red stoplight isn't an error, several different response conditions can and should result in different response codes with documented meanings.

Here's my list:

200 OK - Success, body payload contains current response payload
204 No Content - Success but nothing found matching your request, no body payload
301 Moved Permanently - Deprecated URI used, Correct current URI given in the Location response header, body payload contains response appropriate for the deprecated URI
400 Bad Request - Unsuccessful, bad email address format, no body payload
401 Unauthorized - Unsuccessful, incorrect/invalid authentication provided or missing, no body payload
404 Not Found - Unsuccessful, incorrect/invalid URI used, no body payload
410 Gone - Unsuccessful, unsupported old URI used, no body payload
500 Internal Server Error - Unsuccessful, server error, including web service processing issue and any database issues
503 Service Unavailable - Unsuccessful, server overloaded or under maintenance, no body payload

That's a lot of work for one GET call, just scratching the surface for versioned APIs. Even those don't cover gateways, proxies, or different HTTP verbs. Worst of all, they're are just my opinion.

My answer then to the original question is HTTP 204 No Content for a valid, successful email address lookup not tied to a user, i.e. the equivalent HTTP response code for a successful database query returning an empty result set.

What do you think? Are there others missing for a simple GET service URI? Do you use one or more of these response codes in a different way?