Storing response from PHP Guzzle as JSON in database (Laravel) - php

Im calling a vehicle data API at an endpoint and can return the data fine using:
$client = new Client();
$url = "https://uk1.ukvehicledata.co.uk/api/MISC DETAILS;
$result = $client->get($url);
return $result->request;
This is using mock data so the response is:
{
"Request":{
"RequestGuid":"",
"PackageId":""
"Response":{
// VEHICLE DATA
}
}
However, I now wish to store the response in the database but cannot access ->request or ->Request etc.
Using:
return json_encode( (array)$result );
Actually returns the headers from Guzzle and no response data.
Any help?

You have to convert the body into JSON first:
$jsonArray = json_decode($result->getBody()->getContents(), true);
echo $jsonArray['Request']['RequestGuid'];

Related

How to parse API response correctly

My Problem is relatively simple:
I make an API call and get the following answer in response:
[{"RowKey":24764}]
The Content-Type I'm receiving is text/html
Somehow, I'm just not able to parse this correctly. neither json_encodeor json_decodeseems to help.
I'm trying to Map the object into my response class:
class ApiResponse {
public $schedules = [];
}
with the json object mapper from: https://github.com/mintware-de/json-object-mapper
Consider this test case:
$response = '[{"RowKey":24764}]';
$result = json_decode($response, true);
echo $result[0]['RowKey']; // Output: 24764

Accessing a URL stored in a variable from a controller

I am in a confusing situation
In my Laravel controller, I have a variable
public function storeName($key)
$store = new Store();
$storeName = $store->connectAPI($key);
This $storeName variable will actually give me a URL, which if accessed, will give me a JSON response.
If I die and dump $storeName variable it will print
http://store123.com?key=2093983892
But, what I actually want is to access this $storeName variable, by passing a GET request in my controller, so I can get a JSON response from this API call.
How can I access this URL in my controller?
From Guzzle docs
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', []);
if($res->getStatusCode())
{
// "200"
$json = $res->getBody();
}
I used json_decode inside a curl_init function to solve this issue.

Accessing specific properties from Guzzle response?

I'm using Guzzle to get an HTTP response. If I do this:
$response = $res->getBody();
I get an object with 'email' as one of the properties. But if I do either:
$email = $res->getBody()->email;
or
$email = $response->email
I get a 'No value for email' error. What am I missing?? How can I access a specific property in the response object?
The getBody method returns an instance of StreamInterface. You first need to retrieve the contents of the response:
$response = (string) $res->getBody();
Only then you can decode the json payload:
$json = json_decode($response);
$email = $json->email;

Send raw json HTTP request for an API call in Yii 1.x.x

I asked a similar question earlier, in a nutshell I have an API application that takes json requests and outputs an json response.
For instance here is one of the requests that I need to test out, how can I use this json object with my testing to emulate a 'real request'
{
"request" : {
"model" : {
"code" : "PR92DK1Z"
}
}
The response is straightforward (this bit has been done).
From other users on here this is the optimised method using Yii to do this, I am just unsure how to emulate the json request - e.g essentially send a JSON HTTP request, can anyone assist on how to do this?
public function actionMyRequest() {
// somehow add my json request...
$requestBody = Yii::app()->request->getRawBody();
$parsedRequest = CJSON::decode($requestBody);
$code = $parsedRequest["request"]["model"]["code"];
}
I don't understand if you want your app to send an http request and get the result or at the opposite receive a http request
I answered for the first assumption, I'll change my answer if you want the other
For me the best way to send an HTTP request is to use Guzzle http client.
This is not a yii extension, but you can use third party libraries with yii.
Here's an example from Guzzle page:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();
So in your case you could do something like:
public function actionMyRequest() {
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.your-url.com/');
$requestBody = $res->getBody();
$parsedRequest = CJSON::decode($requestBody);
$code = $parsedRequest["request"]["model"]["code"];
}

Is it possible to parse JSON with Goutte?

I'm working on crawling web sites and there is no problem for parsing HTML with Goutte so far. But I need to retrieve JSON from a web site and because of the cookie management, I don't want to do this with file_get_contents() - that doesn't work.
I can do with pure cURL but in this case I just want to use Goutte and don't want to use any other library.
So is there any method that I can parse only text via Goutte or do I really have to do this with good old methods?
/* Sample Code */
$client = new Client();
$crawler = $client->request('foo');
$crawler = $crawler->filter('bar'); // of course not working
Thank you.
After very deep search inside Goutte libraries I found a way and I wanted to share. Because Goutte is really powerful library but there are so complicated documentation.
Parsing JSON via (Goutte > Guzzle)
Just get needed output page and store json into an array.
$client = new Client(); // Goutte Client
$request = $client->getClient()->createRequest('GET', 'http://***.json');
/* getClient() for taking Guzzle Client */
$response = $request->send(); // Send created request to server
$data = $response->json(); // Returns PHP Array
Parsing JSON with Cookies via (Goutte + Guzzle) - For authentication
Send request one of the page of the site (main page looks better) to get cookies and then use these cookies for authentication.
$client = new Client(); // Goutte Client
$crawler = $client->request("GET", "http://foo.bar");
/* Send request directly and get whole data. It includes cookies from server and
it automatically stored in Goutte Client object */
$request = $client->getClient()->createRequest('GET', 'http://foo.bar/baz.json');
/* getClient() for taking Guzzle Client */
$cookies = $client->getRequest()->getCookies();
foreach ($cookies as $key => $value) {
$request->addCookie($key, $value);
}
/* Get cookies from Goutte Client and add to cookies in Guzzle request */
$response = $request->send(); // Send created request to server
$data = $response->json(); // Returns PHP Array
I hope it helps. Because I almost spend 3 days to understand Gouttle and it's components.
I figured this out after several hours of search , simply do this :
$client = new Client(); // Goutte Client
$crawler = $client->request("GET", "http://foo.bar");
$jsonData = $crawler->text();
mithataydogmus' solution didn't work for me. I created a new class "BetterClient":
use Goutte\Client as GoutteClient;
class BetterClient extends GoutteClient
{
private $guzzleResponse;
public function getGuzzleResponse() {
return $this->guzzleResponse;
}
protected function createResponse($response)
{
$this->guzzleResponse = $response;
return parent::createResponse($response);
}
}
Usage:
$client = new BetterClient();
$request = $client->request('GET', $url);
$data = $client->getGuzzleResponse()->json();
I also could get JSON with:
$client->getResponse()->getContent()->getContents()

Categories