friendship ended with social-app. php is my new best friend
1---
2title: fetch()
3description: API reference for the fetch() helper function
4---
5
6# fetch()
7
8The `fetch()` function is the primary way to make HTTP requests. It's designed to mimic JavaScript's `fetch()` API while providing PHP-specific enhancements.
9
10## Signature
11
12```php
13function fetch(
14 string|RequestInterface|null $resource = null,
15 ?array $options = []
16): ResponseInterface|ClientHandlerInterface|Client
17```
18
19## Parameters
20
21### `$resource`
22
23- Type: `string|RequestInterface|null`
24- Default: `null`
25
26This parameter can be:
27
28- A URL string to fetch, e.g., `'https://api.example.com/users'`
29- A pre-configured `Request` object
30- `null` to return the client for method chaining
31
32### `$options`
33
34- Type: `array|null`
35- Default: `[]`
36
37An associative array of request options:
38
39| Option | Type | Description |
40| ------ | ---- | ----------- |
41| `method` | `string\|Method` | HTTP method (GET, POST, etc.) |
42| `headers` | `array` | Request headers |
43| `body` | `mixed` | Request body (raw) |
44| `json` | `array` | JSON data to send as body (takes precedence over body) |
45| `form` | `array` | Form data to send as body (takes precedence if no json) |
46| `multipart` | `array` | Multipart form data (takes precedence if no json/form) |
47| `query` | `array` | Query parameters |
48| `base_uri` | `string` | Base URI for the request |
49| `timeout` | `int` | Request timeout in seconds |
50| `retries` | `int` | Number of retries |
51| `retry_delay` | `int` | Initial delay between retries in milliseconds |
52| `auth` | `array` | Basic auth credentials [username, password] |
53| `token` | `string` | Bearer token |
54| `proxy` | `string\|array` | Proxy configuration |
55| `cookies` | `bool\|CookieJarInterface` | Cookies configuration |
56| `allow_redirects` | `bool\|array` | Redirect handling configuration |
57| `cert` | `string\|array` | SSL certificate |
58| `ssl_key` | `string\|array` | SSL key |
59| `stream` | `bool` | Whether to stream the response |
60
61## Return Value
62
63The return value depends on the `$resource` parameter:
64
65- If `$resource` is `null`: Returns the client instance (`ClientHandlerInterface` or `Client`) for method chaining
66- If `$resource` is a URL string: Returns a `ResponseInterface` object
67- If `$resource` is a `Request` object: Returns a `ResponseInterface` object
68
69## Throws
70
71- `ClientExceptionInterface` - If a client exception occurs during the request
72
73## Examples
74
75### Basic GET Request
76
77```php
78use function Fetch\Http\fetch;
79
80// Make a simple GET request
81$response = fetch('https://api.example.com/users');
82
83// Check if the request was successful
84if ($response->successful()) {
85 // Parse the JSON response
86 $users = $response->json();
87
88 foreach ($users as $user) {
89 echo $user['name'] . "\n";
90 }
91} else {
92 echo "Error: " . $response->status() . " " . $response->statusText();
93}
94```
95
96### POST Request with JSON Data
97
98```php
99// Send JSON data
100$response = fetch('https://api.example.com/users', [
101 'method' => 'POST',
102 'json' => [
103 'name' => 'John Doe',
104 'email' => 'john@example.com'
105 ]
106]);
107
108// Or use the 'body' option with array (auto-converted to JSON)
109$response = fetch('https://api.example.com/users', [
110 'method' => 'POST',
111 'body' => ['name' => 'John Doe', 'email' => 'john@example.com']
112]);
113```
114
115### Setting Headers
116
117```php
118$response = fetch('https://api.example.com/users', [
119 'headers' => [
120 'Accept' => 'application/json',
121 'X-API-Key' => 'your-api-key',
122 'User-Agent' => 'MyApp/1.0'
123 ]
124]);
125```
126
127### Using Query Parameters
128
129```php
130// Add query parameters
131$response = fetch('https://api.example.com/users', [
132 'query' => [
133 'page' => 1,
134 'per_page' => 20,
135 'sort' => 'created_at',
136 'order' => 'desc'
137 ]
138]);
139```
140
141### Form Submission
142
143```php
144// Send form data
145$response = fetch('https://api.example.com/login', [
146 'method' => 'POST',
147 'form' => [
148 'username' => 'johndoe',
149 'password' => 'secret',
150 'remember' => true
151 ]
152]);
153```
154
155### File Upload
156
157```php
158// Upload a file using multipart form data
159$response = fetch('https://api.example.com/upload', [
160 'method' => 'POST',
161 'multipart' => [
162 [
163 'name' => 'file',
164 'contents' => file_get_contents('/path/to/file.jpg'),
165 'filename' => 'upload.jpg',
166 'headers' => ['Content-Type' => 'image/jpeg']
167 ],
168 [
169 'name' => 'description',
170 'contents' => 'Profile picture'
171 ]
172 ]
173]);
174```
175
176### Authentication
177
178```php
179// Bearer token authentication
180$response = fetch('https://api.example.com/profile', [
181 'token' => 'your-oauth-token'
182]);
183
184// Basic authentication
185$response = fetch('https://api.example.com/protected', [
186 'auth' => ['username', 'password']
187]);
188```
189
190### Timeouts and Retries
191
192```php
193// Set timeout and retry options
194$response = fetch('https://api.example.com/slow-resource', [
195 'timeout' => 30, // 30 second timeout
196 'retries' => 3, // Retry up to 3 times
197 'retry_delay' => 100 // Start with 100ms delay (uses exponential backoff)
198]);
199```
200
201### Method Chaining
202
203```php
204// Return the client for method chaining
205$users = fetch()
206 ->withToken('your-oauth-token')
207 ->withHeader('Accept', 'application/json')
208 ->get('https://api.example.com/users')
209 ->json();
210```
211
212### Using a Request Object
213
214```php
215use Fetch\Http\Request;
216
217// Create a custom request
218$request = Request::post('https://api.example.com/users')
219 ->withJsonBody(['name' => 'John Doe', 'email' => 'john@example.com'])
220 ->withHeader('X-API-Key', 'your-api-key');
221
222// Send the request
223$response = fetch($request);
224```
225
226## Internal Implementation
227
228The `fetch()` function works by:
229
2301. Processing the provided options with `process_request_options()`
2312. Handling base URI configuration if provided with `handle_request_with_base_uri()`
2323. Using the global client instance from `fetch_client()` to execute the request
2334. Returning appropriate responses based on the input parameters
234
235## Notes
236
237- The `fetch()` function is not a direct implementation of the Web Fetch API; it's inspired by it but adapted for PHP
238- When passing an array as the request body, it's automatically encoded as JSON
239- For more complex request scenarios, use method chaining with `fetch()` or the `ClientHandler` class
240- The function automatically handles conversion between different data formats based on content type
241- When used without arguments, `fetch()` returns the global client instance for method chaining
242
243## See Also
244
245- [fetch_client()](/api/fetch-client) - Get or configure the global client instance
246- [HTTP Method Helpers](/api/http-method-helpers) - Specialized helper functions for different HTTP methods
247- [ClientHandler](/api/client-handler) - More details on the underlying client implementation
248- [Response](/api/response) - API for working with response objects