VOOZH about

URL: https://deepwiki.com/hypervel/components/3.6-http-client-for-external-requests

⇱ HTTP Client for External Requests | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

HTTP Client for External Requests

Purpose and Scope

This document covers the HTTP Client system for making external HTTP requests from Hypervel applications. The system provides a fluent API for building requests, automatic retry logic, connection pooling, middleware support, and comprehensive testing utilities with request faking. This is distinct from the incoming HTTP request handling covered in Request Lifecycle and Processing.

The HTTP Client is exposed through the Http facade and uses Guzzle as the underlying HTTP library, wrapping it with Laravel-style convenience methods and coroutine-safe connection pooling.

Sources: src/http-client/src/Factory.php1-527 src/support/src/Facades/Http.php1-122 src/http-client/composer.json1-44


System Architecture

Component Overview

The HTTP Client system consists of several key classes that work together to provide a complete HTTP client solution:


Sources: src/http-client/src/Factory.php31-96 src/http-client/src/PendingRequest.php38-210 src/http-client/src/Response.php25-56 src/http-client/src/Request.php14-28

Request Lifecycle


Sources: src/http-client/src/PendingRequest.php713-795 src/http-client/src/Factory.php404-417 src/http-client/src/PendingRequest.php1034-1046


Factory and Client Creation

Factory Class

The Factory class serves as the main entry point for creating HTTP clients. It manages global middleware, global options, connection pooling, and request faking for tests.

ResponsibilityMethodDescription
Client CreationcreatePendingRequest()Creates new PendingRequest with global settings
Global MiddlewareglobalMiddleware(), globalRequestMiddleware(), globalResponseMiddleware()Apply middleware to all requests
Global OptionsglobalOptions()Set options for all requests
Connection ManagementregisterConnection(), getClient()Manage named connections with pooling
Testing Supportfake(), fakeSequence(), stubUrl()Set up request stubbing
Assertion MethodsassertSent(), assertNotSent(), assertSentCount()Verify requests in tests

Sources: src/http-client/src/Factory.php31-96 src/http-client/src/Factory.php98-136 src/http-client/src/Factory.php404-417

Connection Pooling

The Factory supports connection pooling through the ClientPoolProxy class, which wraps Guzzle clients to enable connection reuse across coroutines:


Connections are registered and configured through the Factory:

  • Registration: registerConnection($name, $config) adds a connection to the poolables list
  • Configuration: setConnectionConfig($name, $config) stores pool configuration (min, max connections, wait timeout)
  • Resolution: getClient($connection, $handlerStack, $config) returns either a pooled proxy or direct client
  • Poolable Check: Only registered connections get wrapped in ClientPoolProxy

Sources: src/http-client/src/Factory.php436-476 src/http-client/src/ClientPoolProxy.php1-65 src/http-client/src/Factory.php73-88

Global Configuration

The Factory accepts global middleware and options that apply to all requests:


Sources: src/http-client/src/Factory.php98-136 src/http-client/src/PendingRequest.php187-210 src/http-client/src/Factory.php414-417


PendingRequest Fluent API

Core Request Building

The PendingRequest class provides a fluent interface for building HTTP requests. It uses method chaining to configure all aspects of a request before sending:

CategoryMethodsPurpose
Base URLbaseUrl($url)Set base URL for relative paths
Body FormatasJson(), asForm(), asMultipart(), withBody()Configure request body format
HeaderswithHeaders(), withHeader(), accept(), acceptJson(), contentType()Set request headers
AuthenticationwithBasicAuth(), withDigestAuth(), withToken()Configure authentication
ParameterswithQueryParameters(), withUrlParameters()Set query and URL template parameters
Timeoutstimeout(), connectTimeout()Configure timeout behavior
RedirectsmaxRedirects(), withoutRedirecting()Control redirect handling
Filesattach()Attach files for multipart requests
OptionswithOptions(), withoutVerifying(), sink()Advanced Guzzle options

Sources: src/http-client/src/PendingRequest.php212-521 src/http-client/src/PendingRequest.php38-183

HTTP Verb Methods

PendingRequest provides convenience methods for each HTTP verb:


All methods return either a Response object (sync) or PromiseInterface (async).

Sources: src/http-client/src/PendingRequest.php624-705 tests/HttpClient/HttpClientTest.php76-186

Request Building Flow


Sources: src/http-client/src/PendingRequest.php713-795 src/http-client/src/PendingRequest.php800-847

URL Parameter Substitution

PendingRequest supports URL template parameters using RFC 6570 URI templates via withUrlParameters():


The expansion happens in expandUrlParameters() using GuzzleHttp\UriTemplate\UriTemplate.

Sources: src/http-client/src/PendingRequest.php410-417 src/http-client/src/PendingRequest.php800-803 tests/HttpClient/HttpClientTest.php1130-1142


Response Handling

Response Class

The Response class wraps Guzzle's PSR-7 response with convenient methods for accessing and testing response data:


Sources: src/http-client/src/Response.php25-56 src/http-client/src/Response.php58-152 src/http-client/src/Response.php195-233

Body Access Methods

The Response class provides multiple ways to access the response body:

MethodReturn TypeDescription
body()stringRaw response body as string
json($key, $default)mixedJSON decoded as array, with dot notation key access
object()object|array|nullJSON decoded as object
collect($key)CollectionJSON as Collection, with optional key
fluent($key)FluentJSON as Fluent object
resource()resourceBody as PHP stream resource
decodeUsing($callback)selfSet custom decoder for non-JSON responses

Sources: src/http-client/src/Response.php58-152 tests/HttpClient/HttpClientTest.php347-454

Status Code Helpers

Response provides expressive status checking methods:


Sources: src/http-client/src/Response.php195-233 src/http-client/src/Concerns/DeterminesStatusCode.php (trait), tests/HttpClient/HttpClientTest.php100-334

Error Handling

Response supports throwing exceptions on errors:


Sources: src/http-client/src/Response.php293-373 src/http-client/src/PendingRequest.php564-592 tests/HttpClient/HttpClientTest.php1467-1545


Retry Mechanisms

Retry Configuration

PendingRequest supports automatic retries with customizable logic:


Sources: src/http-client/src/PendingRequest.php731-794 src/http-client/src/PendingRequest.php496-508

Retry Method Signature

The retry() method configures retry behavior:


Usage Examples:


Sources: src/http-client/src/PendingRequest.php496-508 tests/HttpClient/HttpClientTest.php1547-1646

Retry State Variables

The retry mechanism uses several instance variables:

VariableTypeDefaultPurpose
$triesarray|int1Number of attempts or array of delays
$retryDelayClosure|int100Milliseconds to wait or callback returning delay
$retryWhenCallbackcallable|nullnullDetermines if retry should happen
$retryThrowbooltrueWhether to throw exception after all retries

Sources: src/http-client/src/PendingRequest.php106-118 src/http-client/src/PendingRequest.php731-794


Middleware Stack

Middleware Types

The HTTP Client supports three types of middleware at different scopes:


Sources: src/http-client/src/Factory.php98-136 src/http-client/src/PendingRequest.php523-551 src/http-client/src/PendingRequest.php1048-1165

Handler Stack Construction

The buildHandlerStack() method constructs the Guzzle middleware stack:


Middleware execution order (bottom to top):

  1. Guzzle's default handler
  2. Stub handler (for faking)
  3. Recorder handler (records request/response pairs)
  4. Before-sending callbacks
  5. Instance middleware (pushed via withMiddleware())
  6. Global middleware (from Factory)

Sources: src/http-client/src/PendingRequest.php1048-1075 src/http-client/src/PendingRequest.php1077-1165

Before-Sending Callbacks

Before-sending callbacks execute just before the request is sent, allowing last-minute modifications:


The default before-sending callback stores the request and cookies on the PendingRequest instance for later access.

Sources: src/http-client/src/PendingRequest.php554-561 src/http-client/src/PendingRequest.php202-209

Middleware Helpers


Sources: src/http-client/src/PendingRequest.php523-551 tests/HttpClient/HttpClientTest.php1712-1850


Request Faking and Testing

Fake System Architecture

The HTTP Client provides comprehensive testing support through request faking and stubbing:


Sources: src/http-client/src/Factory.php183-224 src/http-client/src/PendingRequest.php1136-1165 src/http-client/src/Factory.php289-306

Faking Methods

MethodPurposeExample
fake()Stub all requests with 200 OKHttp::fake();
fake($callback)Stub with callbackHttp::fake(fn($req) => Http::response(['ok' => true]));
fake($array)Stub specific URLsHttp::fake(['github.com/*' => ['data' => 'stub']]);
fakeSequence($url)Create response sequenceHttp::fakeSequence()->push('First')->push('Second');
stubUrl($url, $response)Stub specific URLHttp::stubUrl('api.com/*', Http::response(['ok' => true]));

Sources: src/http-client/src/Factory.php183-260 tests/HttpClient/HttpClientTest.php76-97

Response Factory Methods

The Factory provides static methods for creating stubbed responses:


Sources: src/http-client/src/Factory.php139-170 src/http-client/src/ResponseSequence.php34-84 tests/HttpClient/HttpClientTest.php859-932

Response Sequences

ResponseSequence allows defining multiple responses that will be returned in order:


By default, sequences throw OutOfBoundsException when exhausted unless dontFailWhenEmpty() is called.

Sources: src/http-client/src/ResponseSequence.php1-133 tests/HttpClient/HttpClientTest.php859-932

Assertion Methods

After faking requests, use assertion methods to verify behavior:


Sources: src/http-client/src/Factory.php308-382 tests/HttpClient/HttpClientTest.php688-743

Preventing Stray Requests

In tests, you can ensure all requests are faked:


This prevents accidental real HTTP requests during testing.

Sources: src/http-client/src/Factory.php262-286 src/http-client/src/PendingRequest.php1136-1165 tests/HttpClient/HttpClientTest.php1874-1924

Request Object in Tests

The Request object provides access to request details in assertions:

Property/MethodDescription
url()Full request URL
method()HTTP method (GET, POST, etc.)
headers()All headers as array
hasHeader($key, $value)Check if header exists
body()Raw request body
data()Parsed data (form or JSON)
isJson()Check if JSON request
isForm()Check if form request
isMultipart()Check if multipart request
hasFile($name, $value, $filename)Check if file attached
$request['key']Array access to data

Sources: src/http-client/src/Request.php14-279 tests/HttpClient/HttpClientTest.php524-815


Advanced Features

Connection Configuration

Named connections can be configured with pooling parameters:


Sources: src/http-client/src/Factory.php436-444 src/http-client/src/PendingRequest.php1249-1265

Asynchronous Requests

Requests can be made asynchronously using async():


Sources: src/http-client/src/PendingRequest.php1219-1226 src/http-client/src/PendingRequest.php854-886

Debugging

PendingRequest provides debugging methods:


These use Symfony VarDumper to output request and option details.

Sources: src/http-client/src/PendingRequest.php594-621

Cookie Management


Sources: src/http-client/src/PendingRequest.php420-429 src/http-client/src/Response.php246-252

Transfer Statistics

Response objects have access to transfer statistics:


Sources: src/http-client/src/Response.php186-260 src/http-client/src/PendingRequest.php959-965


Usage Examples

Basic Requests


Complex Request


File Upload


Testing Example


Sources: tests/HttpClient/HttpClientTest.php76-1047 tests/HttpClient/HttpClientTest.php1547-1850

Refresh this wiki

On this page