VOOZH about

URL: https://deepwiki.com/hypervel/support/4.3-http-client

⇱ HTTP Client | hypervel/support | DeepWiki


Loading...
Menu

HTTP Client

This document covers the HTTP client functionality provided by the Http facade, which enables making HTTP requests to external APIs and services. The client is built on top of Guzzle and provides a fluent interface for request configuration, middleware support, automatic retries, connection pooling, and comprehensive testing capabilities.

For URL generation and routing, see URL Generation. For handling incoming HTTP requests, see Request and Response.

Architecture Overview

The HTTP client system consists of multiple layers that work together to provide a flexible and testable HTTP interface.

HTTP Client Architecture


Sources: src/Facades/Http.php1-121

Basic Usage

The Http facade provides static methods for making HTTP requests. Each method returns either a Response object or a PromiseInterface for async requests.

Making HTTP Requests

MethodPurposeExample Usage
get()GET requestHttp::get('https://api.example.com/users')
post()POST requestHttp::post('https://api.example.com/users', ['name' => 'John'])
put()PUT requestHttp::put('https://api.example.com/users/1', ['name' => 'Jane'])
patch()PATCH requestHttp::patch('https://api.example.com/users/1', ['status' => 'active'])
delete()DELETE requestHttp::delete('https://api.example.com/users/1')
head()HEAD requestHttp::head('https://api.example.com/health')
send()Custom methodHttp::send('OPTIONS', 'https://api.example.com')

The get() and head() methods accept query parameters as the second argument, while other methods accept request body data.

Sources: src/Facades/Http.php87-93

Request Configuration

The HTTP client provides a fluent interface for configuring requests before sending them. Each configuration method returns a PendingRequest instance that can be further chained.

Request Configuration Flow


Base URL and Headers

Http::baseUrl('https://api.example.com')
 ->withHeaders(['X-API-Key' => 'secret'])
 ->withHeader('Accept-Language', 'en')
 ->get('/users');

Available header methods:

  • withHeaders(array) - Set multiple headers
  • withHeader(string, mixed) - Set single header
  • replaceHeaders(array) - Replace all headers
  • withUserAgent(string) - Set User-Agent header

Sources: src/Facades/Http.php50-68

Authentication

The client supports multiple authentication methods:

MethodTypeUsage
withBasicAuth()HTTP BasicwithBasicAuth('username', 'password')
withDigestAuth()HTTP DigestwithDigestAuth('username', 'password')
withToken()Bearer TokenwithToken('token', 'Bearer')

Sources: src/Facades/Http.php64-66

Body Formats

Configure how request data is encoded:

MethodFormatContent-Type
asJson()JSONapplication/json
asForm()Form URL-encodedapplication/x-www-form-urlencoded
asMultipart()Multipart formmultipart/form-data
withBody()Raw bodyCustom

For file uploads, use attach():

Http::attach('document', $contents, 'report.pdf')
 ->post('https://api.example.com/upload');

Sources: src/Facades/Http.php51-56

Query Parameters

Add query string parameters using:

  • withQueryParameters(array) - Add query parameters to the request
  • withUrlParameters(array) - Replace URL template placeholders

Sources: src/Facades/Http.php57-68

Timeouts and Redirects

Control connection behavior:

MethodPurposeDefault
timeout(int|float)Request timeout in seconds30
connectTimeout(int|float)Connection timeoutNone
maxRedirects(int)Maximum redirects to follow5
withoutRedirecting()Disable redirect following-
withoutVerifying()Disable SSL verification-

Sources: src/Facades/Http.php70-76

Cookies

Set cookies for the request:

Http::withCookies(['session_id' => '123'], 'example.com')
 ->get('https://example.com/api');

Sources: src/Facades/Http.php69

Middleware System

The HTTP client supports middleware for intercepting and modifying requests and responses. Middleware can be applied globally or per-request.

Middleware Flow


Global Middleware

Global middleware applies to all requests:

Http::globalMiddleware(function ($handler) {
 return function ($request, $options) use ($handler) {
 // Modify request
 return $handler($request, $options)->then(
 function ($response) {
 // Modify response
 return $response;
 }
 );
 };
});

Available global middleware methods:

  • globalMiddleware(callable) - Add general middleware
  • globalRequestMiddleware(callable) - Add request-only middleware
  • globalResponseMiddleware(callable) - Add response-only middleware
  • globalOptions(array|\Closure) - Set default options

Sources: src/Facades/Http.php10-13

Request-Specific Middleware

Apply middleware to individual requests:

MethodPurpose
withMiddleware(callable)Add general middleware
withRequestMiddleware(callable)Add request middleware
withResponseMiddleware(callable)Add response middleware
beforeSending(callable)Run callback before sending

Sources: src/Facades/Http.php78-81

Retry Logic

The client supports automatic retries with configurable backoff strategies.

Basic Retry Configuration

Http::retry(3, 100) // Retry 3 times with 100ms delay
 ->get('https://api.example.com/data');

Advanced Retry Configuration

The retry() method accepts:

ParameterTypeDescription
$timesint|arrayNumber of retries or array of delays
$sleepMillisecondsint|\ClosureDelay between retries or callback
$whencallable|nullCondition to determine if retry should occur
$throwboolWhether to throw on final failure

Conditional Retries

Http::retry(3, 100, function ($exception, $request) {
 return $exception instanceof ConnectionException;
})

Sources: src/Facades/Http.php76

Connection Management

The HTTP client supports multiple named connections with independent configurations and connection pooling.

Connection Architecture


Registering Connections

Define named connections with specific configurations:

Http::registerConnection('api', [
 'base_uri' => 'https://api.example.com',
 'timeout' => 30,
 'headers' => [
 'X-API-Key' => 'secret',
 ],
]);

Using Connections

Switch to a specific connection for a request:

Http::connection('api')
 ->get('/users');

The connection() method accepts an optional second parameter to override connection configuration:

Http::connection('api', ['timeout' => 60])
 ->get('/slow-endpoint');

Sources: src/Facades/Http.php34-109

Connection Pooling

Enable connection pooling for specific drivers:

MethodPurpose
addPoolable(string)Mark driver as poolable
removePoolable(string)Remove driver from pooling
setPoolables(array)Set all poolable drivers
getPoolables()Get poolable drivers
setReleaseCallback(string, \Closure)Set release callback for driver
getReleaseCallback(string)Get release callback

Sources: src/Facades/Http.php40-44

Testing with Fakes

The HTTP client provides comprehensive testing utilities to fake HTTP responses without making actual network requests.

Testing Architecture


Basic Faking

Fake all HTTP requests:

Http::fake(); // All requests return 200 OK

Fake specific URLs:

Http::fake([
 'https://api.example.com/*' => Http::response(['data' => 'value'], 200),
 'https://cdn.example.com/*' => Http::response('Not Found', 404),
]);

Fake with a callback:

Http::fake(function ($request) {
 if ($request->url() === 'https://api.example.com/users') {
 return Http::response(['users' => []], 200);
 }
 return Http::response(null, 404);
});

Sources: src/Facades/Http.php17-19

Response Sequences

Create sequences of responses for multiple requests to the same endpoint:

Http::fakeSequence('https://api.example.com/status')
 ->push('pending', 200)
 ->push('processing', 200)
 ->push('complete', 200);

// First request returns 'pending'
// Second request returns 'processing'
// Third request returns 'complete'

Or create a sequence without URL binding:

$sequence = Http::sequence()
 ->push('first', 200)
 ->push('second', 200)
 ->whenEmpty(Http::response('default', 200));

Http::fake(['*' => $sequence]);

Sources: src/Facades/Http.php16-18

Stub URL

Stub a specific URL without affecting other requests:

Http::stubUrl('https://api.example.com/users', 
 Http::response(['users' => []], 200)
);

Sources: src/Facades/Http.php19

Failed Connections

Simulate connection failures:

Http::fake([
 'https://unreliable.com/*' => Http::failedConnection('Connection timeout'),
]);

Sources: src/Facades/Http.php15

Preventing Stray Requests

Prevent any non-faked requests from being made during tests:

Http::preventStrayRequests();

Http::fake([
 'https://api.example.com/*' => Http::response(['data' => 'value'], 200),
]);

// This will throw an exception
Http::get('https://other-api.example.com/data');

Control stray request prevention:

  • preventStrayRequests(bool) - Enable/disable prevention
  • preventingStrayRequests() - Check if prevention is enabled
  • allowStrayRequests() - Disable prevention

Sources: src/Facades/Http.php20-22

Assertions

Verify that requests were sent as expected:

Request Assertions

MethodPurpose
assertSent(callable)Assert a request matching the callback was sent
assertSentInOrder(array)Assert requests were sent in specific order
assertNotSent(callable)Assert no request matching the callback was sent
assertNothingSent()Assert no requests were sent
assertSentCount(int)Assert exact number of requests were sent
assertSequencesAreEmpty()Assert all sequences were consumed

Example assertions:

Http::fake();

Http::post('https://api.example.com/users', ['name' => 'John']);

Http::assertSent(function ($request) {
 return $request->url() === 'https://api.example.com/users' &&
 $request['name'] === 'John';
});

Http::assertSentCount(1);

Sources: src/Facades/Http.php24-29

Recording Requests

Access recorded requests for custom assertions:

$requests = Http::recorded(function ($request) {
 return $request->url() === 'https://api.example.com/users';
});

// Returns Collection of [Request, Response] pairs

Sources: src/Facades/Http.php30

Async Requests

The HTTP client supports asynchronous requests that return promises instead of blocking for the response.

Making Async Requests

Enable async mode:

$promise = Http::async()->get('https://api.example.com/data');

$promise->then(
 function ($response) {
 // Handle successful response
 },
 function ($exception) {
 // Handle error
 }
);

The async() method returns a PendingRequest configured for asynchronous execution. The HTTP methods (get(), post(), etc.) return a GuzzleHttp\Promise\PromiseInterface instead of a Response.

Sources: src/Facades/Http.php103-104

Error Handling

Configure how the client handles errors:

MethodPurpose
throw(callable|null)Throw exception on client/server errors
throwIf(callable|bool)Conditionally throw exception
throwUnless(callable|bool)Throw exception unless condition is true

Example:

Http::throw()
 ->get('https://api.example.com/data'); // Throws on 4xx/5xx

Http::throwIf(fn($response) => $response->failed())
 ->get('https://api.example.com/data');

Sources: src/Facades/Http.php82-84

Debugging

Debug requests and responses:

MethodPurpose
dump()Dump request/response details and continue
dd()Dump request/response details and die
Http::dd()->get('https://api.example.com/data');

Sources: src/Facades/Http.php85-86

Additional Configuration

Guzzle Options

Pass custom Guzzle options:

Http::withOptions([
 'allow_redirects' => false,
 'proxy' => 'tcp://localhost:8125',
 'cert' => ['/path/to/cert.pem', 'password'],
])

Sources: src/Facades/Http.php77

Sink

Stream response to a file or resource:

Http::sink('/path/to/file.pdf')
 ->get('https://example.com/document.pdf');

Sources: src/Facades/Http.php73

Content Type

Set content type explicitly:

Http::contentType('application/xml')
 ->withBody('<xml>...</xml>')
 ->post('https://api.example.com/data');

Sources: src/Facades/Http.php58-60

Method Summary

Factory Methods (Static)

These methods configure the factory itself and affect all requests:

  • Global middleware configuration
  • Connection registration
  • Fake response configuration
  • Test assertions

PendingRequest Methods (Fluent)

These methods configure individual requests and can be chained:

  • Request configuration (headers, auth, body)
  • Middleware attachment
  • Error handling
  • HTTP method execution

The facade delegates to \Hypervel\HttpClient\Factory, which creates PendingRequest instances for fluent configuration and ultimately executes requests via Guzzle's ClientInterface.

Sources: src/Facades/Http.php1-121