2

I'm designing a RESTful API and wondering what's the best format for validation error messages.

For example, my account creation endpoint accepts a JSON object:

user: {
  first_name: string,
  last_name: string,
  address: {
    street: string,
    city: string,
    zip_code: string
  }
}

My responses will be in the following format:

{
    code: 400,  // HTTP code
    message: "Validation failed",  // general message
    type: "validation_failed",  // there are other types of errors as well
    errors: WHAT_DO_I_SHOW_HERE
}

I have several choices for validation error messages:

Format 1

errors: {
  last_name: "First name is required",
  address: {
    zip_code: "ZIP code is invalid"
  }
}

or flatten the errors as in Format 2

errors: {
  last_name: "First name is required",
  "address.city": "City is required",
  "address.zip_code": "ZIP code is invalid"
}

or use an array, where each element can have field name, error code, error message, nested errors, etc.

errors: [
  {
    field: "first_name",
    message: "First name is required",
  },
  {
    field: "address",
    errors: [
      {
        field: "zip_code",
        message: "ZIP code is invalid"
      }
    ]
  }
]

or

errors: [
  {
    field: "first_name",
    message: "First name is required",
  },
  {
    field: "address.zip_code",
    message: "ZIP code is invalid"
  }
]

Apparently the array format is more flexible since field name is optional, so it can accommodate errors related to a combination of multiple fields (e.g., end time of a time interval must be after the begin time). But my question is, which one would be easier for API users to consume?

4

You are trying to do too much in your api layer. Simply fail on the first validation error and return that message.

The consumer of your api should implement the full validation before calling the api and you should publish the validation rules to enable them to do this.

  • I'm actually developing an internal API. I'm trying to provide more info to make it easy for the front end developers. – sean hawk Oct 3 '16 at 12:41
  • But you are actualy making it harder. As they are forced to learn and integrate with your custom validation api rather than use an out of the box library – Ewan Oct 3 '16 at 13:05
1

As an API consumer, I would prefer the last option. Loop over the array, attach error messages to either the field (if name exists) or the general errors box (if it doesn't).

Nested arrays are a pain to code around, and the previous options are all limiting because they don't allow for form-level validation errors.

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.