Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Http Client Laravel Package

symfony/http-client

Symfony HttpClient provides a modern HTTP client for PHP with sync and async requests, streaming responses, retries, and built-in support for common auth and options. Designed for performance, flexible transports, and smooth integration with Symfony apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/http-client
    

    For Laravel, use symfony/http-client as a dependency in composer.json.

  2. Basic Request:

    use Symfony\Contracts\HttpClient\HttpClientInterface;
    use Symfony\HttpClient\HttpClient;
    
    $client = HttpClient::create();
    $response = $client->request('GET', 'https://api.example.com/data');
    $content = $response->getContent();
    
  3. First Use Case: Fetch JSON data from an external API:

    $response = $client->request('GET', 'https://api.example.com/users');
    $users = $response->toArray(); // Automatically decodes JSON
    

Key Entry Points

  • HttpClient::create(): Default client with cURL transport.
  • HttpClientInterface: Contract for dependency injection.
  • request(): Core method for all HTTP requests (GET, POST, etc.).

Implementation Patterns

Common Workflows

1. Dependency Injection

Register the client in Laravel's service container (config/app.php):

'providers' => [
    // ...
    Symfony\Contracts\HttpClient\HttpClientInterface::class => function ($app) {
        return Symfony\HttpClient\HttpClient::create();
    },
],

Inject via constructor:

public function __construct(private HttpClientInterface $client) {}

2. Request Customization

  • Headers/Body:
    $response = $client->request('POST', '/api/data', [
        'headers' => ['Authorization' => 'Bearer token'],
        'body' => json_encode(['key' => 'value']),
    ]);
    
  • Query Parameters:
    $response = $client->request('GET', '/api/data', [
        'query' => ['page' => 1, 'limit' => 10],
    ]);
    

3. Async Requests

$promise = $client->request('GET', 'https://api.example.com/data');
$content = $promise->then(function ($response) {
    return $response->getContent();
});

4. Decorators for Reusability

  • Caching:
    use Symfony\Contracts\Cache\CacheInterface;
    use Symfony\Component\HttpClient\Cache\CacheClient;
    
    $cache = new CacheClient($client, $cachePool);
    
  • Retry Logic:
    use Symfony\Component\HttpClient\Retry\RetryClient;
    
    $retryClient = new RetryClient($client, [
        'max_retries' => 3,
        'delay' => 100,
    ]);
    

5. Streaming Responses

$response = $client->request('GET', 'https://large-file.example.com/data');
$stream = $response->getContent(false); // Stream instead of buffering

6. Authentication

  • Basic Auth:
    $response = $client->request('GET', 'https://api.example.com/protected', [
        'auth_basic' => ['user', 'pass'],
    ]);
    
  • Bearer Tokens:
    $response = $client->request('GET', 'https://api.example.com/protected', [
        'headers' => ['Authorization' => 'Bearer token123'],
    ]);
    

7. Error Handling

try {
    $response = $client->request('GET', 'https://api.example.com/data');
    $response->toArray();
} catch (\Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface $e) {
    // Handle 4xx errors
} catch (\Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface $e) {
    // Handle 5xx errors
} catch (\Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface $e) {
    // Handle network errors
}

Laravel-Specific Patterns

1. Service Container Integration

Bind the client with custom configurations:

$this->app->singleton(HttpClientInterface::class, function ($app) {
    return HttpClient::create([
        'base_uri' => 'https://api.example.com/v1/',
        'timeout' => 30,
        'headers' => [
            'Accept' => 'application/json',
            'User-Agent' => 'Laravel-App/1.0',
        ],
    ]);
});

2. Middleware for Requests

Use Laravel's middleware to modify requests:

$client = HttpClient::create();
$client->withOptions([
    'on_headers' => function (ResponseInterface $response, array $options) {
        // Modify headers or add logging
    },
]);

3. Queueable HTTP Jobs

Dispatch long-running requests to queues:

use Symfony\Component\HttpClient\Exception\TransportExceptionInterface;

class FetchDataJob implements ShouldQueue
{
    public function handle(HttpClientInterface $client) {
        try {
            $response = $client->request('GET', 'https://slow-api.example.com/data');
            // Process response
        } catch (TransportExceptionInterface $e) {
            $this->release(60); // Retry after 60 seconds
        }
    }
}

4. API Resource Wrappers

Create a service class to abstract API calls:

class UserApiService
{
    public function __construct(private HttpClientInterface $client) {}

    public function getUser(int $id): array {
        $response = $this->client->request('GET', '/users/' . $id);
        return $response->toArray();
    }
}

Gotchas and Tips

Pitfalls

1. Resource Leaks

  • Issue: Forgetting to close streams or handles can cause memory leaks.
  • Fix: Use finally blocks or Laravel's try-catch-finally to ensure cleanup:
    $response = $client->request('GET', 'https://example.com/stream');
    $stream = $response->getContent(false);
    try {
        // Process stream
    } finally {
        $stream->close();
    }
    

2. Connection Pooling

  • Issue: Default CurlHttpClient reuses connections, which can cause issues with stateful APIs (e.g., OAuth tokens).
  • Fix: Reset the client between requests if needed:
    $client->request('GET', 'https://api.example.com/token');
    $client->reset(); // Clear connection state
    

3. Timeout Misconfigurations

  • Issue: Default timeout (30s) may be too short for slow APIs.
  • Fix: Configure timeouts per request or globally:
    $client = HttpClient::create(['timeout' => 60]);
    // Or per request
    $client->request('GET', 'https://slow-api.example.com', ['timeout' => 120]);
    

4. Async Response Handling

  • Issue: Forgetting to await promises can lead to unhandled exceptions.
  • Fix: Use then() or await in async contexts:
    $promise = $client->request('GET', 'https://api.example.com');
    $promise->then(function ($response) {
        // Handle response
    })->wait(); // Block until completion (if needed)
    

5. Caching Pitfalls

  • Issue: CachingHttpClient may serve stale data if not configured properly.
  • Fix: Set appropriate max_age and stale_while_revalidate:
    $cacheClient = new CacheClient($client, $cachePool, [
        'max_age' => 3600, // 1 hour
        'stale_while_revalidate' => 60, // 1 minute
    ]);
    

6. Proxy Configurations

  • Issue: Proxies may break HTTP/3 or require custom DNS resolution.
  • Fix: Configure proxy explicitly:
    $client = HttpClient::create([
        'proxy' => 'tcp://proxy.example.com:8080',
    ]);
    

7. SSL/TLS Issues

  • Issue: Self-signed certificates or strict TLS versions can fail.
  • Fix: Disable verification (not recommended for production) or configure CA bundle:
    $client = HttpClient::create([
        'verify_peer' => false, // Disable verification (insecure!)
        'cafile' => '/path/to/certificate.pem',
    ]);
    

Debugging Tips

1. Enable Verbose Logging

$client = HttpClient::create([
    'debug' => true,
    'on_headers' => function (ResponseInterface $response, array $options) {
        error_log($
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle