Laravel HTTP Guzzle

6 months ago

In Laravel, Guzzle is a popular HTTP client that allows you to make HTTP requests to external servers. It is often used for tasks such as consuming APIs, sending HTTP requests, and handling responses. Guzzle is included by default in Laravel, so you don't need to install it separately.

Here's a basic overview of how you can use Guzzle in a Laravel application:

  1. Make a GET Request:

    use Illuminate\Support\Facades\Http;
    
    $response = Http::get('https://api.example.com/posts');
    
    // Get the response body as an array
    $data = $response->json();
    
    // Or get the raw response body
    $rawData = $response->body();
    
  2. Make a POST Request:

    use Illuminate\Support\Facades\Http;
    
    $response = Http::post('https://api.example.com/posts', [
        'title' => 'New Post',
        'content' => 'This is the content of the post.',
    ]);
    
    // Process the response as needed
    
  3. Handling Responses:

    // Get the HTTP status code
    $statusCode = $response->status();
    
    // Check if the request was successful (status code 2xx)
    $isSuccessful = $response->successful();
    
    // Get the response headers
    $headers = $response->headers();
    
    // Get a specific header
    $contentType = $response->header('content-type');
    
  4. Error Handling:

    // Check if the request was unsuccessful (status code 4xx or 5xx)
    if ($response->failed()) {
        // Handle the error
    }
    
    // Get the response body as an array even if the request was unsuccessful
    $data = $response->json();
    
  5. Timeouts and Retries:

    // Set a timeout in seconds
    $response = Http::timeout(5)->get('https://api.example.com/posts');
    
    // Retry the request a specified number of times
    $response = Http::retry(3, 100)->get('https://api.example.com/posts');
    
  6. Sending JSON Requests:

    $response = Http::post('https://api.example.com/posts', [
        'json' => [
            'title' => 'New Post',
            'content' => 'This is the content of the post.',
        ],
    ]);
    
  7. Authentication:

    // Basic Authentication
    $response = Http::withBasicAuth('username', 'password')->get('https://api.example.com/posts');
    
    // Bearer Token Authentication
    $response = Http::withToken('your-token')->get('https://api.example.com/posts');
    

Remember to handle exceptions appropriately, especially when dealing with external services. Guzzle may throw exceptions for network errors, timeouts, etc. You can use try-catch blocks to handle these exceptions and provide meaningful error messages to your application users.

This is just a basic introduction to using Guzzle in Laravel. The official Guzzle documentation (https://docs.guzzlephp.org/) provides more in-depth information and examples for advanced usage.

Jese Leos avatar
mahatma (2) minutes ro read