API Design – Should Error Codes in JSON Be Integers or Strings?

apidesign-patternserror messagesjsonprogramming practices

I'm designing a backend webservice, and when an error occurs I'm returning it as a JSON to the frontend. This JSON contains an error code, which the frontend maps to an localized string and shows that to the user.

Should my error codes be strings or integers?

{
  "error": {
    "code": 9900,
    "message": "Invalid ID"
  }
}

OR

{
  "error": {
    "code": "9900",
    "message": "Invalid ID"
  }
}

I'm thinking integers myself, but I'm just wondering if maybe returning fixed length error codes would be more correct, like if I atm have error codes like 9900, 9901, and in the future I wanna send the code 12, would it be correct to send them as "9900", "9901", and "0012", vs 9900, 9901, and 12.

Best Answer

I would go with text. It's OK to have a string where you only use numbers. As a rule of thumb: you should not use integers for things that are not mathematical in nature. That is, if you can do addition or multiplication on the values in a sensible way, then it's a number. Otherwise it's an identifier and you should stick with text. In practice you will probably be fine but using integer types to hold things that are not really numbers can end up being a problem. A classic example is using an integer to store zip-codes i.e. US postal codes.

Related Topic