Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful service, how to respond if validation failed?

Tags:

rest

http

I have service that takes some entity and needs to save/update this entity:

http://myhost.com/rest/entity

I use POST and submit JSON. Inside service it detects that entity passed is not good. Not valid, order passed in with customer that doesn not exist, etc.

How should I reply? HttpCode.NotFound? Or others? How do you reply to such things?

like image 955
katit Avatar asked Jan 20 '12 15:01

katit


People also ask

What HTTP response status do you return for validation errors?

In most cases Eloqua's APIs will respond to requests with the standard HTTP status code definitions. If the API fails to validate a request, it will respond with a validation error message (JSON or XML) describing the issue. 400: "There was a parsing error."

What is API validation failed?

If the API fails to validate a request, it will respond with a 400 validation error message (JSON or XML) describing the issue. The below validation errors are the most common and will respond with some details, including a list of validation messages.

How do I validate a status code in REST API?

We can read the status code using the getStatusCode() method. Similarly, we can read the status line using the getStatusLine () method of the response interface. Once the status is read, then we can verify if the code is a success (200) or any other code.


2 Answers

422 Unprocessable Entity, defined in WebDAV (RFC 4918):

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

like image 183
Julian Reschke Avatar answered Sep 17 '22 16:09

Julian Reschke


In our project in such situations we do the following:

  1. Set response code to HTTP 400 Bad Request
  2. Set response body to the following JSON: {"message":"%extended error message here%"}

But it's really very subjective.

Also I'd suggest reading This blog article on RESTfull error handling - it describes many available options, so you can choose something for your taste.

like image 42
Sergey Kudriavtsev Avatar answered Sep 17 '22 16:09

Sergey Kudriavtsev