friendship ended with social-app. php is my new best friend
1--- 2title: Basic Examples 3description: Basic examples for using the Fetch HTTP package 4--- 5 6# Basic Examples 7 8This page provides basic examples of how to use the Fetch HTTP package to make common HTTP requests. 9 10## Basic GET Requests 11 12Making a simple GET request: 13 14```php 15// Make a GET request 16$response = fetch('https://api.example.com/users'); 17 18// Check if the request was successful 19if ($response->successful()) { 20 // Parse the JSON response 21 $users = $response->json(); 22 23 // Use the data 24 foreach ($users as $user) { 25 echo $user['name'] . "\n"; 26 } 27} else { 28 echo "Error: " . $response->status() . " " . $response->statusText(); 29} 30``` 31 32Using the `get()` helper function: 33 34```php 35// Make a GET request with query parameters 36$response = get('https://api.example.com/users', [ 37 'page' => 1, 38 'per_page' => 20, 39 'sort' => 'name' 40]); 41 42// Access data using array syntax 43if ($response->successful()) { 44 echo "Total users: " . $response['meta']['total'] . "\n"; 45 46 foreach ($response['data'] as $user) { 47 echo "- " . $user['name'] . "\n"; 48 } 49} 50``` 51 52## POST Requests 53 54Creating a resource: 55 56```php 57// Create a user with JSON data 58$response = post('https://api.example.com/users', [ 59 'name' => 'John Doe', 60 'email' => 'john@example.com', 61 'role' => 'admin' 62]); 63 64// Check for success and get the created resource 65if ($response->successful()) { 66 $user = $response->json(); 67 echo "Created user with ID: " . $user['id'] . "\n"; 68} elseif ($response->isUnprocessableEntity()) { 69 // Handle validation errors 70 $errors = $response->json()['errors']; 71 foreach ($errors as $field => $messages) { 72 echo "$field: " . implode(', ', $messages) . "\n"; 73 } 74} else { 75 echo "Error: " . $response->status(); 76} 77``` 78 79Submitting a form: 80 81```php 82// Send form data 83$response = fetch('https://api.example.com/contact', [ 84 'method' => 'POST', 85 'form' => [ 86 'name' => 'Jane Smith', 87 'email' => 'jane@example.com', 88 'message' => 'Hello, I have a question about your product.' 89 ] 90]); 91 92if ($response->successful()) { 93 echo "Form submitted successfully!"; 94} else { 95 echo "Failed to submit form: " . $response->status(); 96} 97``` 98 99## PUT and PATCH Requests 100 101Updating a resource completely (PUT): 102 103```php 104// Update a user with all fields 105$response = put('https://api.example.com/users/123', [ 106 'name' => 'John Smith', 107 'email' => 'john.smith@example.com', 108 'role' => 'editor' 109]); 110 111if ($response->successful()) { 112 echo "User updated successfully!"; 113} 114``` 115 116Updating a resource partially (PATCH): 117 118```php 119// Update only specific fields 120$response = patch('https://api.example.com/users/123', [ 121 'role' => 'admin' 122]); 123 124if ($response->successful()) { 125 echo "User role updated successfully!"; 126} 127``` 128 129## DELETE Requests 130 131Deleting a resource: 132 133```php 134// Delete a user 135$response = delete('https://api.example.com/users/123'); 136 137if ($response->successful()) { 138 echo "User deleted successfully!"; 139} elseif ($response->isNotFound()) { 140 echo "User not found!"; 141} else { 142 echo "Failed to delete user: " . $response->status(); 143} 144``` 145 146Bulk delete with a request body: 147 148```php 149// Delete multiple users 150$response = delete('https://api.example.com/users', [ 151 'ids' => [123, 456, 789] 152]); 153 154if ($response->successful()) { 155 $result = $response->json(); 156 echo "Deleted " . $result['deleted_count'] . " users"; 157} 158``` 159 160## Working with Headers 161 162Adding custom headers: 163 164```php 165// Send a request with custom headers 166$response = fetch('https://api.example.com/data', [ 167 'headers' => [ 168 'X-API-Version' => '2.0', 169 'Accept-Language' => 'en-US', 170 'Cache-Control' => 'no-cache', 171 'X-Request-ID' => uniqid() 172 ] 173]); 174 175// Get response headers 176$contentType = $response->header('Content-Type'); 177$rateLimitRemaining = $response->header('X-RateLimit-Remaining'); 178 179echo "Content Type: $contentType\n"; 180echo "Rate Limit Remaining: $rateLimitRemaining\n"; 181``` 182 183## Request Timeout 184 185Setting request timeout: 186 187```php 188// Set a 5-second timeout 189$response = fetch('https://api.example.com/slow-operation', [ 190 'timeout' => 5 191]); 192 193// Or with the fluent interface 194$response = fetch() 195 ->timeout(5) 196 ->get('https://api.example.com/slow-operation'); 197``` 198 199## Working with Different Response Types 200 201### JSON Responses 202 203```php 204$response = get('https://api.example.com/users/123'); 205 206// Get as associative array (default) 207$userData = $response->json(); 208echo $userData['name']; 209 210// Get as object 211$userObject = $response->object(); 212echo $userObject->name; 213 214// Using array access syntax directly on response 215$name = $response['name']; 216$email = $response['email']; 217``` 218 219### XML Responses 220 221```php 222$response = get('https://api.example.com/feed', null, [ 223 'headers' => ['Accept' => 'application/xml'] 224]); 225 226// Parse XML 227$xml = $response->xml(); 228 229// Work with SimpleXMLElement 230foreach ($xml->item as $item) { 231 echo (string)$item->title . "\n"; 232 echo (string)$item->description . "\n"; 233} 234``` 235 236### Raw Responses 237 238```php 239// Get raw response body (for non-JSON/XML content) 240$response = get('https://api.example.com/text-content'); 241$content = $response->body(); 242 243// Or using text() method 244$text = $response->text(); 245 246echo "Content length: " . strlen($content) . " bytes"; 247``` 248 249## Configuring Global Defaults 250 251Setting global configuration for all requests: 252 253```php 254// Configure once at application bootstrap 255fetch_client([ 256 'base_uri' => 'https://api.example.com', 257 'timeout' => 10, 258 'headers' => [ 259 'User-Agent' => 'MyApp/1.0', 260 'Accept' => 'application/json' 261 ] 262]); 263 264// Now use simplified calls in your code 265$users = get('/users')->json(); // Uses base_uri 266$user = post('/users', ['name' => 'John'])->json(); 267``` 268 269## Method Chaining 270 271Using the fluent interface: 272 273```php 274$response = fetch() 275 ->withHeader('X-API-Key', 'your-api-key') 276 ->withQueryParam('include', 'comments,likes') 277 ->withQueryParam('sort', 'created_at') 278 ->timeout(5) 279 ->get('https://api.example.com/posts'); 280 281if ($response->successful()) { 282 $posts = $response->json(); 283 // Process posts 284} 285``` 286 287## Next Steps 288 289Now that you're familiar with the basics, check out these more advanced examples: 290 291- [API Integration Examples](/examples/api-integration) - Real-world API integration patterns 292- [Async Patterns](/examples/async-patterns) - Working with asynchronous requests 293- [Error Handling](/examples/error-handling) - Robust error handling strategies 294- [File Handling](/examples/file-handling) - Uploading and downloading files 295- [Authentication](/examples/authentication) - Working with different authentication schemes