In Guzzle, an HTTP client for PHP, you can add query parameters to a request by including them in the request options array with the key query
. Guzzle will automatically append the query parameters to the URI of the request.
Here's an example of how you might add query parameters to a GET request using Guzzle:
<?php
require 'vendor/autoload.php'; // Make sure you have included the composer autoload file
use GuzzleHttp\Client;
$client = new Client();
// The query parameters you want to send
$queryParams = [
'param1' => 'value1',
'param2' => 'value2'
];
// Send a GET request to http://your-api.com/endpoint with the query parameters
$response = $client->request('GET', 'http://your-api.com/endpoint', [
'query' => $queryParams
]);
// Get the body of the response
$body = $response->getBody();
$content = $body->getContents();
echo $content;
If you need to send a POST request with form parameters and query parameters, you can do so by using both form_params
and query
in the request options array:
<?php
require 'vendor/autoload.php'; // Make sure you have included the composer autoload file
use GuzzleHttp\Client;
$client = new Client();
// The form parameters you want to send
$formParams = [
'form_param1' => 'value1',
'form_param2' => 'value2'
];
// The query parameters you want to send
$queryParams = [
'query_param1' => 'value1',
'query_param2' => 'value2'
];
// Send a POST request to http://your-api.com/endpoint with the form and query parameters
$response = $client->request('POST', 'http://your-api.com/endpoint', [
'form_params' => $formParams,
'query' => $queryParams
]);
// Get the body of the response
$body = $response->getBody();
$content = $body->getContents();
echo $content;
In the above examples, Guzzle takes care of encoding the query parameters and appending them to the URI. It also sends the form parameters in the body of the POST request with the appropriate Content-Type
header (application/x-www-form-urlencoded
).
Guzzle automatically merges query parameters if the URI you are hitting already has query parameters. So, if you make a request to http://your-api.com/endpoint?existing_param=existing_value
and pass ['query' => ['new_param' => 'new_value']]
in the request options, Guzzle will combine them into http://your-api.com/endpoint?existing_param=existing_value&new_param=new_value
.