-
-
Notifications
You must be signed in to change notification settings - Fork 8
Making HTTP requests with fetch
The fetch() function is the heart of the library. It accepts either a URL-like input or a PSR-7 request object, and returns a Promise that resolves with a GT\Http\Response.
Here is the smallest useful example:
use GT\Fetch\Http;
use GT\Http\Response;
$http = new Http();
$http->fetch("https://api.github.com/orgs/phpgt/repos")
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Unable to load repositories");
}
return $response->json();
})
->then(function($json) {
echo "Loaded ", count($json->getPrimitiveValue()), " repositories.", PHP_EOL;
})
->catch(function(Throwable $reason) {
echo $reason->getMessage(), PHP_EOL;
});
$http->wait();Here we can see three distinct stages:
-
fetch()creates the HTTP request - the first
then()works with theResponse - the second
then()works with the decoded body
The first Promise resolves with a GT\Http\Response. This allows us to inspect:
statusok- headers
- URI information
The response body can then be consumed using one of the response helper methods:
text()json()blob()formData()
For example:
$http->fetch("https://example.com/message.txt")
->then(function(Response $response) {
return $response->text();
})
->then(function(string $text) {
echo $text;
});If the request has already been constructed elsewhere in the application, we do not need to rebuild it as an init array. fetch() accepts any PSR-7 RequestInterface.
use GT\Http\Header\RequestHeaders;
use GT\Http\Request;
use GT\Http\Uri;
$request = new Request(
"GET",
new Uri("https://api.github.com/orgs/phpgt/repos"),
new RequestHeaders()
);
$http->fetch($request)
->then(function(Response $response) {
return $response->json();
})
->then(function($json) {
echo "Done.", PHP_EOL;
});This is especially useful when another library, framework component or application layer is already speaking PSR-7.
Any exception thrown in the chain can be handled with catch().
$http->fetch("https://example.com/api")
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Status was $response->status");
}
return $response->json();
})
->catch(function(Throwable $error) {
echo "Request failed: ", $error->getMessage(), PHP_EOL;
});For longer examples, take a look at usage examples.
The next section covers the supported request options.
PHP.GT/Fetch is a separately maintained component of PHP.GT/WebEngine.