php-guzzleHow to make HTTP request with PHP Guzzle?
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.
To make an HTTP request with Guzzle, you need to create a GuzzleHttp\Client
object and pass it the base URI of the web service you are trying to access.
$client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org/']);
Then you can use the $client
object to make an HTTP request. For example, to make a GET request:
$response = $client->request('GET', 'get');
echo $response->getBody();
The output of the above code will be a JSON string containing the response from the web service:
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "GuzzleHttp/6.3.3 curl/7.54.0 PHP/7.2.10"
},
"origin": "1.2.3.4",
"url": "http://httpbin.org/get"
}
Code explanation
-
$client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org/']);
- creates aGuzzleHttp\Client
object and passes it the base URI of the web service you are trying to access. -
$response = $client->request('GET', 'get');
- uses the$client
object to make an HTTP request. In this case, it is a GET request. -
echo $response->getBody();
- prints out the response from the web service.
Helpful links
More of Php Guzzle
- How to use PHP Guzzle to make a batch request?
- How to set a user agent in PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
- What version of PHP is required for Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to set a timeout for a request with PHP Guzzle?
- How to add a bearer token in PHP Guzzle?
- How to add an authorization header bearer in PHP Guzzle?
- How to update PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
See more codes...