Rest – validation error responses in REST API

apiapi-designerror messagesrestweb-api

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?

Best Answer

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.

Related Topic