php-guzzlePHP Guzzle get request example
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Here is an example of how to use Guzzle to make a GET request:
<?php
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
?>
The code above will make a GET request to the URL https://api.github.com/user
with authentication credentials user
and pass
. The response will be stored in the $res
variable. The status code, header and body of the response can be accessed using the getStatusCode()
, getHeader()
and getBody()
methods respectively.
Parts of the code:
$client = new GuzzleHttp\Client();
: This creates a new Guzzle client.$res = $client->request('GET', 'https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]);
: This makes a GET request to the URLhttps://api.github.com/user
with authentication credentialsuser
andpass
.echo $res->getStatusCode();
: This prints the status code of the response.echo $res->getHeader('content-type');
: This prints the value of thecontent-type
header of the response.echo $res->getBody();
: This prints the body of the response.
Helpful links
More of Php Guzzle
- How to use PHP Guzzle to make a batch request?
- How to update PHP Guzzle?
- How to set a user agent in PHP Guzzle?
- How to stream with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to download a file with Guzzle in PHP?
- How to handle a RequestException with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
- How to get the response body in PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
See more codes...