VOOZH about

URL: https://deepwiki.com/hypervel/api-client/4.5-apirequest

⇱ ApiRequest | hypervel/api-client | DeepWiki


Loading...
Menu

ApiRequest

This page documents the ApiRequest class, which provides a fluent interface for building PSR-7 compliant HTTP requests. The class serves as a mutable wrapper around PSR-7 request objects, enabling method chaining and lazy evaluation of request modifications.

For information about how requests are executed, see PendingRequest. For details on request lifecycle middleware, see Request Middleware. For configuration of request parameters at the client level, see Request Configuration.


Overview

The ApiRequest class extends HttpClientRequest from the hypervel/http-client package and implements the builder pattern for constructing HTTP requests. It maintains an internal PSR-7 RequestInterface instance and provides fluent methods to modify request properties including method, URL, headers, and body content.

Key Characteristics:

  • Extends Hypervel\HttpClient\Request
  • Uses the HasContext trait for contextual data management
  • Implements fluent interface pattern with static return types
  • Provides lazy evaluation of data changes through the dataChanged flag
  • Supports both JSON and form-encoded request bodies
  • Converts to PSR-7 compliant RequestInterface via toPsrRequest()

Sources: src/ApiRequest.php1-241


Class Structure and Inheritance


Inheritance Chain:

ClassPackagePurpose
RequestInterfacepsr/http-messagePSR-7 standard HTTP request interface
HttpClientRequesthypervel/http-clientBase request wrapper with data handling
ApiRequesthypervel/api-clientFluent builder for API requests

Sources: src/ApiRequest.php12-14


HTTP Method and URL Configuration

The ApiRequest class provides methods to configure the HTTP method and URL for the request.

Method Configuration

The withMethod() method sets the HTTP request method by delegating to the underlying PSR-7 request object:

withMethod(string $method): static

Implementation:

  • Calls $this->request->withMethod($method) on the wrapped PSR-7 request
  • Returns $this for method chaining
  • Accepts any valid HTTP method string (GET, POST, PUT, DELETE, etc.)

Sources: src/ApiRequest.php24-29

URL Configuration

The withUrl() method configures the request URL with support for both string URLs and callable transformers:

withUrl(callable|string $url, bool $preserveHost = false): static

Parameters:

ParameterTypeDescription
$urlcallable|stringTarget URL or callable that transforms current URL
$preserveHostboolWhether to preserve the Host header from original request

Behavior:

  • If $url is a callable, it receives the current URL string and returns a modified URL
  • Wraps the URL in a GuzzleHttp\Psr7\Uri object
  • Delegates to $this->request->withUri() on the PSR-7 request
  • The $preserveHost parameter controls whether the Host header is updated

Sources: src/ApiRequest.php34-43


Header Management

The ApiRequest class provides comprehensive methods for managing HTTP request headers.

Header Methods Overview


Sources: src/ApiRequest.php46-177

Header Setting Methods

MethodPurposeBehavior
withHeader()Set single header, replacing existingCalls PSR-7 withHeader() which replaces all values
withHeaders()Set multiple headers, replacing existingIterates and calls withHeader() for each
withAddedHeader()Add single header value without replacingCalls PSR-7 withAddedHeader() which appends value
withAddedHeaders()Add multiple header valuesIterates and calls withAddedHeader() for each
withoutHeader()Remove single headerCalls PSR-7 withoutHeader()
withoutHeaders()Remove multiple headersIterates and calls withoutHeader() for each

Sources: src/ApiRequest.php48-177

Specialized Header Methods

The class provides convenience methods for common header configurations:

Content-Type Management:

contentType(string $contentType): static
asForm(): static
asJson(): static

Accept Header Management:

accept(string $contentType): static
acceptJson(): static

Authentication:

withToken(string $token, string $type = 'Bearer'): static
  • Constructs and sets the Authorization header
  • Default type is 'Bearer'
  • Formats as: {type} {token}

Sources: src/ApiRequest.php124-129

User Agent:

withUserAgent(bool|string $userAgent): static
  • Sets the User-Agent header
  • Trims the provided string

Sources: src/ApiRequest.php134-137


Data and Body Management

The ApiRequest class manages request body content through two mechanisms: raw body strings and structured data arrays with automatic serialization.

Data Change Tracking

The class uses a dataChanged flag to track when data modifications require body regeneration:


Sources: src/ApiRequest.php17-19

Data Methods

MethodSignaturePurpose
withData()withData(array $data): staticMerges data with existing data array
withoutData()withoutData(array $data): staticRemoves specified keys from data array
withBody()withBody(string $body): staticSets raw body string directly

Data Method Behavior:

withData() Implementation:

  • Retrieves current data via $this->data() (inherited method)
  • Merges new data using array_merge()
  • Sets $this->dataChanged = true to trigger serialization
  • Returns $this for chaining

Sources: src/ApiRequest.php193-199

withoutData() Implementation:

  • Retrieves current data to ensure it's populated
  • Unsets each specified key
  • Implicitly marks data as changed (requires serialization)

Sources: src/ApiRequest.php204-212

withBody() Implementation:

  • Creates new Hyperf\Engine\Http\Stream with the body string
  • Calls PSR-7 withBody() to replace body
  • Sets $this->dataChanged = false since raw body bypasses data serialization

Sources: src/ApiRequest.php182-188

Content Type Transitions

The asForm() and asJson() methods handle content type transitions intelligently:

Form-to-JSON Transition (asJson()):

if ($this->isForm()) {
 if (!$this->data) {
 $this->parameters(); // Parse form data from body
 }
 $this->dataChanged = true;
}

When switching from form to JSON, the method:

  1. Checks if current content is form-encoded
  2. Parses existing body into data array via parameters()
  3. Marks data as changed to trigger JSON serialization

Sources: src/ApiRequest.php94-105

JSON-to-Form Transition (asForm()):

if ($this->isJson() || !$this->hasHeader('Content-Type')) {
 if (!$this->data) {
 $this->json(); // Parse JSON data from body
 }
 $this->dataChanged = true;
}

When switching from JSON to form (or setting initial content type):

  1. Checks if current content is JSON or no content type is set
  2. Parses existing body into data array via json()
  3. Marks data as changed to trigger form serialization

Sources: src/ApiRequest.php78-89


PSR-7 Compliance and Conversion

The ApiRequest class maintains PSR-7 compliance through lazy evaluation and conversion methods.

Conversion Flow


Sources: src/ApiRequest.php217-224

toPsrRequest() Method

The toPsrRequest() method converts the builder to a PSR-7 compliant request:

public function toPsrRequest(): RequestInterface

Implementation:

  1. Checks if $this->dataChanged is true
  2. If changed, calls applyChangedData() to serialize data to body
  3. Returns $this->request (the PSR-7 RequestInterface)

Sources: src/ApiRequest.php217-224

Data Serialization (applyChangedData())

The private applyChangedData() method handles serialization based on content type:


Serialization Logic:

Content TypeSerialization MethodOutput Format
application/x-www-form-urlencodedhttp_build_query($this->data, '', '&')URL-encoded string
application/json or no typejson_encode($this->data)JSON string
OtherRaw data array (unusual case)Array cast to string

Sources: src/ApiRequest.php226-240


Integration with Request Lifecycle

The ApiRequest class integrates into the larger request lifecycle orchestrated by PendingRequest.

Request Building Flow


Sources: src/ApiRequest.php1-241

Context Management

The ApiRequest class uses the HasContext trait to store and retrieve contextual metadata:


For detailed information on context management, see HasContext Trait.

Sources: src/ApiRequest.php14


Method Summary

Complete Method Reference

CategoryMethodReturnsPurpose
HTTP ConfigurationwithMethod(string)staticSet HTTP method
withUrl(callable|string, bool)staticSet request URL
HeaderswithHeader(string, string)staticSet single header
withHeaders(array)staticSet multiple headers
withAddedHeader(string, string)staticAdd header value
withAddedHeaders(array)staticAdd multiple header values
withoutHeader(string)staticRemove header
withoutHeaders(array)staticRemove multiple headers
Content TypecontentType(string)staticSet Content-Type header
asForm()staticSet form content type
asJson()staticSet JSON content type
accept(string)staticSet Accept header
acceptJson()staticSet JSON accept header
AuthenticationwithToken(string, string)staticSet authorization token
User AgentwithUserAgent(bool|string)staticSet user agent
Body & DatawithBody(string)staticSet raw body string
withData(array)staticMerge data into request
withoutData(array)staticRemove data keys
ConversiontoPsrRequest()RequestInterfaceConvert to PSR-7 request

Sources: src/ApiRequest.php24-224


Key Design Patterns

The ApiRequest class implements several important design patterns:

Fluent Interface Pattern

All builder methods return static, enabling method chaining:

$request->withMethod('POST')
 ->withUrl('https://api.example.com/users')
 ->asJson()
 ->withData(['name' => 'John'])
 ->withToken('abc123');

Sources: src/ApiRequest.php24-212

Lazy Evaluation

Data serialization is deferred until toPsrRequest() is called, allowing multiple data modifications without repeated serialization overhead.

Sources: src/ApiRequest.php217-240

Immutable PSR-7 Wrapping

Each modification creates a new PSR-7 request object following PSR-7 immutability requirements, while the ApiRequest builder itself is mutable:

$this->request = $this->request->withMethod($method);

The builder reassigns $this->request with each PSR-7 operation, maintaining the PSR-7 contract while providing a mutable interface.

Sources: src/ApiRequest.php26 src/ApiRequest.php40 src/ApiRequest.php59


Sources: src/ApiRequest.php1-241