3

I'm currently in the process of creating a small API. I have some error conditions, the 3 in question in this case are:

  1. The user making a request with any method other than POST
  2. The user not being authenticated
  3. An entity not being found; resulting in no action being able to be made.

In that order. I had originally decided that I could assign a status code to each of these errors, (i.e. 400, 403, and 404, in that order) but then realised that I can't set multiple HTTP status codes.

How does one deal with this issue? Should I use HTTP status codes?

2 Answers 2

3

In my view it should check each of these conditions in the order you specified and return immediately with the corresponding error code if one of the conditions fail.

So only 1 error code will be returned.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd actually switch the order of 1 and 2. You should never reveal more information of a system than is necessary. Another solution, since it's an API, would be to set the status code to 200 and return an error description explaining exactly what went wrong
Good point @SaniHuttunen. Neal, this is the approach I have ended up going for.
2

It would be OK to use HTTP status codes, but it depends on who is consuming your API. Sometimes it is better to just return 200 OK and then include Error information in the body.

With Status Codes

If you go with status codes just return the first error encountered, no use in handling the request further anyways, so in pseudo:

if (request is not POST) return 405; //abort here
//we know request is POST here
if (request not auhtorized) return 401; //abort here
//we know request is POST and authorized
if (request requests a not exisiting entity) return [404, 422, ..., 5xx] either will do; // abort here
// we now know the request is POST, autorized and requests valid information
processRequest();

Without Status Codes

As an alternative, since you tagged ajax, I assume you are returning JSON, so just return 200 OK and include a the fields success : [true|false] and errorMessage : ["Not POST"|"Bad Auth"|"Bad Request or Unknown resource"|"OK"] in your JSON answer.

You could also combine both ways, but depending on the ajax client not all will work well with all status codes. Given the information in the answer, all you need to do is check if success === true and handle error otherwise.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.