I use the Requests for http request:
I also package it to a util function:
function http_util($url, $params, $add_headers = null, $base_url = null ){
$headers = array('Accept'=>'application/json');
if($add_headers){
$headers = array_merge($headers, $add_headers);
}
if($base_url) {
$url = $base_url . $url;
}
$request = Requests::post($url, $headers, $params);
return $request;
}
but I found, such as the curl example:
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
if the curl example convert to use my http_util, how to use? I am not sure whether my http_util will have more optimize action. and how to use the http_util request the curl example?
You cant use it as-is you'll need to add the $options param as noted in the docs: http://requests.ryanmccue.info/docs/authentication.html
The "util" function is simply setting a content Accept header. Not worth writing a function for that.
$result = Requests::post('http://localhost:8000/o/token' [
// headers
'Accept' => 'application/json'
], [
// data
'grant_type' => 'password',
'username' => '<user_name>',
'password' => '<password>',
], [
// options
'auth' => new Requests_Auth_Basic(['<client_id>', '<client_secret>'])
]);
Related
I am using codeigniter-3, i have to update the data but the API is extrenal API .i am using Guzzle class to contact with that api it's working fine but it's not updating the data because it's not taking the data ,can you tell me how to pass the arguments or body to the curl request..?
library
public function putcurl($url,$headers,$args){
$client = new GuzzleHttp\Client();
$response = $client->request('PUT',$url,['headers' => $headers],['body'=>$args]);
$body = $response->getBody();
$arr_body = json_decode($body);
return ($arr_body);
}
controller.php
$url = $this->config->item('url')['editstation'].$id;
$headers=[
'Authorization' => 'Basic xxxxxxxxxxxxxx',
'Content-Type' => ' application/json',
'Cookie' =>'ci_session=3e7c29f86fd6b8e738d8caefc37fa5b61e3b9ed0',
'x-api-key' => 'test#123',
];
$res = $this->customcurls->putcurl($url,$headers,$args);
I'm trying to test an endpoint of my Api with phpunit and the symfony WebTestCase object. I have to send a POST request with the KernelBrowser but I can't figure it out how to add parameters to the body of the request. My request work fine on postman.
I've tried this
$client->request('POST', '/url', ['param1' =>'value1', 'param2' => 'value2']);
It's not working.
I've tried this
$client->request('POST', '/url', [], [], [], '{param1: value, param2: value}');
It doesn't work,
I can't use the $client->submitForm() method because the form is send by another app.
Maybe it came from my Api endpoint because I'm using $_POST variable ?:
$res = false;
if(count($_POST) === 2){
$user = $this->userrepo->findByName($_POST['value1']);
if($user){
if($this->passwordEncoder->isPasswordValid($user[0], $_POST['value2'])){
$res = true;
}
}
}
return new Response($this->serializer->serialize(['isChecked' => $res], 'json'));
My test method has never passed the first if statement,
here my test method:
$client = static::createClient();
$client->request('POST', '/url', ['value1' => 'value1', 'value2' => 'value2']);
$this->assertStringContainsString('{"isChecked":true}', $client->getResponse()->getContent());
Here the POST request I'm trying to send:
curl --location --request POST 'http://localhost:8000/url' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--form 'value1=value1' \
--form 'value2=value2'
Symfony's test client dispatches the request internally. The global $_POST variable will always be empty. You should use the Request object in the controller to access the parameters. The attribute request contains the post data.
public function myAction(Request $request): Response
{
$postParameters = $request->request;
$res = false;
if ($postParameters->count() === 2) {
$user = $this->userrepo->findByName($postParameters->get('value1'));
if ($user) {
if ($this->passwordEncoder->isPasswordValid($user[0], $postParameters->get('value2'))) {
$res = true;
}
}
}
return new Response($this->serializer->serialize(['isChecked' => $res], 'json'));
}
Regarding the different variations of your test call, this one should work with the action above.
$client->request('POST', '/url', ['value1' => 'value1', 'value2' => 'value2']);
I have a method using gullzehttp and would like to change it to the pool plus the pool implements the Request method
<?php
use GuzzleHttp\Client;
$params = ['password' => '123456'];
$header = ['Accept' => 'application/xml'];
$options = ['query' => $params, 'headers' => $header];
$response = $client->request('GET', 'http://httpbin.org/get', $options);
I need to change to the Request method, but I could not find in the documentation how to send querystring variables in the Request
<?php
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://httpbin.org/get', $options);
You need to add the query as a string to the URI.
For that you can use http_build_query or a guzzle helper function to convert a parameter array to an encoded query string:
$uri = new Uri('http://httpbin.org/get');
$request = new Request('GET', $uri->withQuery(GuzzleHttp\Psr7\build_query($params)));
// OR
$request = new Request('GET', $uri->withQuery(http_build_query($params)));
I also had trouble figuring out how to properly place the new Request() parameters. but structuring it the way i did below using php http_build_query to convert my arrays to query params and then appended it to the url before sending fixed it.
try {
// Build a client
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://pro-api.coinmarketcap.com',
// You can set any number of default request options.
// 'timeout' => 2.0,
]);
// Prepare a request
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest';
$headers = [
'Accepts' => 'application/json',
'X-CMC_PRO_API_KEY' => '05-88df-6f98ba'
];
$params = [
'id' => '1'
];
$request = new Request('GET', $url.'?'.http_build_query($params), $headers);
// Send a request
$response = $client->send($request);
// Receive a response
dd($response->getBody()->getContents());
return $response->getBody()->getContents();
} catch (\Throwable $th) {
dd('did not work', $th);
return false;
}
I have been trying to download a file in Guzzle and it acts wired, Then I noticed that the request URL has gone haywire. I don't understand how to use the setEncodingType(false); function.
This is what I have right now.
public class Foo{
private $client;
private $loginUrl = 'https://<site>/login';
private $parseUrl = 'https://<site>/download';
public function __construct()
{
require_once APPPATH . 'third_party/guzzle/autoloader.php';
$this->client = new GuzzleHttp\Client(['cookies' => true, 'allow_redirects' => [
'max' => 10, // allow at most 10 redirects.
'strict' => true, // use "strict" RFC compliant redirects.
'referer' => true, // add a Referer header
'protocols' => ['https'], // only allow https URLs
'track_redirects' => true
]]);
}
public function download(){
$q_params = array('param_a'=> 'a', 'param_b'=>'b');
$target_file = APPPATH.'files/tmp.log';
$response = $this->client->request('GET', $this->parseUrl,['query'=>$reportVars, 'sink' => $target_file]);
}
}
Can anyone tell me how can I use disable the url encoding in the above code?
Cursory glance through the code of GuzzleHttp\Client::applyOptions indicates that when you utilze the "query" request option the query will be built to PHP_QUERY_RFC3986 as shown below:
if (isset($options['query'])) {
$value = $options['query'];
if (is_array($value)) {
$value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
}
if (!is_string($value)) {
throw new \InvalidArgumentException('query must be a string or array');
}
$modify['query'] = $value;
unset($options['query']);
}
Guzzle utilizes GuzzleHttp\Psr7\Uri internally. Note how the withoutQueryValue() and withQueryValue() methods will also encode the query string.
I have had a lot of success "hard coding" my query parameters, like the following:
$uri = 'http://somewebsite.com/page.html?param_a=1¶m2=245';
I would like to also note that there is no setEncodingType() within GuzzleHttp\Client.
I've created a custom Provider for Laravel Socialite.
The authentication part is going well until i'll try to call the user method.
Not sure what's going wrong.
Method documentation at wunderlist
My code:
/**
* {#inheritdoc}
*/
protected function getUserByToken($token)
{
$response = $this->getHttpClient()->get('https://a.wunderlist.com/api/v1/users', [
'X-Access-Token: ' . $token . ' X-Client-ID: ' . $this->clientId
]);
return json_decode($response->getBody(), true);
}
I get the following error:
InvalidArgumentException in MessageFactory.php line 202:
allow_redirects must be true, false, or array
Do i miss things in the options array?
Jos
Actually socialite is not supposed to do something like this. But instead you may use Guzzle. There is a good video at laracasts. Just search for Easy HTTP Requests. And here's the code that you may use for guzzle:
$client = new \Guzzle\Service\Client('a.wunderlist.com/api/v1/');
$response = $client->get('user')->send();
// If you want this response in array:
$user = $response->json();
Just read the docs here.
When using this with straight forward curl there is no issue.
As far as i can see the issue lies in the headers i'll parse.
The following solution is something i can live with, although it's not perfect.
$headers = array();
$headers[] = 'X-Access-Token: ' . $token;
$headers[] = 'X-Client-ID: ' . $this->clientId;
$response = $this->getHttpClient()->get('a.wunderlist.com/api/v1/user', [
'config' => [
'curl' => [
CURLOPT_POST => 0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false
]
]
]);
return json_decode($response->getBody(), true);