Skip to content

Overview

Greg Bowler edited this page Mar 16, 2026 · 3 revisions

The easiest way to understand Fetch is to see the overall shape of the code first.

1. Create an Http object

use GT\Fetch\Http;

$http = new Http();

2. Call fetch() and work with the Response

use GT\Http\Response;

$http->fetch("https://api.github.com/orgs/phpgt/repos")
	->then(function(Response $response) {
		if(!$response->ok) {
			throw new RuntimeException("Unexpected status: $response->status");
		}

		return $response->json();
	})
	->then(function($json) {
		echo "Repository count: ", count($json->getPrimitiveValue()), PHP_EOL;
	});

3. Finish the queued work

$http->wait();

This is the basic pattern we will use throughout the rest of the documentation:

  • create one Http object
  • queue one or more requests
  • attach then() and catch() handlers as needed
  • call wait() or all()

The Response object

The first promise returned from fetch() resolves with a GT\Http\Response. From there we can inspect headers and status immediately, and then choose how to read the body.

The most common body helpers are:

  • $response->text()
  • $response->json()
  • $response->blob()
  • $response->formData()

Each of these returns another Promise. This means we can keep chaining work in a natural way.

$http->fetch("https://example.com/data.json")
	->then(function(Response $response) {
		return $response->json();
	})
	->then(function($json) {
		// Work with decoded JSON here.
	});

If we prefer a blocking flow, we can use awaitFetch() and the matching await... methods on the response body:

$response = $http->awaitFetch("https://example.com/data.json");
$json = $response->awaitJson();

Concurrency by default

One of the most useful parts of this library is that we can queue multiple requests on the same Http object before calling wait().

$http->fetch("https://example.com/a.json");
$http->fetch("https://example.com/b.json");
$http->fetch("https://example.com/c.json");

$http->wait();

Here we can see the intent clearly: set up all of the work first, then wait for it to complete. This is often much easier to read than deeply nested synchronous request code.


In the next section we will look at constructing Http objects.

Clone this wiki locally