Skip to main content

Basic Request Patterns

GET

$request = new HttpRequest(
    url: 'https://api.example.com/users',
    method: 'GET',
    headers: ['Accept' => 'application/json'],
    body: '',
    options: [],
);

$response = $client->withRequest($request)->get();
// @doctest id="63d1"
string|array request bodies are supported. Arrays are JSON-encoded. If encoding fails (for example because a value is not serializable), HttpRequestBody throws InvalidArgumentException.

POST JSON

$request = new HttpRequest(
    url: 'https://api.example.com/messages',
    method: 'POST',
    headers: ['Content-Type' => 'application/json'],
    body: ['text' => 'hello'],
    options: [],
);

$response = $client->withRequest($request)->get();
// @doctest id="5ae1"

Request Mutation Is Immutable

$request = $request
    ->withHeader('Authorization', 'Bearer ' . $token)
    ->withStreaming(false);
// @doctest id="f662"
Each with*() call returns a new request.

Driver + Config via Builder

use Cognesy\Http\Config\HttpClientConfig;
use Cognesy\Http\Creation\HttpClientBuilder;

$client = (new HttpClientBuilder())
    ->withConfig(new HttpClientConfig(
        driver: 'guzzle',
        connectTimeout: 5,
        requestTimeout: 30,
        failOnError: true,
    ))
    ->create();
// @doctest id="9a4b"

Error Strategy

  • failOnError: false (default): HTTP 4xx/5xx are returned as regular responses
  • failOnError: true: driver throws typed HTTP exceptions for 4xx/5xx
Migration note: built-in preset defaults are aligned to failOnError: false. If you depended on throwing behavior by default, set failOnError: true explicitly.