Skip to content

#100_REST_API_error_best_practice

Andrew edited this page May 1, 2019 · 1 revision

Spike Number: Issue 100

Spike Title: REST API Error Best Practice

Andrew Davis
1/5/19

Goals / Deliverables

A small report on different REST API error codes and when to use which.

Technologies, Tools and Resources Used

REST API Best Practices blog post Mozilla HTTP Status Code docs Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content RFC 7231

Error codes and when to use them:

4xx Client Error

400 Bad Request
Response based on the request having bad/incorrect syntax. An example response would be text if a page response is expected. If JSON is expected return some json to explain the error eg.
{"errors":[{"code":123,"message":"Data was invalid."}]}

401 Unauthorized
Use when the route is available but the request didn't include information identification, eg the API key submitted is unknown to the system.

403 Forbidden
Known identification was submitted in the request but that user doesn't have the rights to access the resource.

404 Not Found
The server doesn't recognize the route in the URL. Most REST APIs libraries/packages will automatically return a 404 on a route not described.

405 Method Not Allowed
The route exists but the HTTP method listed in the request isn't allowed. For example a route may accept a GET, or POST request but not a DELETE. The reply should contain a list of the available methods for that route.

5xx Server Error

500 Internal Server Error
A catch all for a non-descript error. If the server is unable to determine what went wrong it should return 500.
Eg Something causes an exception to be fired, at the top level catch is a way to return error 500.

503 Service unavailable
Server is unable to handle the request. Typically the response is a page explaining the problem. If the response is JSON then some JSON to explain the problem.
Eg if an API gateway can't fulfill a request due to X_service being unreachable it should return "Error 503 unable to reach X_service" to better help the debugging cause.

Clone this wiki locally