HTTP response for validation request - validation

I've got a service that validates names, that can be used to check whether a username is OK. It looks something like this:
POST http://names.myservice.com/validate
content-type: application/json
{"name": "Abdul Hideo McDodgycharacter¬§(*&^$%£!"}
=> 200 OK
{"errors": "contains invalid characters"}
So the point of the service is to check the validity of a proposed username, also checking in my db to see whether it's already been taken. My question is: should the response code be 400 (Bad Request) when there are validation errors?
If I was building a user API to create users, that's what I'd do when presented with Abdul here, but I'm not. In this case the request is for validation, the input data is acceptable, and the response contains the requested representation, which is a list of errors for the supplied data, so a 200 OK feels right. A 400 would indicate my validation request was malformed, and the data to be validated couldn't be identified.
I realise that this isn't very RESTful, because "validate" is basically a verb, so if there's another way to do this that solves my query, please suggest it!

If the request for validation was successful, then 200 (OK) is the correct response code. As far as endpoints, you can consider
POST /validated-names

Related

meaning of 'readbody' when when working with ruby http responses

What is readbody supposed to mean/indicate?
"#<Net::HTTPOK 200 OK readbody=true> "
"#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>"
source
I'm going to take a shot and guess that it means that they were able to read the body of the HTTP request.
There's the source code of the #read_body method in the link you provided.
https://github.com/ruby/ruby/blob/fe8cc13685a847f5b4b687d9edb88f5bee58fd70/lib/net/http/response.rb#L19
https://apidock.com/ruby/Net/HTTPResponse/read_body

How to return Http Status-Line with Error Response?

I am working on a Spring-Boot application. With each response I would like to return http Status-Line, Headers and Body. As per standards a Status-Line looks like: HTTP-Version SP Status-Code SP Reason-Phrase CRLF.
For Example: Http/1.1 400 Bad Request
I am using ResponseEntity with VnDErrors but Status-Line is not forming as per standards. I am able to see only "Http/1.1 400". Here Reason-Phrase is missing.
I have tried with #ResponseBody with #ResponseStatus annotation but no luck to achieve desired result.
Here is piece of code which I am using:
#ExceptionHandler(HttpRequestMethodNotSupportedException)
ResponseEntity<VndErrors> httpRequestMethodNotSupportedException(ex) {
LOGGER.error(ex.message)
ResponseEntity.status(BAD_REQUEST).contentType(VND_ERROR).body(new
VndErrors(BAD_REQUEST, exceptionMessage))
}
Expected reponse which conatins Status-Line: "Http/1.1 400 Bad Request"
Would like to know is this achievable? If yes, then how I can proceed to do same.
This is the standard behavior of tomcat see tomcat-8.5-changelog.html
spring-boot-issue-6789
RFC 7230 states that clients should ignore reason phrases in HTTP/1.1 response messages. Since the reason phrase is optional, Tomcat no longer sends it. As a result the system property org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER is no longer used and has been removed. (markt)

HTTP Status code and Response Body in HTTP POST for data validation

Let's suppose to have an HTTP POST that accept as input a JSON with some data and it must validate these data. The method should return also a validation message in the response body.
Ex.
{
"A" : 1,
"B" : 1,
"C" : 3
}
Suppose to have some validation rules defined over the JSON, for example (A + B) should be less than C parameter.
I have some doubts about the HTTP status code.
If the JSON is valid the HTTP POST should returns 200
If the JSON is not valid (missing parameters or wrong types) the HTTP POST should returns 400
But in case the JSON is valid (there are all the requested parameters and the types are correct) but the parameters don't respect the defined rules (A + B < C) what should be the HTTP Status?
200 and than an explanation in the response body?
400 and the explanation in the response body?
Is there the need to differentiate the HTTP Status from the Validation rules Status?
Cheers
That's what status code 422 ("Unprocessable Entity") has been designed for.
See https://www.greenbytes.de/tech/webdav/rfc4918.html#STATUS_422.
It all depends on the use-case / functionality you want to achieve.
If you want to make it easy for others to work with valid messages, I would perhaps return 2xx only if the message is completely valid, and in all other cases return 4xx. In this case the caller does not need to parse the result, which makes it easy to work with.
If the use-case is to provide some analytic service that others will use to analyze messages, not specifically to use the message itself, then I would return 2xx with the result of the analysis unless the message can not be parsed (not a json for example), in which case 4xx is warranted.
your response need to be 400 with the follwing message: "Bad Request: parameters don't respect the rules".
400 error

Example Content-Types for `POST` validation failures?

Suppose an HTTP server responds to a POST with a 400 response code because the request failed validation (e.g. email address not found). If the server wishes to provide more information to the client about the nature of the error, how should this be returned? For each possible content type used in requests, should there ideally be an associated "error" content type?
For example, given the request
POST /users
Content-Type: application/x-myuser
{
"email": "foo#example.com",
"name": "Michael"
}
a response might be
400 Bad Request
Content-Type: application/x-myuser-error
{
"email": "Email address foo#example.com not found"
}
Are there any good examples of "error" content types publicly available?
I don't have any examples, but it's good to always keep these in mind:
Always include a machine-readable error, and generalize as much as possible. A JSON structure like
{"error":"Email address not found!","code":"fielderror","field":"email","reason":"notfound"} (could be simplified to {"error":"...","code":"emailnotfound"})
allows API developers to properly present the error to the user (and act on the error) while it allows you to change the messages without breaking applications. It also really helps with translation of error messages, both on your end and the external developer's end.
A different approach is to simply don't return any body, and use HTTP headers to tell the user agent what went wrong. For example, you could use X-Error and X-Error-Code to show a human readable error, and a machine readable code.
Creating too many content types might be a bad thing. I personally prefer to always use application/json and let the user agent know the status by looking at the HTTP codes: 200, 400, 403, 404, 500, etc.
Definitely don't ever start making combinations of HTTP codes and content types. You don't want your users to have to learn that application/myapp/error means there's an error, UNLESS it's 200 in which case you're in the edit screen, OR when it's 302 it's not actually an error but a redirect. This is why you should probably stick with one content type.
Bottom line: always keep it simple. Make sure that there's one field which you have to look at, not two or three, when detecting a status. Once the user agent has determined the status it could choose to look at some other fields for extra info, but only after it has determined that something went wrong. Including a separate content type probably won't help there.

Custom http codes

Could I use custom HTTP codes?
I want to use these codes as response for AJAX requests.
Example:
220 - will be correspond to status that some item was created successfully
420 - will be correspond to status that some validations errors were occurred
Each response will be has json string.
You can define extension codes, but it only makes sense if you want to standardize something; in which case you need to write a spec, and get the status code registered (see http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-12.html#rfc.section.4.1).
If this is just between your server and your client, simply put the additional information into the response body and use a more generic status code.
That being said -- what you called "420" is already defined as "422 Unprocessable Entity".
Using your server side language of choice you can send headers to the browser with the relevant HTTP code and message.

Resources