When designing a RESTful API that uses JSON to respond to requests, I usually return an object like this when an error happens:

  "error": "Something bad happened",
  "error_code": "XXX"

Do I need to have a "error": "" or "error": null in my object when there is no error?


If the response is a success, don't include error in your response. Example:

GET /product/15406/

200 OK
    "id": 15406,
    "name": "A cookie with pieces of chocolate",
    "price": 1.45,
    "is-available": true

On the other hand, an error would look like:

GET /product/nan/

403 Forbidden
    "error": 5020,
    "error-message": "The specified product identifier cannot be converted to a number."


  • Do change the HTTP status code on error. Returning 200 OK when something got wrong is silly.

  • Don't include error fields in the success response. Why would you? You aren't including price or is-available in the erroneous response, are you?

  • Do use strings for text and numbers for numbers. Your "error_code": "XXX" looks like you are putting a number as an error code, but passing it as a string. If it's a number, it should remain a number in the response. Note that using strings as error codes may be a good solution: error 5020 is not extremely explicit; error "InvalidProductIdentifier" is.

| improve this answer | |
  • The "403 Forbidden" status looks somewhat weird, but HTTP does not have status for invalid parameter, so you can only use "403 Forbidden" or "404 Not Found". – Jan Hudec Aug 1 '13 at 7:52
  • @JanHudec: actually the 403 here is wrong. For bad parameters you should use "400 Bad Request". – vartec Aug 1 '13 at 9:11
  • @vartec: I understand "Bad Request" as not being correct HTTP or having invalid HTTP headers, which is not the case here. So I think either 404 (because it does not point to valid resource, whether because the format is wrong or because the particular id does not exist being secondary) or 403 (the server states it refuses to talk to about URL not matching the specified format). – Jan Hudec Aug 1 '13 at 9:19
  • @vartec: from what I've seen, APIs tend to use 403 in many cases (including wrong parameters). IMO, it doesn't really matter which one among 400, 403 or 404 is used, as long as the API is consistent. – Arseni Mourzenko Aug 1 '13 at 9:23
  • 1
    @JanHudec: 400 is any bad request, doesn't matter if it's malformed HTTP, a syntax error or just request that doesn't pass the validation. Using 400 in this case is for example the standard way as described in the "RESTful Web Services" book – vartec Aug 1 '13 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.