Send nested array via Laravel Http Client - laravel

I want to send request to an API website containing nested params via Laravel Http Client (Laravel 7.x)
$params = [
'type' => 'books',
'variables' => [
'color' => 'red',
'size' => 'large'
]
]
I want my url to like this:
http://example.com/?type=books&variables={"color":"red","size":"large"}
encoded above url:
http://example.com/?type=books&variables=%7B%22color%22%3A%22red%22%2C%22size%22%3A%22large%22%7D
But when I use:
Http::get('http://example.com', $params);
The API server returns error.
But when I use:
Http::get('http://example.com/?type=books&variables={"color":"red","size":"large"}');
It works well.
So how can I convert my params array into url ?
(I don't have access to API server)

try json_encode()
$params = [
'type' => 'books',
'variables' => json_encode([
'color' => 'red',
'size' => 'large'
])
]
$url = "http://example.com?".http_build_query($params);
Http::get($url);
and http_build_query()
ref link https://www.php.net/manual/en/function.http-build-query.php

Related

Laravel 9 | cURL request to HTTP Client

New versions of laravel have their own HTTP client. I like the syntax and want to use it. Before that I was always using cURL.
I am now trying to make a request with the new HTTP client, but I always get a weird result back. Status is 200 btw.:
{
"cookies": {},
"transferStats": {}
}
I dont know where this comes from, my endpoint does not return this.
This is the cURL version, which works:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => env('SCAMMER_CHECK_ENDPOINT'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('auth' => $data['auth'],'authUserId' => $msd_user_id,'img' => $data['base64img']),
));
$scammer_check = curl_exec($curl);
curl_close($curl);
This is the same request with the HTTP client, which does not work:
$scammer_check = Http::post(env('SCAMMER_CHECK_ENDPOINT'), [
'auth' => $data['auth'],
'authUserId' => $msd_user_id,
'img' => $data['base64img']
]);
I also tried to use raw body, but same result:
$scammer_check = Http::withBody(
json_encode(array('auth' => $data['auth'],'authUserId' => $msd_user_id,'img' => $data['base64img'])), 'application/json'
)->post(env('SCAMMER_CHECK_ENDPOINT'));
It seems like the HTTP client is returning an empty response with cookies and transferStats. This could be due to incorrect response handling.
You could try retrieving the response body by using the "body" method on the response object like this:
$response = Http::post(env('SCAMMER_CHECK_ENDPOINT'), [
'auth' => $data['auth'],
'authUserId' => $msd_user_id,
'img' => $data['base64img']
]);
$scammer_check = $response->body();
Alternatively, you could try specifying the expected response format like this:
$scammer_check = Http::post(env('SCAMMER_CHECK_ENDPOINT'), [
'auth' => $data['auth'],
'authUserId' => $msd_user_id,
'img' => $data['base64img']
])->json();

Sending multidimensional array as key with Laravel http client request

I want to use the HelloSign API to let users sign contracts through our Laravel application. To make the API calls I use Laravel's Http Client which is build around the Guzzle Http Client.
In order to assign a signer to a HelloSign transaction the API expects the following parameter:
signers[Agent][name]
Now when I run this in postman. It works like a charm. But when I use the parameters like this in Laravel's HTTP client I receive the following error message: Invalid parameter: signers[Agent][name]. But when I use the same exact structure using cURL it workins like a charm.
HTTP Client:
Http::withBasicAuth($key, '')->post($url, [
'test_mode' => '1',
'template_id' => $template_id,
'signers[Agent][name]' => 'John Doe',
'signers[Agent][email_address]' => 'dummy#test.com'
]);
cURL:
CURLOPT_POSTFIELDS => array(
'test_mode' => '1',
'template_id' => $template_id,
'signers[Agent][name]' => 'John Doe',
'signers[Agent][email_address]' => 'dummy#test.com'
),
How can I make the HTTP client work?
Try to use multidimensional array:
Http::withBasicAuth($key, '')->post($url, [
'test_mode' => '1',
'template_id' => $template_id,
'signers' => [
'Agent' => [
'name' => 'John Doe',
'email_address' => 'dummy#test.com'
]
]
]);

Guzzle Post Null/Empty Values in Laravel

I've been trying to work with Guzzle and learn my way around it, but I'm a bit confused about using a request in conjunction with empty or null values.
For example:
$response = $client->request('POST',
'https://www.testsite.com/coep/public/api/donations', [
'form_params' => [
'client' => [
'web_id' => NULL,
'name' => 'Test Name',
'address1' => '123 E 45th Avenue',
'address2' => 'Ste. 1',
'city' => 'Nowhere',
'state' => 'CO',
'zip' => '80002'
],
'contact' => [],
'donation' => [
'status_id' => 1,
'amount' => $donation->amount,
'balance' => $donation->balance,
'date' => $donation->date,
'group_id' => $group->id,
],
]
]);
After running a test, I found out that 'web_id' completely disappears from my request if set to NULL. My question is how do I ensure that it is kept around on the request to work with my conditionals?
At this point, if I dd the $request->client, all I get back is everything but the web_id. Thanks!
I ran into this issue yesterday and your question is very well ranked on Google. Shame that it has no answer.
The problem here is that form_params uses http_build_query() under the hood and as stated in this user contributed note, null params are not present in the function's output.
I suggest that you pass this information via a JSON body (by using json as key instead of form_params) or via multipart (by using multipart instead of form_params).
Note: those 2 keys are available as constants, respectively GuzzleHttp\RequestOptions::JSON and GuzzleHttp\RequestOptions::MULTIPART
Try to define anything like form_params, headers or base_uri before creating a client, so:
// set options, data, params BEFORE...
$settings = [
'base_uri' => 'api.test',
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'ajustneedatokenheredontworry'
],
'form_params' => [
'cash' => $request->cash,
'reason' => 'I have a good soul'
]
];
// ...THEN create your client,
$client = new GuzzleClient($settings);
// ...and finally check your response.
$response = $client->request('POST', 'donations');
If you check $request->all() at the controller function that you are calling, you should see that were sent successfully.
For those using laravel, use this:
Http::asJson()

Can’t submit data to API Platform

I have a controller through which I send data to my local environment of the api platform (which is running fine)
/**
* Creates a new Location entity.
*
*/
public function createAction(Request $request)
{
$this->get("suvya_breadcrumbs.factory")->update('New Hub');
$form = $this->createForm(HubType::class);
$form->handleRequest($request);
$new_url = $this->generateUrl('new_hub');
$redirect_url = $this->generateUrl('home');
if ($form->isSubmitted() && $form->isValid()) {
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'form_params'=> $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Content-Type'=> 'application/json',
'Authorization'=> 'eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJhZG1pbiIsImlhdCI6MTUxNzg3NjE1NCwiZXhwIjoxNTE3ODc5NzU0fQ.gIG9lueJJZxzkOl8qblhHWwiJvW97m4gz1-1mYeM9SgMzMW35Wh6XamOOYiISDN99yJ6Ovo-wKk6whpE5UGMDVw_wGek003Dd6r-Y7Ql3kVLHksn2JFzhAN3GwlXFcOI4MIjmq5qBhkzv21pHymO0yn1SlzWBwb0O7WygywefMu5p09zGuvAiP9I2ShyQLZhjj8bB_odf3dI-Ql0ZbRmn_JDkDoPcm5U11i-3S1oMikBmFq0WtTcWo7vezt3QdA3bY4_bgaISINAiYRR-_cvjpBSqFSE6n1ZYtHvKFn-98wXXsBGxEAoZw6iQL4iRgOI8F_uaiCo0eRHC7q0_xQ_V_W0-5XDIQXWDwoiVaUXnjO6xo2Fldp7PLO1ueJz1e4wiOy2-TunZdc8UCtw2BdFIQtWatPLi_v_rsNvF2H-6hwa9UOKEi9Z4tH4KkuATbXAxxfkCbSOyY1SAWP0riooPQi_AI2J7L2Ly86eAuKo1Hix3EuEogo19GSyBz_cCWczyERQWM9gikuUs8E22SIAdxTl8ZLFaXgiZIibDvb8pqcN8izFjywWbF2CkyWC58WxrVd6Bfmfnm7k9T6oZqwIZ-TQR-SbRnUHN1hpWUjFCk-tHhgvh7osHXmxe3grzA8M3LPBpQGQiTeqBZFMjF4Tx8zW2tuiEn6TwhV14Lj24Vc'
]
]);
die();
}
return $this->render('SuvyaFabricsCloudBundle:Common:basic.html.twig', array(
'form' => $form->createView(),
'page_title'=> 'Hub aanmaken',
'action_path' => $new_url,
'cancel_path'=> $redirect_url,
'submit_button_title' => 'Opslaan',
));
}
But unfortunately i'm getting an error in my dev.log of the api environment:
[2018-02-06 02:32:37] request.INFO: Matched route "api_hubs_post_collection". {"route":"api_hubs_post_collection","route_parameters":{"_controller":"api_platform.action.post_collection","_format":null,"_api_resource_class":"AppBundle\\Entity\\Hub","_api_collection_operation_name":"post","_route":"api_hubs_post_collection"},"request_uri":"http://127.0.0.1:8000/hubs","method":"POST"} []
[2018-02-06 02:32:37] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Serializer\Exception\UnexpectedValueException: "Syntax error" at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php line 78 {"exception":"[object] (Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException(code: 0): Syntax error at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php:78)"} []
The output of form->getData():
array (size=4)
'postalCode' => string 'sdfdsf' (length=6)
'streetName' => string 'sdfsdf' (length=6)
'doorNumber' => string 'sdfsfd' (length=6)
'city' => string 'sdfsfd' (length=6)
Running the endpoint at the api platform with the same values goes fine as well.
Does anyone of you has an idea why this goes wrong?
You're sending a payload encoded in application/x-www-form-urlencoded (HTML form like) to the API Platform API, while, according to the headers you've set, it excepts data encoded in JSON.
To encode the data of the form in JSON, you can use the following Guzzle snippet:
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'json' => $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Authorization'=> '...'
]
]);
Alternatively, you can configure API Platform to accept form data, but I would not recommend going this way (it's better to only deal with JSON API-side).

How to send bulk data through Guzzle?

I am implementing an API that needs to receive data from my database. The data comes from my 'Products' table. I organized the products that I want to send through Guzzle.
public function post()
{
$product = Product::where('erp_status', '=', 1)->limit(5)->offset(0)->get();
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://httpbin.org',
// You can set any number of default request options.
'timeout' => 2.0,
]);
And right after I created a foreach to send the data through the URL.
foreach($product as $prod){
set_time_limit(0);
$r = $client->request('POST', 'https://api.mercadolibre.com/items?access_token=XXXXXXXXXXXXXXXXXXX', [
'json' => [
'title' => $prod->description->erp_name,
'category_id' => 'MLB46511',
'price' => 10,
'currency_id' => 'BRL',
'available_quantity' => 10,
'buying_mode' => 'buy_it_now',
'listing_type_id' => 'gold_special',
'condition' => 'new',
'description' => 'Teste',
'pictures' => [
['source' => $prod->image->erp_image]
]
]
]);
}
return view('home');
}
But every time I run. It returns the message:
cURL error 28: Operation timed out after 2012 milliseconds with 0 out of 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
My variable $product have 5 thousand rows.
Does Guzzle support this amount? Is it possible to use the guzzle in this case or what is the pure PHP script?
Any suggestion?

Resources