Guzzle with Laravel 9 - php

I'm working on Lavravel 9 with guzzle to send some data in
the below code need to get some data from the database how can get data from the database?.
$response = Http::post('APIurl', [
"headers" => [
//header information
],
"body" => [
'title' => "**Get data from database**",
'body' => "**Get data from database**,
'userId' => 22
],
]);
Thank you

Assuming your API returns a json result, simply call the json() method on the Response object. If you want the raw response body, use body() instead.
For example, take github's api:
$response = Http::get('api.github.com'); // replace with your call
$body = $response->body(); // returns string
$json = $response->json(); // tries to return a json array.
To add data to your request, try passing a json string in the body.
$data = json_encode([
'title' => ...,
'body' => ...,
'user_id' => ...,
]);
$response = Http::post('your-api-here', [
'headers' => [
...
],
'body' => $data,
]);

Related

Trying to use Laravel HTTP to upload a file to a 3rd party

I have the following Postman request for testing a third party API;
What I am trying to do is convert this into code using Laravel's HTTP class, the code i currently have is;
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true,
'frontfile' => Storage::get('somefrontfile.jpg'),
'sideview' => Storage::get('itsasideview.png'),
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->asForm()
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
But every time I run this, the 3rd party API comes back with Invalid ID, even though if i use Postman with the same ID it works fine.
I cant seem to figure out where i am going wrong with my code;
As #Cbroe mention about attach file before sending post request you can make this like this example:
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->attach(
'frontfile', file_get_contents(storage_path('somefrontfile.jpg')), 'somefrontfile.jpg'
)
->attach(
'sideview', file_get_contents(storage_path('itsasideview.png')), 'itsasideview.jpg'
)
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
Also i think you need remove asForm method because it's override your header accept type to application/x-www-form-urlencoded that is way your exception is Invalid ID
Some third party API would require you to have the request with content type as multipart/form data
you can double check all the headers being pass on your postman request HEADERS tab and view on Hidden headers.
If you indeed need your request to be in multipart/form-data, You can use the multipart options of guzzle.
Although this doesnt seem to be on Laravel HTTP-Client docs, you can simply pass a asMultipart() method in your HTTP request
just check the /vendor/laravel/framework/src/Illuminate/Support/Facades/Http.php for full reference of HTTP client.
You can have your request like this.
public function uploadToThridParty() {
$uploadContents = [
[
'name' => 'id',
'contents' => 'this-is-my-id'
],
[
'name' => 'fileUpload',
'contents' => true
],
[
'name' => 'frontfile',
'contents' => fopen( Storage::path( 'somefrontfile.jpg' ), 'r')
],
[
'name' => 'sideview',
'contents' => fopen( Storage::path( 'itsasideview.jpg' ), 'r')
],
];
$request = Http::withHeaders(['Accept' => 'application/json']);
$response = $request->asMultipart()->post('https://urltoupload.com/upload', $uploadContents );
}

Guzzle: Sending POST with Nested JSON to an API

I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:
{
"startCountryCode": "CH"
"endCountryCode": "US",
"products": {
"quantity": 1,
"vid": x //Variable ID
}
}
Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate
$body = [
"endCountryCode" => "US",
"startCountryCode" => "CN",
"products" => [
'vid' => $vid,
'quantity' => 1
],
];
$request = $this->client->request(
'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
[
'headers' => [
'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
],
'body' => json_encode( $body )
],
);
I've also tried using 'json' => $body instead of the 'body' parameter.
I am getting 400 Bad Request error.
Any ideas?
Try to give body like this.
"json" => json_encode($body)
I spent so many hours on this to just realise that products is actually expecting array of objects. I've been sending just a one-dimensional array and that was causing the 'Bad Request' error.
In order to fix this, just encapsulate 'vid' and 'quantity' into an array and voila!
You don't need to convert data in json format, Guzzle take care of that.
Also you can use post() method of Guzzle library to achieve same result of request. Here is exaple...
$client = new Client();
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array("endCountryCode" => "US", "startCountryCode" => "CN", "products" => array("vid" => $vid, "quantity" => 1));
$response = $client->post('https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate', $params);

Receive data in Json in PHP

I am posting data to my script file to receive data. In my script file, File.php, I am not able to get the object patient in the dumped results. When i do var_dump($get_patient_info->patient);,
it throws an error saying Object {patient} not found.
Could i be mapping the data wrongly?
PS: Beginner in Laravel
SendingData Controller
$hospitalData = [];
$hospitalData[] = [
'patient' => 'Mohammed Shammar',
'number' => '34',
],
$url = "https://example.com/file.php";
$client = new Client();
$request = $client->post($url, [
'multipart' => [
[
'name' => 'patient_info',
'contents' => json_encode($hospitalData),
],
],
]);
$response = $request->getBody();
return $response;
File.php
$get_patient_info = $_POST['patient_info'];
var_dump($get_patient_info);
Results
string(189) "[{"patient":"Mohammed Shammar","number":"34"}]"
You can json_decode and fetch the data as follows,
$temp = json_decode($get_patient_info);
echo $get_patient_info[0]->patient;
json_decode — Decodes a JSON string
Hope this helps.

Sending variables to another application and get the response from that?

I need to send data to another webpage of different application and it will send some json data which i need to use in further instruction.
I need to send some basic information like cus_name, cus_email, cus_phone to that webpage and that will send some data as json format.
i got the basic idea of how can i catch the json response : like that,
$client = new Client();
$body = $client->get('https://securepay.google.com/gwprocess/v3/api.php')->getBody();
$data = json_decode($body);
return redirect($data->GatewayPageURL);
How do i send those variables to and catch the response in same controller?
Thanks in advance.
You can send Query String Parameters in two ways.
Include them in the URI itself.
$response = $client->request('GET', 'https://securepay.google.com/gwprocess/v3/api.php?cus_name=name&cus_email=email&cus_phone=phone');
Or
Specify them using the query request option as an array
$response = $client->request('GET', 'https://securepay.google.com/gwprocess/v3/api.php', [
'query' => [
'cus_name' => 'name',
'cus_email' => 'email',
'cus_phone' => 'phone'
]
]);
Or for Post Requests:
$response = $client->request('POST', 'https://securepay.google.com/gwprocess/v3/api.php', [
'form_params' => [
'cus_name' => 'name',
'cus_email' => 'email',
'cus_phone' => 'phone'
]
]);
and then to get the response:
$result = json_decode($response->getBody());

Shapeshift API always returns "No Withdrawal Address Specified" error

I am using Shape Shift API for sending transaction with Guzzle. I am always getting the error given in title. My code given below:
$client = new GuzzleHttp\Client();
$data = [
"amount" => 1,
"withdrawal" => '0x23f016d7a8e408e5551ae7aa51b3fe1534165463',
"pair" => 'btc_eth',
"returnAddress" => '12stJs8vZNuuVfjZSSzpLPA96quNissk1b'
];
$result = $client->post( 'https://shapeshift.io/shift', [ 'Content-Type' => 'application/json' ],
[ 'json' => $data ] );
print "<pre>";
print_r( $result->getBody()->getContents() );
print "</pre>";
Same parameters work fine when using in Python.
You are doing the request wrong. The correct variant is with two parameters:
$result = $client->post('https://shapeshift.io/shift', ['json' => $data]);
Content type is configured automatically when you use json option.

Categories