What's the right HTTP error code if parsing the request fails - parsing

If you create a web service which receives an processes some data like XML/JSON and the parsing of the data fails because it's incorrect, what do you do?
Send a HTTP 400 error code: After all it was the client who messed up the data (XML/JSON)
Send a HTTP 500 error code: It's the server who wasn't able to complete its task

If data in the request is malformed, then you'll want to return a 400 level error. Generally 500-level errors mean that something is wrong on the server that has nothing to do with the client or the client's request.

422 code.
422 Unprocessable Entity
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
https://www.rfc-editor.org/rfc/rfc4918#section-11

Related

Mark successful siesta response as error

I'm working with a really strange (and nasty) API that I have no control over, and unfortunately when an invalid request is made, instead of responding with a 4xx status, it responds with a 200 status instead.
With this response, it also changes the response body from the usual XML response to plain text, but does not change the content type header. You can imagine how annoying this is!
I've got Siesta working with the API and the fact that it is no actually RESTful in the slightest, but I'm unsure how to get the next part working - handling the unsuccessful requests.
How do I go about transforming a technically valid and successful 200 response, into an error response? Right now I have the following setup:
configure("/endpoint") {
$0.mutateRequests { req in
... perform some mutation to request ...
}
$0.pipeline[.parsing].add(self.XMLTransformer)
}
configureTransformer("/endpoint") {
($0.content as APIResponse)
.data()
.map(Resource.init)
}
This is working just fine when the response actually is XML, however in the scenario where the response is an error, I receive the following:
bad api request: invalid api key
or something similar to this. The XMLParser class is already handling this, and in turn marks itself as having come across an error, however I don't know how to make Siesta realise that there is an error, and to not call my transformer but instead mark the request as failed to I can handle the error elsewhere.
How can I achieve what I'm after?
configureTransformer is just a common-case shortcut for the full-featured (but more verbose) arbitrary transformers Siesta’s pipeline supports. Full transformers can arbitrarily convert any response to any other, including success → failure and failure → success. The user guide discusses this a bit.
You can see this in action in the example project, which has a customer transformer that does something very similar to what you want, turning a 404 failure into a success with the content false. It is configured here and defined here. That example does a failure → success transformation, but you should find the code adaptable for your success → failure purposes.

YouTube API v3.0 CommentsThread.list proccessing failuer issue

When I send a comments thread. List request to the YouTube API
I get the following exception "But not for all videos":
Google.GoogleApiException: Google.Apis.Requests.RequestError
The API server failed to successfully process the request.
While this can be a transient error, it usually indicates that the requests input is invalid. Check the structure of the commentThread resource in the request body to ensure that it is valid. [400].
And for those videos I double checked the inputs sent with the request and I
make the request with the same data directly from the YouTube API requests trial section but everything goes right!
I want to know why this request becomes valid on some video ID's but invalid on the others ?
I'll appreciate any help.
Here is the full written log: System.AggregateException: One or more errors occurred. ---> Google.GoogleApiException: Google.Apis.Requests.RequestError
The API server failed to successfully process the request. While this can be a transient error, it usually indicates that the requests input is invalid. Check the structure of the commentThread resource in the request body to ensure that it is valid. [400]
Errors [
Message[The API server failed to successfully process the request. While this can be a transient error, it usually indicates that the requests input is invalid. Check the structure of the commentThread resource in the request body to ensure that it is valid.] Location[body - other] Reason[processingFailure] Domain[youtube.commentThread]
]
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
at Google.Apis.Requests.ClientServiceRequest`1.d__0.MoveNext() in c:\ApiaryDotnet\default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 0
--- End of inner exception stack trace ---
CommentThreads.list API doesn't need a request body as indicated in the API reference
Request body
Do not provide a request body when calling this method.
This may have caused the RequestError on your call. Try to remove any objects passed when calling this API, hopefully this would fix the issue.

Are all elements in a POST requests body mandatory?

If a POST request requires that i send four data elements in the body, like:
{
"name":abc,
"surname":xyz,
"contact_no":1234,
"address":random_value
}
What will happen if I miss out some of the elements, for example if I call the web service with elements like,
{
"name":abc,
"surname":xyz,
}
What error is the server likely to throw ? I am having this issue because I am making a API call and it's giving me a HTTP error 500, so I guess it's not an error on my part, but this is one doubt i wanted to clear. Thanks in advance.
Its depends on the service structure (if all fields are mandatory or not),
and HTTP error (500) returns to server error or (server or link) not found .

HTTP CODE = 409 errors

We are experiencing HTTP CODE = 409 error when we are trying to push our code to the repository. I tried with different IP address and it still doesn't work.
I wonder if there's something wrong with remote side.
Here is the message we got when pushing:
error: RPC failed; result=22, HTTP code = 409
fatal: The remote end hung up unexpectedly
fatal: recursion detected in die handler
Everything up-to-date
Check the Content-Type, like that one application/json. Attached link have a example:
http://blog.app4domain.com/2016/12/got-409-http-return-code-in-jboss.html
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Does every successful HTTP request always return status code 200?

In Delphi, I'm using Indy's TIdHTTPWebBrokerBridge coupled with TIdHTTP to send/receive data via HTTP. On the Server, I don't have any fancy handling, I always just respond with a simple content stream. If there's any issues, I only return information about that issue in the response content (such as authentication failed, invalid request, etc.). So, on the client side, can I assume that every successful request I make to this server will always have a response code of 200 (OK)?
I'm wondering because on the client, the requests are wrapped inside functions which return just a boolean for the success of the request.
Inside this function:
IdHTTP.Get(SomeURL, AStream);
Result:= IdHTTP.ResponseCode = 200;
This function handles any and every request which could possibly fetch data. If there were any issues in the request, This function should return False. In my scenario, since I always return some sort of content on the server, would the client always receive a response code of 200 in this function?
I guess the real question is, if I always return some sort of content and handle all exceptions on the server, then will the server always return status code of 200 to each request?
"Does every successful HTTP request always return status code 200?"
See w3.org: HTTP/1.1 Status Code Definitions (RFC 2616)
The answer is No. All 2xx are considered successful.
That may depend on the HTTP method used.
Should your web-server application always return 200 upon success? That may as well depend on the request method and the signal it intends for the client . e.g.
for PUT method (emphasis is mine):
If an existing resource is modified, either the 200 (OK) or 204 (No
Content) response codes SHOULD be sent to indicate successful
completion of the request.
for POST method:
The action performed by the POST method might not result in a resource
that can be identified by a URI. In this case, either 200 (OK) or 204
(No Content) is the appropriate response status, depending on whether
or not the response includes an entity that describes the result.
If a resource has been created on the origin server, the response
SHOULD be 201 (Created) and contain an entity which describes the
status of the request and refers to the new resource, and a Location
header (see section 14.30). Responses to this method are not
cacheable, unless the response includes appropriate Cache-Control or
Expires header fields. However, the 303 (See Other) response can be
used to direct the user agent to retrieve a cacheable resource.
As you can learn from the RCF, every method SHOULD have it's own success status codes, depending on the implementation.
Your other question:
"can I assume that every successful request I make to this server will always have a response code of 200 (OK)?"
You can always expect Status code 200, if your web server always responds with Status 200. Your web server application controls what response it returns to the client.
That said, Status code 200 is the Standard response for successful HTTP requests (The actual response will depend on the request method used), and in the real world of web servers, SHOULD be set as default upon successful request, unless told otherwise (As explained in Remy's answer).
To answer your specific question:
can I assume that every successful request I make to this server will always have a response code of 200 (OK)?
The answer is Yes, because TIdHTTPWebBrokerBridge wraps TIdHTTPServer, which always sets the default response code to 200 for every request, unless you overwrite it with a different value yourself, or have your server do something that implicitly replies with a different response code (like Redirect() which uses 302, or SmartServeFile() which uses 304), or encounter an error that causes TIdHTTPServer to assign a 4xx or 5xx error response code.
However, in general, what others have told you is true. On the client side, you should handle any possible HTTP success response code, not just 200 by itself. Don't make any assumptions about the server implementation.
In fact, TIdHTTP already handles that for you. If TIdHTTP encounters a response code that it considers to be an error code, it will raise an EIdHTTPProtocolException exception into your code. So if you don't get an exception, assume the response is successful. You don't need to check the response code manually.
If there is a particular response code that normally raises an exception but you do not want it to, you can specify that value in the optional AIgnoreReplies parameter of TIdHTTP.Get() or TIdHTTP.DoRequest(). Or, if you are are using an up-to-date Indy 10 SVN revision, a new hoNoProtocolErrorException flag was recently added to the TIdHTTP.HTTPOptions property so the EIdHTTPProtocolException exception is not raised for any response code.
Successful resposes are 2xx List_of_HTTP_status_codes
i did the following. Process straight all 200`s and LOG exceptions. worked, not a single non 200 - except unauthorized and timeouts (password or sometimes unavaliable server). but many/all responses will be considered for a wide range of mainstream apps.
while (iRedo < 3) do begin
s := Self.HTTPComponent.Get( sUrl );
if self.HTTPComponent.ResponseCode = 200 then begin
break;
end;
// IDEIA - log what happend if not 200
logWhatHappend( s, HTTPComponent ); // then log content, headers, etc
inc( iRedo ); sleep( 5 );
end;

Resources