Skip to content

Instantly share code, notes, and snippets.

@MajorBreakfast
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MajorBreakfast/8884211 to your computer and use it in GitHub Desktop.
Save MajorBreakfast/8884211 to your computer and use it in GitHub Desktop.
API Errors

If a request fails the server SHOULD answer with an error which is stored in the "error" property. The simplest form ist just a string with the type of the error:

{
  "error": "csrfTokenInvalid"
}

Error types SHOULD be in camelCase starting with a lowercase letter and SHOULD NOT end with "Error".

The more elaborate form is providing an error object. Error objects MUST hold a "type" property with the type of the error:

{
  "error": {
    "type": "selfDestructionCannotBeAborted",
    "secondsUntilDetonation": 300
  }
}

You SHOULD NOT include a "message" property containing a string with an explanation. If further information is needed, it SHOULD be conveyed using JSON fields (facilitates i18n).

Validation errors

Validation errors are probably the most common type of error occuring in APIs. As such it makes sense to standardize them further.

{
  "error": {
    "type": "validation",
    "violations": [
      { "path": "users/0/email", "rule": "required" },
      { "path": "users/0/email", "rule": "email" },
      { "path": "users/0/password", "rule": "length", "min": 8 },
      { "path": ["users/0/city",
                 "users/0/zipCode"], "rule": "zipCodeMatch" }
    ]
  }
}

Validation errors SHOULD adhere to the following structure. In order to conform they...

  • MUST be of type "validation"
  • MUST have a "violations" array that contains an object for each violation.
  • Each violation object...
    • MUST contain a "rule" property that contains the name of the broken rule
    • SHOULD contain an "path" property...
      • with the name of the affected field as string, or
      • with the names of the affected fields as array with strings
    • CAN include parameters for the rule
@MajorBreakfast
Copy link
Author

Changed "at" to "path" to bring it in line with the JSON patch standard.

@bendrucker
Copy link

This looks good to me

@MajorBreakfast
Copy link
Author

@bendrucker Take a look at json-api/json-api#7. The json-api spec is currently in the works and already quite awesome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment