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 keep alive with Guzzle in PHP?
- How to retry requests with PHP Guzzle?
- How to post form data with PHP Guzzle?
- How to install PHP Guzzle without Composer?
- How to download a file with Guzzle in PHP?
- How to convert a response to an array with PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to send multipart requests with Guzzle in PHP?
See more codes...