VOOZH about

URL: https://deepwiki.com/hypervel/api-client/7.3-response-middleware

⇱ Response Middleware | hypervel/api-client | DeepWiki


Loading...
Menu

Response Middleware

Purpose and Scope

This document covers response middleware in the hypervel/api-client package. Response middleware processes ApiResponse objects after HTTP execution but before resource creation, enabling transformations, error handling, caching, and logging of incoming HTTP responses.

For information about request middleware that processes outgoing requests, see Request Middleware. For general middleware concepts and the pipeline architecture, see Middleware Overview. For implementing custom middleware classes, see Creating Custom Middleware.


Overview

Response middleware executes after the HTTP client receives a response from the external API but before the response is wrapped in an ApiResource. This positioning allows middleware to:

  • Transform response data before it reaches application code
  • Handle HTTP errors and convert them to exceptions or alternate responses
  • Cache responses for subsequent requests
  • Log response details for debugging or auditing
  • Normalize response structures across different APIs

Response middleware is configured separately from request middleware, allowing distinct concerns to be handled at appropriate lifecycle stages.

Sources: src/PendingRequest.php42-45 src/PendingRequest.php284-290


Response Middleware Pipeline

The following diagram illustrates how response middleware processes ApiResponse objects through the pipeline:


Sources: src/PendingRequest.php284-290 src/PendingRequest.php301-307


Configuration Methods

The PendingRequest class provides several methods for configuring response middleware:

MethodDescriptionBehavior
withResponseMiddleware(array $middleware)Replace all response middlewareOverwrites existing middleware array
withAddedResponseMiddleware(array $middleware)Append to existing middlewareMerges with current middleware array
enableMiddleware()Enable middleware processingSets $enableMiddleware = true
disableMiddleware()Disable middleware processingSets $enableMiddleware = false
withMiddlewareOptions(array $options)Set middleware configurationOptions passed via context to all middleware

All configuration methods return static, enabling fluent method chaining.

Sources: src/PendingRequest.php127-142 src/PendingRequest.php67-82 src/PendingRequest.php87-92


Execution Lifecycle

The following sequence diagram shows the detailed execution flow of response middleware:


Key lifecycle points:

  1. Line 284: ApiResponse wrapper is created from the PSR-7 response
  2. Line 286: Conditional check of $this->enableMiddleware flag
  3. Line 287: Call to handleMiddlewareResponse() if enabled
  4. Line 304: Context injection with withContext('options', $this->middlewareOptions)
  5. Line 305: Pipeline execution through createMiddleware($this->responseMiddleware)
  6. Line 290: Resource creation with $this->resource::make($response, $request)

Sources: src/PendingRequest.php284-290 src/PendingRequest.php301-307


Middleware Instantiation and Caching

The createMiddleware() method handles middleware instantiation with built-in caching:


Implementation details:

  • Line 309-326: The createMiddleware() method processes the middleware array
  • Line 318: Cache lookup: static::$cachedMiddleware[$value] ?? null
  • Line 322: Middleware instantiation: new $value($this->client->getConfig())
  • Line 51: Static cache storage: protected static $cachedMiddleware = []
  • Line 249-252: Cache flushing: flushCache() method

Each middleware class is instantiated once and passed the ApiClient configuration object. Cached instances are reused across multiple requests within the same PHP process.

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


Common Use Cases

Error Handling

Response middleware can intercept error responses and convert them to exceptions or normalized error structures:

  • Check $response->status() for error codes (4xx, 5xx)
  • Parse error response bodies for API-specific error details
  • Throw custom exceptions with contextual information
  • Transform error responses to consistent formats

Response Caching

Middleware can implement caching strategies for API responses:

  • Check cache before allowing request to proceed (combined with request middleware)
  • Store successful responses in cache (Redis, file system, etc.)
  • Set cache expiration based on response headers (Cache-Control, Expires)
  • Implement cache invalidation strategies

Data Transformation

Normalize response data structures across different API versions or endpoints:

  • Convert date strings to standardized formats
  • Rename fields to match application conventions
  • Flatten nested response structures
  • Add computed fields or metadata

Response Logging

Log response details for debugging, auditing, or monitoring:

  • Record response status codes and headers
  • Log response body (with optional truncation for large responses)
  • Measure response time (requires coordination with request middleware)
  • Track API usage patterns and error rates

Context and Configuration

Response middleware receives configuration through the context system:

Context Injection

At src/PendingRequest.php304 the response receives context before middleware processing:

$response->withContext('options', $this->middlewareOptions)

Middleware can access these options using the HasContext trait methods on the ApiResponse object.

Middleware Options Structure

Options are set via withMiddlewareOptions() on PendingRequest:


Configuration Flow


Sources: src/PendingRequest.php87-92 src/PendingRequest.php304 src/PendingRequest.php53-62


Middleware Order

Middleware executes in the order specified in the responseMiddleware array. The first middleware receives the ApiResponse first, and each subsequent middleware receives the response returned by the previous middleware.

Typical ordering strategies:

  1. Error Handler First: Catches HTTP errors before other processing
  2. Cache Handler Second: Stores successful responses after error checking
  3. Transformation Third: Normalizes data structure
  4. Logging Last: Records final response state after all transformations

The order can be controlled by:

  • Setting the initial array in ApiClient configuration
  • Using withResponseMiddleware() to completely replace the array
  • Using withAddedResponseMiddleware() to append middleware to existing array

Sources: src/PendingRequest.php127-142


Integration with ApiResponse

Response middleware operates on ApiResponse objects, which extend the base HTTP response class and implement the HasContext trait:

ApiResponse FeatureMiddleware Usage
withStatus(int $code)Modify status code (e.g., normalize error codes)
withHeader(string $name, $value)Add or modify response headers
withBody(StreamInterface $body)Replace response body content
status()Read HTTP status code
headers()Access response headers
body()Read response body content
withContext(string $key, $value)Store contextual data
context(string $key = null)Retrieve contextual data

All modification methods return a new immutable instance, following PSR-7 conventions.

For detailed information about ApiResponse methods, see ApiResponse. For context management details, see HasContext Trait.

Sources: src/PendingRequest.php301-307


Disabling Response Middleware

Response middleware can be disabled for specific requests:


When disabled (line 286-287), the ApiResponse bypasses the pipeline and proceeds directly to resource creation. This is useful for:

  • Debugging middleware issues
  • Performance-sensitive operations where middleware overhead is unnecessary
  • Testing raw API responses without transformation

Sources: src/PendingRequest.php77-82 src/PendingRequest.php286-288