REST API - HTTP status codes with multiple errors - php

I'm currently in the process of creating a small API. I have some error conditions, the 3 in question in this case are:
The user making a request with any method other than POST
The user not being authenticated
An entity not being found; resulting in no action being able to be made.
In that order. I had originally decided that I could assign a status code to each of these errors, (i.e. 400, 403, and 404, in that order) but then realised that I can't set multiple HTTP status codes.
How does one deal with this issue? Should I use HTTP status codes?

In my view it should check each of these conditions in the order you specified and return immediately with the corresponding error code if one of the conditions fail.
So only 1 error code will be returned.

It would be OK to use HTTP status codes, but it depends on who is consuming your API. Sometimes it is better to just return 200 OK and then include Error information in the body.
With Status Codes
If you go with status codes just return the first error encountered, no use in handling the request further anyways, so in pseudo:
if (request is not POST) return 405; //abort here
//we know request is POST here
if (request not auhtorized) return 401; //abort here
//we know request is POST and authorized
if (request requests a not exisiting entity) return [404, 422, ..., 5xx] either will do; // abort here
// we now know the request is POST, autorized and requests valid information
processRequest();
Without Status Codes
As an alternative, since you tagged ajax, I assume you are returning JSON, so just return 200 OK and include a the fields success : [true|false] and errorMessage : ["Not POST"|"Bad Auth"|"Bad Request or Unknown resource"|"OK"] in your JSON answer.
You could also combine both ways, but depending on the ajax client not all will work well with all status codes. Given the information in the answer, all you need to do is check if success === true and handle error otherwise.

Related

php http post response for web hook

I'm trying to create a web hook notification. The documentation of the service i want to use requires that i specify a URL where POST requests can be performed. This URL will receive the following object, in json format, and must respond with a Status Code between 200-299.
{
"type": "ping"
}
I don't know how to proceed making my server on localhost respond with a 200 status code. http_response_code(200) works well on live server but nothing seem to be happening on localhost.
Is there any way i can make it work with localhost?
I've included the link to the documentation here (i hope it's not against the rule).
I am thinking that you wouldn't have to send them the response. The webhook would know about the response. If it reached your URL successfully, it would be a 200 OK right off the bat. If the API is requesting a response back then I imagine that you would have to call it back somehow. Is this a well-known API? Any documentation?
The response code is in the response header, not in the content.
PHP defaults to a response code of 200, so if you don't mess with it at all, you should be good.
If you want to set a different response code (202 for example), just call:
http_response_code(202);
Or set the full header yourself:
header('HTTP/1.1 202 Accepted');
Proper way to explicitly set 200 (or any other) status code with http_response_code function is just as following (don't echo or json_encode it):
http_response_code(200);
It should force webserver to use 200 status code in it's response. However, webserver could possibly ignore it. To check what response code your webserver sends, use telnet or any REST tool like Postman

Catch POST response from API with 302 status

I am trying to catch POST response send to me by external API.
The problem is that POST array is completely empty while I can check in firebug that browser recieved it but with codes 302 FOUND and second (with same body) with code 307 TEMPORARY REDIRECT:
Is there any way to grab this data inside my script or is this something wrong with server re-directions?
If you are using the CURL library, there are two options that help with your case:
curl_setopt($curl,CURLOPT_HEADER,1);
This returns the response header including the status code. You can see whether 302 is returned.
Or you can simply follow the redirect
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
Edit: sorry just saw you were doing this on the client side.
If this is an AJAX call, you can get the status code in the raw XHR object.

what http status codes to accept

I'm using Curl to find out the status code of a website. This is in response to a user typing in a url in a form, basically I just want to check the url is valid, so I thought the best way would be to only allow certain codes which are likely to be ok. But this isn't working as well as expected. For EG tesco returns 503, Marks&Sparks a 405. So it seems like there could be a lot more status codes which are in fact ok but which don't seem like they should be ok to me.
So... my question is, what http status codes should I trust. Or should I be doing this the other way round and pass everything except some particular status codes?
For completeness and in case it helps anyone, here's how I'm getting the status code:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200 || $statusCode == 300 || $statusCode == 301 || $statusCode == 302 || $statusCode == 303 || $statusCode == 307 || $statusCode ==) {
$ret = true;
}
Check Existance of a url through CURL
Refer :http://www.php.net/manual/en/function.file-exists.php#74469
<?php
function url_exists($url) {
if (!$fp = curl_init($url)) return false;
return true;
}
?>
Some Status Code and References as per your doubt
200 OK
The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:
GET an entity corresponding to the requested resource is sent in the response;
HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;
POST an entity describing or containing the result of the action;
TRACE an entity containing the request message as received by the end server.
201 Created
The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field.
202 Accepted
The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.
203 Non-Authoritative Information
The returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy. The set presented MAY be a subset or superset of the original version. For example, including local annotation information about the resource might result in a superset of the metainformation known by the origin server. Use of this response code is not required and is only appropriate when the response would otherwise be 200 (OK).
204 No Content
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
205 Reset Content
The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action. The response MUST NOT include an entity.
Read This
http://www.seocentro.com/articles/apache/http-status-codes.html
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Pattern for responses from HTTP JSON API

I have a HTTP JSON API, which runs on php, on a small framework. This API is a wrapper for a databases pgsql functions.
Php framework returns responses in such way:
{
code: 200,
data: []
}
Codes are HTTP code responses (such as 200, 301, 302, etc). pgsql functions returns their own code (negative values for errors, positive for success results), message (meaning of code) and result data:
{
code: -1,
message: 'Wrong data',
data: []
}
So, my packages from API are:
{
code: 200,
data: {
code: 1
message: 'Succeed'
data: []
}
}
Isn't it messy?
Occur some confusions when writing client code, that requests this API.
Maybe there are some standard patterns for making some kind of packages of API.
Your API layout is not messy. As Botond suggested, it is actually pretty logical. The only change I would make to it would be to move your status codes into HTTP headers rather than in the JSON data, to reduce the format a bit. This will also allow you to easily differentiate between successful calls and errors.
Suppose your API can answer with 4 different codes: 200, 201, 403, 404. Respectively: done, not changed, forbidden, not found. Instead of passing this as a JSON variable, you could easily bind it into the HTTP response header, as the values already exist and are well understood. This, as in this question, is a pretty well-accepted method of providing status codes, provided that you are not using this specific header for anything else.
See you have to read the responses in Iterative manner. You can read the JSON response and then check if the data field has another object/array.
You have to assess the code and show error messages on all codes except 200.

When using Ajax with PHP, which of the following are necessary to verify success?

Which of the following answers are correct ?
HTTP ready state of TRUE
HTTP ready state of 4
HTTP status code < 400
HTTP status of 200
Data present in the response
both HTTP status of 200 and HTTP ready state of TRUE
In all my apps, I require only ready state 4 for success, which means as little as: the request is done and the response (if any) is available.
But like Madmartigan very wisely commented: define your version of success.
Usually, an HTTP ready state of 4 and HTTP status code of 200 is needed in order to guarantee that data has been successfully transferred back to your program.

Categories