I have a simple function that makes a cURL request to my RESTful API, and it returns data as it should when a successful request is made. My problem is, when a user perhaps gives the API wrong data or the API can't do what is requested, I don't know how to return error responses (e.g. 404s, 500s).
How would I go about doing this?
At the moment I have the following. In my API client
class Awesome_Api {
static function request($url, $data, $method)
{
// cURL stuffs here...
if (successful)
{
return (success response)
}
else
{
return (error response)
}
}
}
and
$response = Awesome_Api::request($url, $data, $method);
Now how do I return an error response code from the API, and handle it in the client end?
Use the header function to return error codes, like this:
header('HTTP/1.1 500 Internal Server Error');
or
header('HTTP/1.1 404 Not found');
It is very important that you make sure nothing has been written to the output before calling this function, otherwise it will not work as you expect.
In your client API, you can use the curl_error() and curl_errno() functions to retrieve information about the error number and message returned from the server.
Related
Basically, I was sending a AJAX request with an object with some missing JSON data, and I was wondering why I didn't get a status code and got no response data. The JSON is valid, but there are missing data that won't allow the code to successfully run.
So I tried it several times and the request never returned any data and there was no status code as if the server didn't respond and the request timed out. I tried with a correct JSON and it worked flawlessly (I got a 200 status and a proper server response)
public function getAssets($asset_id) {
try {
$response = $this->_services[$current_service]->get_random_asset($asset_id);
} catch (Exception $e) {
throw new Exception('Something is wrong: '.$e->getMessage(), 500);
}
}
I am not sure if this is correct, but I am guessing if I don't catch the thrown Exception by putting the function call of getAssets() in a try block or any function higher in the stack the server will not send any response and the request will timeout?
im developing an API with FlightPHP microframework and I can't set an HTTP response code for my routes.
I can set this and works perfectly:
header('HTTP/1.0 500 Error');
But I want use the native function http_response_code() from PHP. This one don't do anything.
I want to use this because that I don't have to manually type the error message.
To return a HTTP response code using Flight, you can do it like this :
Flight::route('GET /', function(){
Flight::json($data, $code = 500);
});
Where $data is the variable that leads to the array you want to send in json.
If $code is not set, then the default returned HTTP response code is "200".
https://github.com/mikecao/flight/blob/e25f023d4377a2b99b4be8bf7977f3fc0f8089c8/flight/Engine.php#L500
from flight php
Flight::json($data, [$code], [$encode], [$charset], [$option]) // Sends a JSON response.
Flight::jsonp($data, [$param], [$code], [$encode], [$charset], [$option]) // Sends a JSONP response.
I had a similar problem, to send my own headers, I do so:
$code = 404;
Flight->before('stop', function(&$params) use ($code) {
$params[0] = $code;
});
I'm working with the Classic Paypal API and I'm stuck on a problem of responding before I process the request data.
public function store() {
// Send an empty HTTP 200 OK response to acknowledge receipt of the notification
response("", 200);
// Build the required acknowledgement message out of the notification just received
// Once it hits this point, nothing is sent to the client.
}
I know that in order for the client to receive the HTTP 200 response, I will need to add the return keyword in front of it. However, if I return the response immediately, then the processing of the request will not occur. I looked into before and after middlewares, but unfortunately they are not asynchronous. Is there any way of accomplishing a send then process in Laravel 5?
I found a hack solution to this problem:
try {
return response("", 200);
} finally {
// Controller logic here
}
I found this, looks cleaner
response('Response', 200)->send();
// Continue with the script
// Don't forget to exit the script
I am building my own rest api in php for practice. I can evaluate the http code sent to my api (post,put,delete,get). But when I send out my response I really am just printing out a json. For example, I build a response in my api like this
public function actionTest()
{
$rtn=array("id":"3","name":"John");
print json_encode($rtn);
}
I am not manipulating the headers in anyway. From reading stackoverflow, I understand that I should be returning http response codes to match my api results. How can I build on my api and return the response codes. I just don't understand how I can do it because right now I am just printing out a json.
I am not asking which codes to return. I just want to know how to return codes in general.
You could re-think your code this way
public function actionTest()
{
try {
// Here: everything went ok. So before returning JSON, you can setup HTTP status code too
$rtn = array("id", "3", "name", "John");
http_response_code(200);
print json_encode($rtn);
}
catch (SomeException $ex) {
$rtn = array("id", "3", "error", "something wrong happened");
http_response_code(500);
print json_encode($rtn);
}
}
Basically, before stream the output (the JSON data), you can set the HTTP status code by http_response_code($code) function.
And about your additional question in comment, yes, printing the JSON data is the correct way.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using PHP curl how does one get the response body for a 400 response
When using PHP's curl_exec to call a RESTful API the documentation says http://php.net/manual/en/function.curl-exec.php
Returns TRUE on success or FALSE on failure. However, if the
CURLOPT_RETURNTRANSFER option is set, it will return the result on
success, FALSE on failure.
When curl_exec fails it returns false. However the remote server might have tried to return a helpful message to go with that error. How can we access this message using curl_exec, when it just returns false?
For example the remote API might be returning this message and a HTTP 400 status code:
{"Items":[{"Field":"FirstName","Description":"FirstName is required and cannot be null."}]}
Currently I am unable to read this error message that has been returned, instead all I get is false. I have looked at curl_info too. I do have returntransfer set on.
In C# I would use the exception.Response.GetResponseStream method and write:
private static string Post(WebClient client, string uri, string postData)
{
string response = string.Empty;
try
{
response = client.UploadString(uri, "POST", postData);
}
catch (WebException ex)
{
var stream = ex.Response.GetResponseStream(); // here
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
response = reader.ReadToEnd();
}
}
}
return response;
}
How can this be done in PHP? Is curl_exec the right method or should I use something else?
You should look at curl_error
http://www.php.net/manual/en/function.curl-error.php