How to get HTTP status answer from GuzzleHttp response by php Laravel? - php

I develop at php Laravel.
I receiving GuzzleHttp response from Mailgun as Object and can't to get from it the status.
the Object is:
O:8:"stdClass":2:{s:18:"http_response_body";O:8:"stdClass":2:{s:6:"member";O:8:"stdClass":4:{s:7:"address";s:24:"test_of_json-4#zapara.fr";s:4:"name";s:10:"not filled";s:10:"subscribed";b:1;s:4:"vars";O:8:"stdClass":0:{}}s:7:"message";s:36:"Mailing list member has been created";}s:18:"http_response_code";i:200;}
I need just last data pair:
"http_response_code";i:200;
to get it into variable, like:
$http_response_code = 200;
or even just its value.
To get string as I cited above I use
$result_ser = serialize($result);
but yet can't to extract value of variable.
Also I tried this:
$this->resultString .= \GuzzleHttp\json_decode($result_ser, true);
and get error.
Please, explain me , How to get/extract value I needed?

To take the response status code you can use the function getStatusCode :
$response = $client->request();
$statusCode = $response->getStatusCode();
while to take the body of response you can use :
$contents = $response->getBody()->getContents();

let's consider your request is something like
$response = $client->get("https://example.com");
if ( $object_res->getStatusCode() == 200 ) { // here you are checking your http status code
}
$object_res->getStatusCode() is the method to get http status code.
refer docs, there is simple example in this page.

I found that 'mailgun/mailgun' package uses its own HTTP client which also uses 'RestClient' and these classes are return stdObject.
In that Object there is property 'http_response_code' containing HTTP response code like 200, 400, 401 etc.
This property accessible by standard way $object->property and it's a solution of my query in this case.
For anybody who will read this question and answers I should to explain one thing that I not cleared in question.
I made request to the Mailgun API for subscribing member to mailing list. The API returns stdObject, not JSON or XML data.
But also there is one more strange thing - stdObject returned when request is successful only. If request fails you'll get just Exception thrown with message and without code. This forced me, if fail, to parse message body instead of get and resolve error code.

$responseObj->getStatusCode();

Related

getHeader from getInternalResponse in Symfony Panther always return an empty array

By using Symfony Panther, I sent a request and I wanted to get the response. I was able to get the body and the status code but for the header I just got an empty array.
$client = Client::createChromeClient();
$client->request('GET', 'https://google.com');
$client->getInternalResponse()->getHeaders(); // returned empty array!!!
Panther does not have access to the HTTP response as explained in this github issue https://github.com/symfony/panther/issues/17.
But if you read carefuly, you'll see that this is not a limitation of Panther but a limitation of Selenium WebDriver. See this post How to get HTTP Response Code using Selenium WebDriver.
This means that the answer to the question "Can I have access to the HTTP response code or the HTTP header using Symfony Panther?" is "No, it's not possible".
While this is not possible the workaround I found was to create an HttpClient and use it to make a request and get the response from it.
<?php
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::create();
$response = $client->request('GET', $this->myBaseUri);
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();
Here's the documentation for HTTP Client (Symfony Docs) if you want to try this way.
According to this issue: https://github.com/symfony/panther/issues/67, it seems that status code is not managed ( HTTP 200 will always get returned, no matter what the request actually responded.)
And same for the headers, I'm afraid. If you look at class
Symfony\Component\Panther\Client and method get($url) you can see that:
$this->internalResponse = new Response($this->webDriver->getPageSource());
while Response's constructor accepts:
public function __construct(string $content = '', int $status = 200, array $headers = [])
Having these said, no matter what happens, you always get HTTP 200 and empty header array.

Symfony json response is returning content twice

I have been writing an API using Symfony as the backend, a plugin written by a third party is sending certain data to an endpoint, the endpoint is then to return a json encoded response, however following the instructions as set out in the current symfony documaentation(https://symfony.com/doc/current/components/http_foundation.html) the return value is displayed twice and the response is not well formed and outputs like string
The original method that I wrote had calls to a database to validate a token, store a bookmark and display the result of the backend process, however when getting down to brass tacks and removing everything but the response building; it is obvious that this is where the problem lies. The method uses this snippet, though for clarity I have not included the database processing and used the posted values as the return array, the result is the same if it is the post or processed data, the output displays twice.
$token = $request->request->get('token');
$bookmark = $request->request->get('bookmark');
$data = ['token' => $token, 'bookmark' => $bookmark];
$response = new Response();
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->setContent(json_encode($data));
$response->send();
return $response;
What I was expecting was a single json response but what is returned is a double string of the json output
e.g. if I posted these values to the above snippet:
token: ksjdbvqpi8e7rqp7evbprb
bookmark: http://www.google.com
the return result is
{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}
when what I was expecting was just
{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}
I have no idea at the moment why it is displaying twice, any help is as always appreciated.
Thanks
$response->send(); is the line that should be removed.
As you already return object of class Response symfony will take care to output this response to browser, you don't need to do it manually with send().

Laravel forcing json response for api

I'm building an api at my company using laravel.
The problem I'm encountering is that if you send an api request without defining the correct header with the request you will get html back if there is a failure e.g. authorization failure or findOrFail() failure.
My thinking is that you never want to return html (even if the user has the wrong header).
I have a couple of solutions. In BeforeMiddleware.php I can manually insert a header into the request such as:
// Check if we are on an api route
$apiRoute = strncmp($uri, '/api/', 5) == 0;
// Insert the request header to force json response
if ($apiRoute){
$language = $request->header->add('Accept', 'application/json');
}
The 2nd solutions would be to throw an error if they don't have the correct header.
What would be the best way to enforce a json response, what is a good practice for handling api responses in laravel?
Once you detected that you are on your api path you are out of the woods and can indeed tackle your problem in the app\Exceptions\Handler.php file like suggested on How do you force a JSON response on every response in Laravel?.
For an open source project I created JSON exception objects by Microsoft format as output, but you can choose the jsonapi format (http://jsonapi.org/examples/#error-objects-basics) as you like:
https://github.com/StadGent/laravel_site_opening-hours/blob/develop/app/Exceptions/Handler.php
(note that on this implementation it is indeed depending from the headers, but you can use your path detection I think)

SoapClient call returns 500 Internal Server Error

I am trying to connect to an API using PHP and its built-in SoapClient. I have checked against the url I was given through the ill-formatted documents the client gave and $client->__getFunctions() returns a list of three functions. HelloWorld($name), which responds with Hello ~name~, shows me that I am communicating with the server through the SoapClient call and the URL is correct.
However, when I try to access one of the other methods that __getFunctions() gives me, even after copy/pasting the XML from the docs and putting in my own credentials, I am still being given an Internal Server Error faultstring and 500 as faultcode from the SoapFault object.
I am sure that it is my own XML string that is causing the issue but I cannot for the life of me figure out how. Reaching out to the API provider directly hasn't proven helpful. This is my first time dealing with Soap/Web Services so I am unsure of where to go from here.
I did wget http//xxx.xxx.xxx?wsdl and it returned me what looks like a valid XML response, the same one I get when I go directly to the url in the browser. What should I be looking into in order to solve this issue? All of the past API's I've dealt with have been JSON/RESTful so I feel out of my element trying to debug PHP errors.
Edit
I have slowly deleted parts of my method call and parts of my XML string, trying to trigger a different error or something in order to find what I need to fix. What I have found is that by not passing in my XML string, I get a valid response from the $client->FunctionCall(...). It's an "this isn't right" message but it's a message! In fact, passing that function ANYTHING for the xml parameter causes the 500 http faultcode/faultstring. Does this mean that my XMl is poorly formatted or does it mean that there is an issue on their end handling requests?
Second Edit
If I make my $client decleration as follows, I get the faultstring Could not connect to host
$opts = array(
'ssl' => array('ciphers'=>'RC4-SHA')
);
$client = new SoapClient($CREDS['orderingWSDL'], array (
"encoding"=>"ISO-8859-1",
'stream_context' => stream_context_create($opts),
'exceptions'=>true,
));
I am getting more confused the longer I try to fix this.
Sometimes a 500 status coming from a SOAP service could be a SoapFault exception being thrown. To help your troubleshooting, you'll want to be able to inspect both your request XML, and the response XML.
Put your code in try/catch blocks, and use $client->__getLastRequest() and $client->__getLastResponse() to inspect the actual XML.
Example:
$client = new SoapClient('http//xxx.xxx.xxx?wsdl', array('soap_version'=>SOAP_1_1,'trace' => 1,'exceptions' => true));
try {
$response = $client->someFunction();
var_dump($response);
} catch (Exception $e) {
var_dump($e->getMessage());
var_dump($client->__getLastRequest());
var_dump($client->__getLastResponse());
}

PHP Unirest plugin not working properly

I use Unirest for PHP to do some HTTP Requests. Everything works fine, until I want to pass a fairly complex JSON to my Node.js router.
First I do a GET request that returns a JSON Object, then I extend this JSON object (needs to be done, I know it sucks) and want to feed it back into my other http POST request... and here is where the trouble starts:
I echoed the JSON that is returned and copied the output into postman -> works fine. If I want use the JSON directly in PHP in next request:
$teamsMemberOf is the variable which is containing the GET response.
$headers = array("Accept" => "application/json");
$newBody = '{"team":'.$teamsMemberOf->raw_body.'}';
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/my/route/".$result['_id']."/get-something-from-server", $headers, $newBody);
and it doesn't work.
Error is 500 and 'Cannot read property '0' of undefined' which is certainly related to something in the JSON object.
Does someone have an idea how to fix it?

Categories