php send https rest request with headers - php

I need to send a request to an api with auth headers
here is what I've tried so far
$client = new \yii\httpclient\Client(['baseUrl' => 'https://link']);
$response = $client->createRequest()
->setMethod('GET')
->addHeaders(['authorization' => 'token'])
->send();
var_dump($response);
//other
$client = new \GuzzleHttp\Client();
$headers = ['authorization' => 'token'];
$body = 'Hello!';
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://link', $headers, $body);
$response = $client->send($request, ['timeout' => 2]);
$curl = new \linslin\yii2\curl\Curl();
$response = $curl->setHeaders($headers)->get('link', $headers);
var_dump($response);
// other
$opts = [
"http" => [
"method" => "GET",
"header" => "authorization:token\r\n",
],
];
$context = stream_context_create($opts);
$file = file_get_contents('link', false, $context);
var_dump($file);
// other
$ch = curl_init();
$headers = ["authorization:token"];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); # custom headers, see above
$result = curl_exec($ch); # run!
// curl_close($ch);
var_dump($result);
ps: I am working with the yii2 framework
so can anyone tell me what is wrong?
{
"client": {
"baseUrl": null,
"formatters": {
"urlencoded": {
"encodingType": 1,
"charset": null
}
},
"parsers": [],
"requestConfig": [],
"responseConfig": {
"format": "json"
},
"contentLoggingMaxSize": 2000
}
}
that is the error I am getting. I don't get any details regarding the connection ...

this worked for me
$client = new \yii\httpclient\Client(['responseConfig' => [
'format' => \yii\httpclient\Client::FORMAT_JSON,
]]);
$response = $client->createRequest()
->setHeaders(['authorization' => 'f52d76cc976e0e1b6aa81c926cbc33823b5e5983', 'content-type' => 'application/json'])
->setMethod('GET')
->setUrl('https://preprod-next-ngcvin5.ngc-data.fr/api/v1/vehicules/CR-157-NB')
->send();
return $response->data;

Related

Guzzle: Call to undefined method GuzzleHttp\\\\Psr7\\\\Stream::getStatusCode()

I'm trying out guzzle in mu laravel app in order to use FCM notifications, for some reason I'm getting the following error when I try to get response status code, also am I using guzzle correct syntax? they seem to have updated theirs.
Call to undefined method GuzzleHttp\\\\Psr7\\\\Stream::getStatusCode()
My method:
public function send($user,$title,$body, $data = false , $type, $image='')
{
$client = new Client();
$url = 'https://fcm.googleapis.com/fcm/send';
$serverKey = config('services.firebase.api_key');
$headers =
[
'Content-Type' => 'application/json',
'Authorization' => 'key='.$serverKey,
];
$fields =
[
'registration_ids' => [ $user['fcm_token'] ],
'to' => $user['fcm_token'],
"notification" =>
[
"title" => $title,
"body" => $body,
"sound" => "default",
],
"priority" => 10,
'data' => $data,
"android" => [ "priority" => "high" ]
];
$fields = json_encode ( $fields );
try
{
$response = $client->request('POST',$url,[
'headers' => $headers,
"body" => $fields,
]);
$response = $response->getBody();
$statusCode = $response->getStatusCode();
}
catch (ClientException $e)
{
$response = $e->getResponse();
$response = $response->getBody()->getContents();
$statusCode = $response->getStatusCode();
}
$result =
[
'response' => $response,
'statusCode' => $statusCode
];
return $result;
}
Thanks in advance
You are overwriting the response and then trying to get the status code from the stream. You should instead do
$response = $e->getResponse();
$statusCode = $response->getStatusCode();
$response = $response->getBody()->getContents();
Notice I moved the getStatus method
above the getBody.

Request fails on curl but works on guzzle

Am using the following post request on guzzle to microsoft graph which works.
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token ]
]);
$url = "myurl";
$response = $client->post(
$url,
[
'body' => json_encode(
[
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
"meeting"=>$arr['subject']
]
)]
);
$payload = json_decode($response->getBody()->getContents());
var_dump($payload) //here has data
The am doing the same request via curl using
$post = [
"meeting"=>$arr['subject'],
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
$authorization = "Authorization: Bearer ".$token;
$headers = [
'Content-Type' => 'application/json',
$authorization
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error = curl_errno($ch) ? curl_error($ch) : '';
curl_close($ch);
if ($error){
var_dump($error);
throw new Exception($error,500);
}
return $response;
But in curl the above in micorsoft graph throws an error Expected not null\r\nParameter name: meeting but the meeting parameter is not empty. I have also tried setting the value of meeting directly via
$post = [
"meeting"=>"Test meeting",
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
But still doesnt solve. I guess it has something to do with body parameter i have set on guzzle which works. How can i resolve this to have it work even on curl

Using Guzzle to send POST request with JSON

$client = new Client();
$url = 'api-url';
$request = $client->post($url, [
'headers' => ['Content-Type' => 'application/json'],
'json' => ['token' => 'foo']
]);
return $request;
And I get back 502 Bad Gateway and Resource interpreted as Document but transferred with MIME type application/json
I need to make a POST request with some json. How can I do that with Guzzle in Laravel?
Give it a try
$response = $client->post('http://api.example.com', [
'json' => [
'key' => 'value'
]
]);
dd($response->getBody()->getContents());
Take a look..
$client = new Client();
$url = 'api-url';
$headers = array('Content-Type: application/json');
$data = array('json' => array('token' => 'foo'));
$request = new Request("POST", $url, $headers, json_encode($data));
$response = $client->send($request, ['timeout' => 10]);
$data = $response->getBody()->getContents();
you can also try this solution. that is working on my end. I am using Laravel 5.7.
This is an easy solution of Make a POST Request from PHP With Guzzle
function callThirdPartyPostAPI( $url,$postField )
{
$client = new Client();
$response = $client->post($url , [
//'debug' => TRUE,
'form_params' => $postField,
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
]
]);
return $body = $response->getBody();
}
For Use this method
$query['schoolCode'] =$req->schoolCode;
$query['token']=rand(19999,99999);
$query['cid'] =$req->cid;
$query['examId'] =$req->examId;
$query['userId'] =$req->userId;
$tURL = "https://www.XXXXXXXXXX/tabulation/update";
$response = callThirdPartyPostAPI($tURL,$query);
if( json_decode($response,true)['status'] )
{
return success(["data"=>json_decode($response,true)['data']]);
}

How can I get response from guzzle 6 in Laravel 5.3?

I read from here : http://www.phplab.info/categories/laravel/consume-external-api-from-laravel-5-using-guzzle-http-client
I try like this :
...
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\RequestException;
...
public function testApi()
{
try {
$client = new GuzzleHttpClient();
$apiRequest = $client->request('POST', 'https://myshop/api/auth/login', [
// 'query' => ['plain' => 'Ab1L853Z24N'],
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'auth' => ['test#gmail.com', '1234'], //If authentication required
// 'debug' => true //If needed to debug
]);
$content = json_decode($apiRequest->getBody()->getContents());
dd($content);
} catch (RequestException $re) {
//For handling exception
}
}
When executed, the result is null
How can I get the response?
I try in postman, it success get response
But I try use guzzle, it failed
Update :
I check on the postman, the result works
I try click button code on the postman
Then I select php curl and I copy it, the result like this :
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://myshop/api/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\ntest#gmail.com\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n1234\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"postman-token: 1122334455-abcd-edde-aabe-adaddddddddd"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
If it use curl php, the code like that
How can I get the response if it use guzzle?
I see at least one syntax mistake. The third argument of the request() method should look like this:
$requestContent = [
'headers' = [],
'json' = []
];
In your case it could be:
public function testApi()
{
$requestContent = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
'json' => [
'email' => 'test#gmail.com',
'password' => '1234',
// 'debug' => true
]
];
try {
$client = new GuzzleHttpClient();
$apiRequest = $client->request('POST', 'https://myshop/api/auth/login', $requestContent);
$response = json_decode($apiRequest->getBody());
dd($response);
} catch (RequestException $re) {
// For handling exception.
}
}
There are other parameters instead of json for your data, for example form_params. I suggest you take a look at the Guzzle documentation.

Guzzle not sending POST parameters

I am sending this as a test to a test webserver, but the response although its a 201 which means it got it, it does not show the posted data I want to send:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
Is the format of the request I made incorrect?
I can see that it is not getting the post data because when I do a dsm of the response body, it isn't there.
This worked for me, looks like I needed to add the headers:
$url="https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = $form_state->cleanValues()->getValues();
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => $post_data,
'verify'=>false,
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
dsm($body);
dsm($status);

Categories