### Perform HTTP GET Request
Source: https://context7.com/nategood/httpful/llms.txt
Make a GET request and automatically parse the JSON response. Custom headers can be added using magic __call. For a quick one-liner that sends immediately, use `getQuick()`.
```php
expectsJson()
->withXTrivialHeader('Just a demo') // custom header via magic __call
->send();
echo $response->body->name; // "Nate Good"
echo $response->code; // 200
echo $response->content_type; // "application/json"
// Quick one-liner (sends immediately)
$response = Request::getQuick('https://api.github.com/users/nategood', 'json');
echo $response->body->public_repos;
```
--------------------------------
### Install Httpful via Composer
Source: https://context7.com/nategood/httpful/llms.txt
Use Composer to add Httpful to your project dependencies.
```json
{
"require": {
"nategood/httpful": "*"
}
}
```
--------------------------------
### Request::get() — HTTP GET request
Source: https://context7.com/nategood/httpful/llms.txt
Creates a GET request to the given URI. Optionally accepts a MIME type hint for automatic response parsing. Returns a chainable `Request` object; call `->send()` to execute.
```APIDOC
## Request::get()
### Description
Creates a GET request to the specified URI. It supports automatic response parsing based on the Content-Type header and allows for custom headers.
### Method
GET
### Endpoint
`/` (relative to the base URI)
### Parameters
#### Query Parameters
None explicitly mentioned for the factory method itself, but can be appended to the URI.
#### Request Body
Not applicable for GET requests.
### Request Example
```php
expectsJson()
->withXTrivialHeader('Just a demo') // custom header via magic __call
->send();
echo $response->body->name;
echo $response->code;
echo $response->content_type;
// Quick one-liner (sends immediately)
$response = Request::getQuick('https://api.github.com/users/nategood', 'json');
echo $response->body->public_repos;
```
### Response
#### Success Response (200)
- **body** (object) - The parsed response body (e.g., JSON object, XML structure).
- **code** (integer) - The HTTP status code.
- **content_type** (string) - The Content-Type of the response.
#### Response Example
```json
{
"name": "Nate Good",
"public_repos": 10,
"code": 200,
"content_type": "application/json"
}
```
```
--------------------------------
### Make GET Request with Custom Header and JSON Expectation
Source: https://github.com/nategood/httpful/blob/master/README.md
Use this snippet to make a GET request to a specified URL, expect a JSON response, and include a custom header. The response body is automatically parsed as JSON.
```php
expectsJson()
->withXTrivialHeader('Just as a demo')
->send();
echo "{$response->body->name} joined GitHub on " .
date('M jS', strtotime($response->body->created_at)) ."\n";
```
--------------------------------
### Request::put() / Request::patch() / Request::delete() — Mutating HTTP methods
Source: https://context7.com/nategood/httpful/llms.txt
Factory methods for PUT, PATCH, and DELETE requests, all following the same chainable pattern as GET and POST. These are used for updating or deleting resources.
```APIDOC
## Request::put() / Request::patch() / Request::delete()
### Description
Provides factory methods for PUT, PATCH, and DELETE HTTP requests. These methods allow for updating existing resources (PUT, PATCH) or removing them (DELETE) in a chainable manner, similar to GET and POST.
### Method
PUT, PATCH, DELETE
### Endpoint
`/` (relative to the base URI, typically includes resource identifier)
### Parameters
#### Path Parameters
Typically includes resource identifiers (e.g., `/users/42`).
#### Query Parameters
None explicitly mentioned for the factory methods.
#### Request Body
- **payload** (mixed) - The data to send in the request body, often used for PUT and PATCH to specify the new state of the resource.
- **mime_type** (string, optional) - The MIME type of the payload.
### Request Example
```php
sendsJson()
->body(['name' => 'Bob', 'email' => 'bob@example.com'])
->authenticateWith('apiuser', 'secret')
->send();
// PATCH — partial update
$response = Request::patch('https://api.example.com/users/42')
->sendsJson()
->body(['email' => 'new@example.com'])
->send();
// DELETE
$response = Request::delete('https://api.example.com/users/42')
->authenticateWith('apiuser', 'secret')
->send();
echo $response->code;
```
### Response
#### Success Response (200 or 204)
- **code** (integer) - The HTTP status code (e.g., 200 for success, 204 for No Content on DELETE).
#### Response Example
```
204
```
```
--------------------------------
### Include Httpful Bootstrap (Non-Composer)
Source: https://context7.com/nategood/httpful/llms.txt
For projects not using Composer, include the bootstrap file directly.
```php
useProxy('proxy.corp.example.com', 3128)
->send();
// HTTP proxy with Basic auth
$response = Request::get('https://api.example.com/data')
->useProxy('proxy.corp.example.com', 3128, CURLAUTH_BASIC, 'proxyuser', 'proxypass')
->send();
// SOCKS5 proxy
$response = Request::get('https://api.example.com/data')
->useSocks5Proxy('socks5.corp.example.com', 1080)
->send();
?>
```
--------------------------------
### Configure Authentication (Basic, Digest, NTLM)
Source: https://context7.com/nategood/httpful/llms.txt
Httpful supports HTTP Basic, Digest, and NTLM authentication via chainable methods. Basic auth should only be used over HTTPS.
```php
authenticateWith('username', 'p@ssw0rd')
->send();
// Digest Auth
$response = Request::get('https://api.example.com/digest-protected')
->authenticateWithDigest('username', 'p@ssw0rd')
->send();
// NTLM Auth
$response = Request::get('https://intranet.corp/api/data')
->authenticateWithNTLM('DOMAIN\user', 'p@ssw0rd')
->send();
echo $response->hasErrors() ? 'Auth failed' : 'Authenticated!';
```
--------------------------------
### Composer Dependency Configuration
Source: https://github.com/nategood/httpful/blob/master/README.md
Add this to your composer.json file to include Httpful as a project dependency.
```json
{
"require": {
"nategood/httpful": "*"
}
}
```
--------------------------------
### Redirect Handling
Source: https://context7.com/nategood/httpful/llms.txt
Configure automatic following of HTTP 301/302 redirects. The maximum number of redirects can be specified.
```APIDOC
## Redirect Handling
Automatically follow HTTP 301/302 redirects, with configurable maximum redirect count.
```php
followRedirects()
->send();
// Limit to 3 redirects
$response = Request::get('http://example.com/redirect-me')
->followRedirects(3)
->send();
// Disable redirect following
$response = Request::get('http://example.com/redirect-me')
->doNotFollowRedirects()
->send();
echo $response->code; // e.g. 200 or 302
```
```
--------------------------------
### Perform Metadata HTTP Requests (HEAD, OPTIONS)
Source: https://context7.com/nategood/httpful/llms.txt
Send HEAD or OPTIONS requests to inspect endpoint capabilities or response headers without downloading a body. The response code and headers are accessible.
```php
send();
echo $response->code; // 200 or 404
echo $response->headers['Content-Type']; // "application/json"
// OPTIONS — discover allowed methods
$response = Request::options('https://api.example.com/users')->send();
echo $response->headers['Allow']; // "GET, POST, HEAD, OPTIONS"
```
--------------------------------
### Request::head() / Request::options() — Metadata methods
Source: https://context7.com/nategood/httpful/llms.txt
Sends HEAD or OPTIONS requests to inspect endpoint capabilities or response headers without downloading a body.
```APIDOC
## Request::head() / Request::options()
### Description
Factory methods for sending HEAD and OPTIONS HTTP requests. HEAD requests retrieve only the headers of a resource, useful for checking existence or metadata without downloading the body. OPTIONS requests discover the communication options available for a target resource.
### Method
HEAD, OPTIONS
### Endpoint
`/` (relative to the base URI)
### Parameters
None explicitly mentioned for the factory methods themselves.
### Request Example
```php
send();
echo $response->code;
echo $response->headers['Content-Type'];
// OPTIONS — discover allowed methods
$response = Request::options('https://api.example.com/users')->send();
echo $response->headers['Allow'];
```
### Response
#### Success Response (200)
- **code** (integer) - The HTTP status code (e.g., 200 OK, 404 Not Found).
- **headers** (array) - An associative array of response headers.
#### Response Example
```json
{
"code": 200,
"headers": {
"Content-Type": "application/json",
"Allow": "GET, POST, HEAD, OPTIONS"
}
}
```
```
--------------------------------
### Perform Mutating HTTP Requests (PUT, PATCH, DELETE)
Source: https://context7.com/nategood/httpful/llms.txt
Use factory methods for PUT, PATCH, and DELETE requests, following the same chainable pattern. Authentication can be configured using `authenticateWith()`.
```php
sendsJson()
->body(['name' => 'Bob', 'email' => 'bob@example.com'])
->authenticateWith('apiuser', 'secret')
->send();
// PATCH — partial update
$response = Request::patch('https://api.example.com/users/42')
->sendsJson()
->body(['email' => 'new@example.com'])
->send();
// DELETE
$response = Request::delete('https://api.example.com/users/42')
->authenticateWith('apiuser', 'secret')
->send();
echo $response->code; // 204
```
--------------------------------
### Set Global Request Template with `Request::ini()`
Source: https://context7.com/nategood/httpful/llms.txt
Configure a global default template for all subsequent requests. This is useful for setting common headers, authentication tokens, or SSL configurations once per application. Remember to reset to library defaults when finished.
```php
addHeader('X-Api-Key', 'global-api-key-123')
->expectsJson()
->withStrictSSL()
->timeoutIn(10);
Request::ini($template);
// All subsequent requests inherit these settings
$users = Request::get('https://api.example.com/users')->send();
$products = Request::get('https://api.example.com/products')->send();
// Reset to library defaults
Request::resetIni();
```
--------------------------------
### Timeout Configuration
Source: https://context7.com/nategood/httpful/llms.txt
Set a request timeout in seconds. The library supports fractional seconds for millisecond precision.
```APIDOC
## Timeout
Set a request timeout in seconds (supports fractional seconds for millisecond precision).
```php
timeoutIn(5) // alias: ->timeout(5)
->send();
} catch (ConnectionErrorException $e) {
echo "Connection failed: " . $e->getMessage();
echo "cURL error #" . $e->getCurlErrorNumber();
}
```
```
--------------------------------
### Proxy Support
Source: https://context7.com/nategood/httpful/llms.txt
Route requests through HTTP, SOCKS4, or SOCKS5 proxies. Proxy authentication is also supported.
```APIDOC
## Proxy Support
Route requests through HTTP, SOCKS4, or SOCKS5 proxies, with optional proxy authentication.
```php
useProxy('proxy.corp.example.com', 3128)
->send();
// HTTP proxy with Basic auth
$response = Request::get('https://api.example.com/data')
->useProxy('proxy.corp.example.com', 3128, CURLAUTH_BASIC, 'proxyuser', 'proxypass')
->send();
// SOCKS5 proxy
$response = Request::get('https://api.example.com/data')
->useSocks5Proxy('socks5.corp.example.com', 1080)
->send();
```
```
--------------------------------
### Create a Custom CSV Handler in PHP
Source: https://github.com/nategood/httpful/blob/master/src/Httpful/Handlers/README.md
Extend MimeHandlerAdapter to create a handler for text/csv. Implement parse to convert CSV strings to arrays and serialize to convert arrays to CSV strings.
```php
withStrictSSL()
->send();
// Disable SSL verification (dev/test only)
$response = Request::get('https://self-signed.example.com/api')
->withoutStrictSSL()
->send();
?>
```
--------------------------------
### Configure Redirect Handling
Source: https://context7.com/nategood/httpful/llms.txt
Control how HTTP redirects are handled. By default, Httpful follows up to 25 redirects. You can limit or disable this behavior.
```php
followRedirects()
->send();
// Limit to 3 redirects
$response = Request::get('http://example.com/redirect-me')
->followRedirects(3)
->send();
// Disable redirect following
$response = Request::get('http://example.com/redirect-me')
->doNotFollowRedirects()
->send();
echo $response->code; // e.g. 200 or 302
?>
```
--------------------------------
### Sending Payloads with `body()` and MIME type methods
Source: https://context7.com/nategood/httpful/llms.txt
Set the request body using the `body()` method and control the `Content-Type` and `Accept` headers using `sends()`, `expects()`, or shorthand methods like `sendsJson()` and `expectsXml()`.
```APIDOC
## `->body()` and MIME type methods — Sending payloads
Set the request body with `body()`, and control Content-Type and Accept headers using `sends()`, `expects()`, or the shorthand `sendsJson()`, `expectsXml()`, etc.
```php
sendsJson()
->expectsJson()
->body(['title' => 'New Item', 'qty' => 5])
->send();
// Send XML
$xmlPayload = '- Widget10
';
$response = Request::post('https://api.example.com/items')
->sends(Mime::XML)
->expects(Mime::JSON)
->body($xmlPayload)
->send();
// Send URL-encoded form data
$response = Request::post('https://api.example.com/login')
->sendsForm()
->body(['username' => 'alice', 'password' => 'secret'])
->send();
```
```
--------------------------------
### Authenticate with Client-Side Certificate
Source: https://context7.com/nategood/httpful/llms.txt
Use this method to authenticate requests using a client-side SSL certificate and key pair. An optional passphrase can also be provided.
```php
authenticateWithCert(
'/path/to/client.crt', // certificate file
'/path/to/client.key', // key file
'keypassphrase', // optional passphrase
'PEM' // encoding (default: PEM)
)
->send();
echo $response->code; // 200
?>
```
--------------------------------
### Set Request Timeout
Source: https://context7.com/nategood/httpful/llms.txt
Configure a timeout for HTTP requests in seconds. Supports fractional seconds for millisecond precision. Handles `ConnectionErrorException`.
```php
timeoutIn(5) // alias: ->timeout(5)
->send();
} catch (ConnectionErrorException $e) {
echo "Connection failed: " . $e->getMessage();
echo "cURL error #" . $e->getCurlErrorNumber();
}
?>
```
--------------------------------
### Additional cURL Options — `addOnCurlOption()`
Source: https://context7.com/nategood/httpful/llms.txt
Pass any raw cURL option directly for settings not exposed by the Httpful API. This allows for fine-grained control over the underlying cURL request.
```APIDOC
## Additional cURL Options — `addOnCurlOption()`
### Description
Pass any raw cURL option directly for settings not exposed by the Httpful API.
### Method
```php
Request::get(string $uri)
->addOnCurlOption(int $option, mixed $value)
->send();
```
### Example
```php
addOnCurlOption(CURLOPT_INTERFACE, 'eth0') // bind to specific network interface
->addOnCurlOption(CURLOPT_ENCODING, 'gzip') // accept gzip encoding
->addOnCurlOption(CURLOPT_LOW_SPEED_LIMIT, 1024) // abort if speed drops below 1KB/s
->addOnCurlOption(CURLOPT_LOW_SPEED_TIME, 30)
->send();
```
```
--------------------------------
### Authentication — Basic, Digest, and NTLM
Source: https://context7.com/nategood/httpful/llms.txt
Httpful supports HTTP Basic, Digest, and NTLM authentication via chainable methods. Basic auth should only be used over HTTPS.
```APIDOC
## Authentication Methods
### Description
Httpful provides chainable methods for configuring Basic, Digest, and NTLM authentication for HTTP requests. It is recommended to use Basic authentication only over HTTPS connections.
### Methods
- `authenticateWith(string $username, string $password)`: For Basic Authentication.
- `authenticateWithDigest(string $username, string $password)`: For Digest Authentication.
- `authenticateWithNTLM(string $username, string $password)`: For NTLM Authentication.
### Request Example
```php
authenticateWith('username', 'p@ssw0rd')
->send();
// Digest Auth
$response = Request::get('https://api.example.com/digest-protected')
->authenticateWithDigest('username', 'p@ssw0rd')
->send();
// NTLM Auth
$response = Request::get('https://intranet.corp/api/data')
->authenticateWithNTLM('DOMAIN\user', 'p@ssw0rd')
->send();
echo $response->hasErrors() ? 'Auth failed' : 'Authenticated!';
```
### Response
#### Success Response
- **hasErrors()** (boolean) - Returns `false` if authentication was successful, `true` otherwise.
#### Response Example
```
Authenticated!
```
```
--------------------------------
### Request::post() — HTTP POST request
Source: https://context7.com/nategood/httpful/llms.txt
Creates a POST request. Accepts an optional payload and MIME type. Structured payloads (arrays/objects) are automatically serialized according to the Content-Type.
```APIDOC
## Request::post()
### Description
Creates a POST request to a specified URI. It can send a payload, which is automatically serialized based on the `Content-Type` header. Supports sending JSON or form-encoded data.
### Method
POST
### Endpoint
`/` (relative to the base URI)
### Parameters
#### Path Parameters
None.
#### Query Parameters
None explicitly mentioned for the factory method itself.
#### Request Body
- **payload** (mixed) - The data to send in the request body. Can be an array or object for JSON serialization, or a string.
- **mime_type** (string, optional) - The MIME type of the payload, defaults to `application/json` if a structured payload is provided.
### Request Example
```php
sendsJson()
->body(['name' => 'Alice', 'role' => 'admin'])
->send();
echo $response->body->json->name;
// POST URL-encoded form
$response = Request::post('https://httpbin.org/post', ['field' => 'value'], Mime::FORM)
->send();
echo $response->code;
```
### Response
#### Success Response (200)
- **body** (object) - The parsed response body.
- **code** (integer) - The HTTP status code.
#### Response Example
```json
{
"json": {
"name": "Alice",
"role": "admin"
},
"code": 200
}
```
```
--------------------------------
### Send Request Body with MIME Types
Source: https://context7.com/nategood/httpful/llms.txt
Set the request body and control Content-Type and Accept headers using `sends()`, `expects()`, or shorthand methods like `sendsJson()`.
```php
sendsJson()
->expectsJson()
->body(['title' => 'New Item', 'qty' => 5])
->send();
// Send XML
$xmlPayload = '- Widget10
';
$response = Request::post('https://api.example.com/items')
->sends(Mime::XML)
->expects(Mime::JSON)
->body($xmlPayload)
->send();
// Send URL-encoded form data
$response = Request::post('https://api.example.com/login')
->sendsForm()
->body(['username' => 'alice', 'password' => 'secret'])
->send();
?>
```
--------------------------------
### Custom Headers
Source: https://context7.com/nategood/httpful/llms.txt
Add custom headers to requests using `addHeader()`, `addHeaders()`, or convenient magic `with*` methods that automatically format header names.
```APIDOC
## Custom Headers
Add one or multiple headers via `addHeader()`, `addHeaders()`, or the magic `with*` / camelCase methods that convert method names into `Header-Name` format.
```php
addHeader('X-Api-Key', 'abc123')
->addHeaders([
'X-Client-Version' => '2.0',
'Accept-Language' => 'en-US',
])
->withXCorrelationId('req-987') // sets "X-Correlation-Id: req-987"
->send();
```
```
--------------------------------
### File Uploads with `attach()`
Source: https://context7.com/nategood/httpful/llms.txt
Attach one or more files to a multipart/form-data POST request. Httpful automatically detects the MIME types of the attached files.
```APIDOC
## File Uploads — `attach()`
Attach one or more files to a multipart/form-data POST request. MIME types are detected automatically.
```php
attach([
'avatar' => '/path/to/photo.jpg',
'document' => '/path/to/report.pdf',
])
->send();
echo $response->code; // 200 or 201
```
```
--------------------------------
### Attach Files to Multipart Request
Source: https://context7.com/nategood/httpful/llms.txt
Attach one or more files to a multipart/form-data POST request using the `attach()` method. MIME types are detected automatically.
```php
attach([
'avatar' => '/path/to/photo.jpg',
'document' => '/path/to/report.pdf',
])
->send();
echo $response->code; // 200 or 201
?>
```
--------------------------------
### Register Custom MIME Handlers
Source: https://context7.com/nategood/httpful/llms.txt
Register custom or overriding MIME handlers by extending MimeHandlerAdapter. Useful for replacing built-in parsers or adding support for new content types.
```php
'http://api.example.com/ns',
'libxml_opts' => LIBXML_NOCDATA,
]));
// Register a completely custom handler for YAML
class YamlHandler extends MimeHandlerAdapter
{
public function parse($body)
{
return yaml_parse($body); // requires PECL yaml
}
public function serialize($payload): string
{
return yaml_emit($payload);
}
}
Httpful::register('application/x-yaml', new YamlHandler());
// Now requests expecting YAML will use YamlHandler automatically
$response = \Httpful\Request::get('https://api.example.com/config.yaml')
->expects('yaml')
->send();
```
--------------------------------
### Add Additional cURL Options
Source: https://context7.com/nategood/httpful/llms.txt
Pass raw cURL options directly for settings not exposed by the Httpful API, such as binding to a specific network interface or enabling gzip encoding.
```php
addOnCurlOption(CURLOPT_INTERFACE, 'eth0') // bind to specific network interface
->addOnCurlOption(CURLOPT_ENCODING, 'gzip') // accept gzip encoding
->addOnCurlOption(CURLOPT_LOW_SPEED_LIMIT, 1024) // abort if speed drops below 1KB/s
->addOnCurlOption(CURLOPT_LOW_SPEED_TIME, 30)
->send();
```
--------------------------------
### `Response` object — Inspecting responses
Source: https://context7.com/nategood/httpful/llms.txt
The `Response` object provides access to the parsed body, raw body, status code, headers, charset, and metadata from an HTTP exchange.
```APIDOC
## `Response` object — Inspecting responses
### Description
The `Response` object exposes the parsed body, raw body, status code, headers, charset, and metadata from the HTTP exchange.
### Properties
- **code** (int): The HTTP status code.
- **body** (mixed): The parsed response body (e.g., stdClass for JSON).
- **raw_body** (string): The raw, unparsed response body.
- **headers** (Response\Headers): An object for accessing response headers.
- **content_type** (string): The content type of the response.
- **charset** (string): The character set of the response.
### Methods
- **hasErrors()**: Returns `true` if the status code indicates an error (4xx or 5xx).
- **hasBody()**: Returns `true` if the response has a body.
### Example
```php
expectsJson()
->send();
// Status
echo $response->code; // 200
var_dump($response->hasErrors()); // bool(false) — true for 4xx/5xx
var_dump($response->hasBody()); // bool(true)
// Parsed body (stdClass for JSON)
echo $response->body->login; // "nategood"
echo $response->body->public_repos;
// Raw body string
echo $response->raw_body;
// Headers (case-insensitive access)
echo $response->headers['Content-Type']; // "application/json; charset=utf-8"
echo $response->raw_headers; // raw HTTP header string
// Content-type metadata
echo $response->content_type; // "application/json"
echo $response->charset; // "utf-8"
// Cast to string returns raw body
echo (string) $response;
```
```
--------------------------------
### Custom MIME Handlers — `Httpful::register()`
Source: https://context7.com/nategood/httpful/llms.txt
Register a custom or overriding MIME handler by extending `MimeHandlerAdapter`. This is useful for replacing built-in parsers or adding support for new content types.
```APIDOC
## Custom MIME Handlers — `Httpful::register()`
### Description
Register a custom or overriding MIME handler by extending `MimeHandlerAdapter`. Useful to replace built-in parsers or add support for new content types.
### Method
```php
Httpful::register(string $mimeType, MimeHandlerAdapter $handler)
```
### Example
```php
'http://api.example.com/ns',
'libxml_opts' => LIBXML_NOCDATA,
]));
// Register a completely custom handler for YAML
class YamlHandler extends MimeHandlerAdapter
{
public function parse($body)
{
return yaml_parse($body); // requires PECL yaml
}
public function serialize($payload): string
{
return yaml_emit($payload);
}
}
Httpful::register('application/x-yaml', new YamlHandler());
// Now requests expecting YAML will use YamlHandler automatically
$response = \Httpful\Request::get('https://api.example.com/config.yaml')
->expects('yaml')
->send();
```
```
--------------------------------
### Pre-send Request Mutation with `beforeSend()`
Source: https://context7.com/nategood/httpful/llms.txt
Use the `beforeSend()` callback to execute a closure after payload serialization but before the cURL request is dispatched. This allows for last-minute modifications to the request, such as dynamically adding headers.
```php
sendsJson()
->body(['name' => 'Widget'])
->beforeSend(function (Request $request) {
// Dynamically add a timestamp header
$request->addHeader('X-Request-Time', microtime(true));
})
->send();
```
--------------------------------
### Access Response Headers
Source: https://context7.com/nategood/httpful/llms.txt
Response headers are wrapped in a Headers object offering case-insensitive array-like access and conversion to a plain array.
```php
send();
$headers = $response->headers;
// Case-insensitive access
echo $headers['content-type']; // "application/json"
echo $headers['Content-Type']; // "application/json" — same result
echo $headers['X-Rate-Limit']; // "100"
// Convert to plain array
$arr = $headers->toArray();
print_r($arr);
```
--------------------------------
### Custom Response Parsing with `parseWith()`
Source: https://context7.com/nategood/httpful/llms.txt
Provide a custom closure to `parseWith()` to handle response body parsing. This allows for complex transformations or indexing of data beyond Httpful's built-in MIME-based handlers.
```php
parseWith(function (string $body) {
$data = json_decode($body, true);
// Transform: index by 'id' field
return array_column($data['items'], null, 'id');
})
->send();
var_dump($response->body); // associative array keyed by item IDs
```
--------------------------------
### Control Payload Serialization with `serializePayload()` modes
Source: https://context7.com/nategood/httpful/llms.txt
Manage how request payloads are serialized using three modes: `SERIALIZE_PAYLOAD_SMART` (default, serializes objects/arrays, passes scalars), `SERIALIZE_PAYLOAD_ALWAYS` (always serializes), and `SERIALIZE_PAYLOAD_NEVER` (sends raw payload).
```php
sendsJson()
->smartSerializePayload()
->body('{"already":"serialized"}') // passed through as-is
->send();
// Always serialize (forces even scalar strings through json_encode)
$response = Request::post('https://api.example.com/raw')
->sendsJson()
->alwaysSerializePayload()
->body('plain string') // becomes "\"plain string\""
->send();
// Never serialize (send raw payload regardless of type)
$response = Request::post('https://api.example.com/raw')
->neverSerializePayload()
->body('raw=payload&foo=bar')
->send();
```
--------------------------------
### Custom Error Handling with `whenError()` and `ConnectionErrorException`
Source: https://context7.com/nategood/httpful/llms.txt
Register a custom error handler using `whenError()` for non-network errors. Catch `ConnectionErrorException` to specifically handle network-level failures like timeouts or DNS resolution issues.
```php
whenError(function (string $error) {
// Custom error handler (e.g., send to Sentry, log to file)
file_put_contents('/var/log/httpful.log', date('c') . " ERROR: $error\n", FILE_APPEND);
})
->send();
// Catching network-level errors
try {
$response = Request::get('https://unreachable.example.com/api')
->timeoutIn(3)
->send();
} catch (ConnectionErrorException $e) {
echo $e->getMessage(); // "Unable to connect to ..."
echo $e->getCurlErrorNumber(); // e.g. 6 (CURLE_COULDNT_RESOLVE_HOST)
echo $e->getCurlErrorString(); // "Could not resolve host: ..."
}
```
--------------------------------
### Client-Side Certificate Authentication
Source: https://context7.com/nategood/httpful/llms.txt
Authenticate requests using a client-side SSL certificate and key pair. This method supports an optional passphrase and encoding type.
```APIDOC
## Client-Side Certificate Authentication
Authenticate using a client-side SSL certificate and key pair, with an optional passphrase.
```php
authenticateWithCert(
'/path/to/client.crt', // certificate file
'/path/to/client.key', // key file
'keypassphrase', // optional passphrase
'PEM' // encoding (default: PEM)
)
->send();
echo $response->code; // 200
```
```
--------------------------------
### Inspect Response Object
Source: https://context7.com/nategood/httpful/llms.txt
The Response object provides access to the parsed body, raw body, status code, headers, charset, and metadata from the HTTP exchange.
```php
expectsJson()
->send();
// Status
echo $response->code; // 200
var_dump($response->hasErrors()); // bool(false) — true for 4xx/5xx
var_dump($response->hasBody()); // bool(true)
// Parsed body (stdClass for JSON)
echo $response->body->login; // "nategood"
echo $response->body->public_repos;
// Raw body string
echo $response->raw_body;
// Headers (case-insensitive access)
echo $response->headers['Content-Type']; // "application/json; charset=utf-8"
echo $response->raw_headers; // raw HTTP header string
// Content-type metadata
echo $response->content_type; // "application/json"
echo $response->charset; // "utf-8"
// Cast to string returns raw body
echo (string) $response;
```
--------------------------------
### SSL Verification
Source: https://context7.com/nategood/httpful/llms.txt
Manage SSL peer verification for requests. By default, strict SSL verification is enabled. It can be explicitly disabled for development or testing environments.
```APIDOC
## SSL Verification
SSL peer verification is enabled by default in Httpful 1.0.0+. It can be explicitly disabled for development environments.
```php
withStrictSSL()
->send();
// Disable SSL verification (dev/test only)
$response = Request::get('https://self-signed.example.com/api')
->withoutStrictSSL()
->send();
```
```
--------------------------------
### Add Custom Headers to Request
Source: https://context7.com/nategood/httpful/llms.txt
Add one or multiple custom headers to your HTTP request. Httpful provides methods like `addHeader()`, `addHeaders()`, and magic `with*` methods.
```php
addHeader('X-Api-Key', 'abc123')
->addHeaders([
'X-Client-Version' => '2.0',
'Accept-Language' => 'en-US',
])
->withXCorrelationId('req-987') // sets "X-Correlation-Id: req-987"
->send();
?>
```
--------------------------------
### Register a Custom Handler in PHP
Source: https://github.com/nategood/httpful/blob/master/src/Httpful/Handlers/README.md
Register the custom handler for a specific MIME type using Httpful::register(). This ensures that responses with this MIME type are processed by the custom handler.
```php
Httpful::register('text/csv', new SimpleCsvHandler());
```
--------------------------------
### Register Custom Payload Serializer
Source: https://context7.com/nategood/httpful/llms.txt
Register a custom serializer for a specific MIME type or use a wildcard for all types. This overrides built-in handlers.
```php
sendsJson()
->registerPayloadSerializer('application/json', function ($payload) {
// Use custom JSON encoding options
return json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
})
->body(['message' => 'héllo wörld'])
->send();
// Or apply to ALL mime types with a wildcard
Request::post('https://api.example.com/data')
->serializePayloadWith(function ($payload) {
return serialize($payload); // PHP native serialization
})
->body(['key' => 'value'])
->send();
```
--------------------------------
### Perform HTTP POST Request with JSON Body
Source: https://context7.com/nategood/httpful/llms.txt
Send a POST request with a JSON payload. Structured payloads are automatically serialized. For URL-encoded forms, provide the data and Mime::FORM.
```php
sendsJson()
->body(['name' => 'Alice', 'role' => 'admin'])
->send();
echo $response->body->json->name; // "Alice"
// POST URL-encoded form
$response = Request::post('https://httpbin.org/post', ['field' => 'value'], Mime::FORM)
->send();
echo $response->code; // 200
```
--------------------------------
### `Response\Headers` — Header access
Source: https://context7.com/nategood/httpful/llms.txt
Response headers are wrapped in a `Headers` object that provides case-insensitive array-like access and can be converted to a plain array.
```APIDOC
## `Response\Headers` — Header access
### Description
Response headers are wrapped in a `Headers` object that provides case-insensitive array-like access and can be converted to a plain array.
### Methods
- **toArray()**: Converts the headers object into a plain PHP array.
### Example
```php
send();
$headers = $response->headers;
// Case-insensitive access
echo $headers['content-type']; // "application/json"
echo $headers['Content-Type']; // "application/json" — same result
echo $headers['X-Rate-Limit']; // "100"
// Convert to plain array
$arr = $headers->toArray();
print_r($arr);
```
```
--------------------------------
### Disable Auto-Parsing with `withoutAutoParsing()`
Source: https://context7.com/nategood/httpful/llms.txt
By default, Httpful automatically parses response bodies based on the Content-Type header. Use `withoutAutoParsing()` to receive the raw body as a string instead of a parsed object or array.
```php
expectsJson()
->send();
var_dump($response->body); // object(stdClass)
echo $response->body->login; // "nategood"
// Auto-parse OFF — body is a raw string
$response = Request::get('https://api.github.com/users/nategood')
->withoutAutoParsing()
->send();
echo gettype($response->body); // "string"
echo $response->raw_body; // raw JSON string
```
--------------------------------
### Custom Payload Serializer — `registerPayloadSerializer()`
Source: https://context7.com/nategood/httpful/llms.txt
Register a custom serializer closure for a specific MIME type (or '*' for all types), overriding the built-in handler. This allows you to control how request bodies are encoded.
```APIDOC
## Custom Payload Serializer — `registerPayloadSerializer()`
### Description
Register a custom serializer closure for a specific MIME type (or `'*'` for all types), overriding the built-in handler.
### Method
```php
Request::post(string $uri)
->sendsJson()
->registerPayloadSerializer(string $mimeType, callable $serializer)
->body(mixed $payload)
->send();
```
### Example
```php
sendsJson()
->registerPayloadSerializer('application/json', function ($payload) {
// Use custom JSON encoding options
return json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
})
->body(['message' => 'héllo wörld'])
->send();
// Or apply to ALL mime types with a wildcard
Request::post('https://api.example.com/data')
->serializePayloadWith(function ($payload) {
return serialize($payload); // PHP native serialization
})
->body(['key' => 'value'])
->send();
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.