REST API – Best Practices for Status Codes When Validating a Token

apiapi-designrestweb-api

I am working on client JavaScript SPA and a restful API on HTTPS.

Client application needs to call a public endpoint (no token required) in order to valid (GET) a specific TOKEN previously remember within the SPA application.

API returns:

  • If token is valid a status code 200 is returned and a json value {"isValid": "true"}:
  • If token is malformed a status code code 200 is returned and a json value {"isValid": "false"}:
  • If token is unauthorized a status code code 200 is returned and a json value {"isValid": "false"}

I would like to know:

  • Has the backed developer designed correctly API?
  • For malformed token should API return instead a generic 400 (“Bad Request”) and for 401 (“Unauthorized”) for token which is not unauthorized.

Please note: This question is not the just about status code, my concern is regarding the design of a public endpoint which provide information to client application where the endpoint does not require authentication using token.

Best Answer

This depends on the purpose of the API.

If the purpose is validation of tokens, then returning 200 OK for successful requests seems sensible. A 4xx error would mean the usage of the validation API is incorrect, not that the token is invalid.

Things are different if the token manages access to this API. In that case, you don't need an endpoint to check whether the token is valid. The backend should check the access token on every request. Then, when a request fails because the token is invalid, I would expect a Not Authorised response.

Remember that REST APIs use HTTP as a transport. The actual data of your API is not expressed on a HTTP level, but in the bodies of the requests and responses. The HTTP headers and status codes can be used for metadata, authentication, and out-of-band error messaging.

There is an analogy to programming languages here: An API call is similar to a method call. The response contains a return value – the response body. But if the HTTP response has a 4xx or 5xx status, that is as if the method had thrown an exception and did not return normally.

So, your token validation: should it return true/false as a result (a 200 response with a body containing that data), or should it either return nothing or throw an exception (2xx response vs. 4xx response)?