friendship ended with social-app. php is my new best friend
1---
2title: API Reference for Fetch PHP
3description: API reference for the Fetch HTTP client package
4---
5
6# API Reference
7
8Welcome to the API reference for the Fetch HTTP client package. This section provides detailed documentation for all the components, functions, classes, and interfaces available in the package.
9
10## Core Components
11
12The Fetch package is built around several key components:
13
14### Functions
15
16- [`fetch()`](./fetch.md) - The primary function for making HTTP requests
17- [`fetch_client()`](./fetch-client.md) - Function to create a configured HTTP client
18- [HTTP Method Helpers](./http-method-helpers.md) - Helper functions like `get()`, `post()`, etc.
19
20### Classes
21
22- [`Client`](./client.md) - Main HTTP client class
23- [`ClientHandler`](./client-handler.md) - Low-level HTTP client implementation
24- [`Response`](./response.md) - HTTP response representation
25
26### Enums
27
28- [`Method`](./method-enum.md) - HTTP request methods (GET, POST, PUT, etc.)
29- [`ContentType`](./content-type-enum.md) - Content type (MIME type) constants
30- [`Status`](./status-enum.md) - HTTP status codes
31
32## Architectural Overview
33
34The Fetch package is designed with a layered architecture:
35
361. **User-facing API**: The `fetch()`, `fetch_client()`, and HTTP method helpers (`get()`, `post()`, etc.) provide a simple, expressive API for common HTTP operations.
37
382. **Client Layer**: The `Client` class provides a higher-level, feature-rich API with method chaining and fluent interface.
39
403. **Handler Layer**: The `ClientHandler` class provides the core HTTP functionality, handling the low-level details of making HTTP requests.
41
424. **HTTP Message Layer**: The `Response` class represents HTTP responses and provides methods for working with them.
43
445. **Utilities and Constants**: Enums (`Method`, `ContentType`, `Status`) and other utilities provide standardized constants and helper functions.
45
46## Usage Patterns
47
48The API is designed to be used in several ways, depending on your needs:
49
50### One-line Requests
51
52```php
53// Quick GET request
54$response = fetch('https://api.example.com/users');
55
56// Quick POST request with JSON data
57$response = fetch('https://api.example.com/users', [
58 'method' => 'POST',
59 'json' => [
60 'name' => 'John Doe',
61 'email' => 'john@example.com'
62 ]
63]);
64
65// Using HTTP method helpers
66$response = get('https://api.example.com/users');
67$response = post('https://api.example.com/users', [
68 'name' => 'John Doe',
69 'email' => 'john@example.com'
70]);
71```
72
73### Fluent Interface with Client
74
75```php
76// Create a client with a base URI
77$client = fetch_client([
78 'base_uri' => 'https://api.example.com'
79]);
80
81// Chain method calls for a more complex request
82$response = $client
83 ->getHandler()
84 ->withHeader('X-API-Key', 'your-api-key')
85 ->withQueryParameter('page', 1)
86 ->timeout(5)
87 ->get('/users');
88```
89
90### Asynchronous Requests
91
92```php
93// Make an asynchronous request
94$promise = fetch_client()
95 ->getHandler()
96 ->async()
97 ->get('https://api.example.com/users');
98
99// Add callbacks
100$promise->then(
101 function ($response) {
102 // Handle successful response
103 $users = $response->json();
104 foreach ($users as $user) {
105 echo $user['name'] . "\n";
106 }
107 },
108 function ($exception) {
109 // Handle error
110 echo "Error: " . $exception->getMessage();
111 }
112);
113```
114
115### Request Batching and Concurrency
116
117```php
118use function Fetch\async;
119use function Fetch\await;
120use function Fetch\all;
121use function Fetch\map;
122
123// Execute multiple requests in parallel
124$results = await(all([
125 'users' => async(fn() => fetch('https://api.example.com/users')),
126 'posts' => async(fn() => fetch('https://api.example.com/posts')),
127 'comments' => async(fn() => fetch('https://api.example.com/comments'))
128]));
129
130// Process multiple items with controlled concurrency
131$userIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
132$results = await(map($userIds, function($id) {
133 return async(function() use ($id) {
134 return fetch("https://api.example.com/users/{$id}");
135 });
136}, 3)); // Process 3 at a time
137```
138
139### Working with Enums
140
141```php
142use Fetch\Enum\Method;
143use Fetch\Enum\ContentType;
144use Fetch\Enum\Status;
145
146// Make a request with enum values
147$response = fetch_client()
148 ->getHandler()
149 ->withBody($data, ContentType::JSON)
150 ->sendRequest(Method::POST, 'https://api.example.com/users');
151
152// Check response status using enums
153if ($response->getStatus() === Status::CREATED) {
154 echo "User created successfully";
155} elseif ($response->getStatus()->isClientError()) {
156 echo "Client error: " . $response->getStatus()->phrase();
157}
158```
159
160## Extending the Package
161
162The package is designed to be extensible. You can:
163
164- Create custom client handlers
165- Extend the base client with additional functionality
166- Add middleware for request/response processing
167- Create specialized clients for specific APIs
168
169See the [Custom Clients](../guide/custom-clients.md) guide for more information on extending the package.
170
171## Performance Considerations
172
173- Use the global client instance via `fetch_client()` for best performance, as it reuses connections
174- Consider using asynchronous requests for I/O-bound operations
175- Use the `map()` function with controlled concurrency for processing multiple items
176- For large responses, consider streaming the response with the `stream` option
177
178## Compatibility Notes
179
180- Requires PHP 8.1 or higher
181- Built on top of Guzzle HTTP, a widely-used PHP HTTP client
182- Follows PSR-7 (HTTP Message Interface) and PSR-18 (HTTP Client) standards
183- Supports both synchronous and asynchronous operations