VOOZH about

URL: https://deepwiki.com/hypervel/api-client/7.2-request-middleware

⇱ Request Middleware | hypervel/api-client | DeepWiki


Loading...
Menu

Request Middleware

This page documents request middleware, which processes and transforms ApiRequest objects before they are sent to the HTTP transport layer. Request middleware executes after the request is built but before HTTP execution occurs, allowing modification of URLs, headers, body content, and other request properties.

For information about response middleware that processes responses after HTTP execution, see Response Middleware. For an overview of the middleware system architecture, see Middleware Overview. For guidance on creating custom middleware, see Creating Custom Middleware.

Purpose and Scope

Request middleware provides a mechanism to intercept and modify outgoing HTTP requests in the pipeline. Each middleware receives an ApiRequest object, can perform transformations or validations, and must return an ApiRequest object (either modified or unchanged) to continue the pipeline.

Request middleware executes:

  • After the request is built by PendingRequest
  • Before the request is sent via the HTTP client
  • In the order defined in the middleware array

Request Middleware Lifecycle

The following diagram illustrates when request middleware executes within the complete request lifecycle:


Sources: src/PendingRequest.php265-291

The lifecycle phases are:

PhaseLocationDescription
Request BuildingPendingRequest::sendRequest()Initial request construction from method arguments
Request WrappingLine 273HTTP request wrapped in ApiRequest object
Middleware CheckLine 274enableMiddleware flag determines if pipeline executes
Middleware ExecutionLines 293-299Request flows through middleware pipeline
PSR-7 ConversionLine 277Final ApiRequest converted to PSR-7 format
HTTP ExecutionLine 278Converted request sent via HTTP client

Sources: src/PendingRequest.php265-299

The ApiRequest Object

Request middleware operates on ApiRequest instances, which provide a fluent interface for modifying HTTP requests. The class structure is:


Sources: src/ApiRequest.php1-241

Key Methods Available to Middleware

Request middleware can call any method on ApiRequest to transform the request:

Method CategoryMethodsPurpose
HTTP MethodwithMethod()Modify HTTP verb (GET, POST, etc.)
URL ManipulationwithUrl()Change request URL
HeaderswithHeader(), withHeaders(), withAddedHeader(), withoutHeader()Add, modify, or remove headers
AuthenticationwithToken()Add authorization tokens
Content TypeasJson(), asForm(), contentType(), acceptJson()Set content negotiation headers
Body ContentwithBody(), withData(), withoutData()Modify request body
ContextwithContext(), context()Store metadata for downstream middleware

Sources: src/ApiRequest.php22-241

Request Middleware Execution Flow

The following diagram shows the code flow when request middleware executes:


Sources: src/PendingRequest.php265-299

Middleware Instantiation and Caching

The system instantiates middleware classes with specific behavior:


Sources: src/PendingRequest.php309-326

Key characteristics of middleware instantiation:

AspectImplementationLocation
Constructor InjectionEach middleware receives $client->getConfig()Line 322
Caching StrategyMiddleware instances cached in static propertyLine 318-319
Cache KeyClass name used as cache keyLine 318, 322
Cache LifetimePersists for entire PHP requestLine 51
Cache ClearingManual via flushCache() methodLines 249-252

Sources: src/PendingRequest.php51 src/PendingRequest.php309-326

Middleware Context and Options

Request middleware can access contextual data through the HasContext trait. The system automatically injects middleware options into the request's context:


Sources: src/PendingRequest.php293-299 src/PendingRequest.php84-92

Middleware can access options using:


Sources: src/ApiRequest.php14

Request Middleware Configuration

Request middleware is configured at multiple levels with specific precedence:


Sources: src/PendingRequest.php53-62 src/PendingRequest.php107-142

Configuration Methods

MethodEffectUse Case
withRequestMiddleware(array)Replaces all request middlewareOverride client defaults for specific request
withAddedRequestMiddleware(array)Appends to existing middlewareAdd request-specific middleware while keeping defaults
enableMiddleware()Enables middleware pipelineRe-enable after disabling
disableMiddleware()Disables middleware pipelineSkip all middleware for specific request
withMiddlewareOptions(array)Sets options for middleware contextPass configuration to middleware

Sources: src/PendingRequest.php65-102 src/PendingRequest.php107-142

Common Use Cases

Request middleware is commonly used for:

1. Request Signing and Authentication

Adding signatures, API keys, or computed authentication headers before sending.

Implementation Point: Middleware operates on ApiRequest::withHeader() or ApiRequest::withToken()

2. URL Transformation

Modifying or normalizing request URLs, adding version prefixes, or tenant-specific paths.

Implementation Point: Middleware uses ApiRequest::withUrl() with callback or string

3. Request Logging and Debugging

Capturing outgoing request details for logging or debugging purposes.

Implementation Point: Middleware reads from ApiRequest without modifying, logs to external system

4. Rate Limiting and Throttling

Implementing client-side rate limiting before requests are sent.

Implementation Point: Middleware checks state, potentially delays or throws exceptions

5. Data Transformation

Converting or normalizing request data before serialization.

Implementation Point: Middleware uses ApiRequest::withData() or ApiRequest::withBody()

6. Header Standardization

Ensuring required headers are present on all requests.

Implementation Point: Middleware uses ApiRequest::withHeaders() to add missing headers

Sources: src/ApiRequest.php22-241

Technical Details

Middleware Array Structure

The request middleware array contains class names or callables:


Sources: src/PendingRequest.php38-45

Pipeline Execution

The pipeline executes middleware in array order. Each middleware must:

  1. Accept an ApiRequest parameter
  2. Return an ApiRequest instance
  3. Either be invokable (__invoke()) or have a handle() method

The pipeline uses Hypervel\Support\Pipeline which implements the pipe-and-filter pattern.

Sources: src/PendingRequest.php49 src/PendingRequest.php293-299

Request Immutability Pattern

ApiRequest follows an immutable design pattern where modification methods return new instances:


This ensures middleware cannot inadvertently corrupt the request state for other middleware in the pipeline.

Sources: src/ApiRequest.php22-241

Disabling Request Middleware

Request middleware can be disabled for specific requests:


Sources: src/PendingRequest.php74-82 src/PendingRequest.php274-277

This is useful when:

  • Debugging specific requests without middleware interference
  • Bypassing middleware for internal or health check requests
  • Performance optimization for high-frequency requests that don't need middleware

Sources: src/PendingRequest.php265-299