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

Httpclient Laravel Package

digital-link/httpclient

Lightweight Laravel/PHP HTTP client wrapper for making outbound requests with a clean, simple API. Provides convenient helpers for common methods, headers, and payloads to speed up calling external APIs in your applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require digital-link/httpclient
    

    Add the package to your config/app.php under providers:

    DigitalLink\HttpClient\HttpClientServiceProvider::class,
    
  2. First Use Case: Basic HTTP Request

    use DigitalLink\HttpClient\HttpClient;
    
    $client = app(HttpClient::class);
    $response = $client->get('https://api.example.com/users');
    $data = json_decode($response->getBody(), true);
    
  3. Where to Look First

    • Documentation: Check the Fig Standards HTTP Client Proposal for interface expectations.
    • Service Provider: Review HttpClientServiceProvider for default configurations or bindings.
    • Facade: If available, use HttpClient::get() or HttpClient::post() for convenience.

Implementation Patterns

Core Workflows

  1. Request/Response Handling

    // GET request with query params
    $response = $client->get('https://api.example.com/users', [
        'query' => ['active' => true]
    ]);
    
    // POST request with JSON body
    $response = $client->post('https://api.example.com/users', [
        'json' => ['name' => 'John Doe']
    ]);
    
  2. Middleware Integration Add custom middleware to the client:

    $client = app(HttpClient::class);
    $client->pushMiddleware(function ($request, callable $next) {
        $request->withHeader('X-Custom-Header', 'value');
        return $next($request);
    });
    
  3. Retry Logic Implement retry middleware for transient failures:

    $client->pushMiddleware(function ($request, callable $next) use ($client) {
        $attempts = 0;
        while ($attempts < 3) {
            try {
                return $next($request);
            } catch (Exception $e) {
                $attempts++;
                if ($attempts === 3) throw $e;
                usleep(1000); // 1ms delay
            }
        }
    });
    
  4. Dependency Injection Bind the client in service containers or use constructor injection:

    class UserService {
        public function __construct(private HttpClient $client) {}
    }
    
  5. Async Requests (if supported)

    $promise = $client->getAsync('https://api.example.com/users');
    $response = $promise->wait();
    

Gotchas and Tips

Common Pitfalls

  1. Interface Compliance

    • The package adheres to the Fig HTTP Client Proposal. Ensure your code matches expected methods like:
      • get(), post(), put(), delete(), patch()
      • withHeader(), withQuery(), withBody()
      • getStatusCode(), getBody(), getHeaders()
  2. Response Handling

    • Body Consumption: HTTP responses are streams. Consume the body once to avoid rewind issues:
      $body = $response->getBody()->getContents(); // Consume fully
      
    • Status Codes: Check getStatusCode() before accessing the body (e.g., 404 may return empty).
  3. Middleware Order

    • Middleware runs in LIFO (Last-In-First-Out) order. Push middleware early if it should run first:
      $client->pushMiddleware($authMiddleware); // Runs last
      $client->pushMiddleware($loggingMiddleware, 'highest'); // Runs first
      
  4. Timeouts

    • Default timeouts may not be set. Configure globally or per-request:
      $client->withTimeout(10); // 10 seconds
      // OR per-request
      $response = $client->get('...', ['timeout' => 5]);
      
  5. SSL/TLS Issues

    • If using self-signed certificates, disable verification temporarily (not for production):
      $client->withOptions(['verify' => false]);
      

Debugging Tips

  1. Log Requests/Responses Add a middleware to log payloads:

    $client->pushMiddleware(function ($request, callable $next) {
        \Log::debug('Request:', [
            'url' => (string) $request->getUri(),
            'method' => $request->getMethod(),
            'headers' => $request->getHeaders(),
            'body' => $request->getBody() ? $request->getBody()->getContents() : null,
        ]);
        $response = $next($request);
        \Log::debug('Response:', [
            'status' => $response->getStatusCode(),
            'body' => $response->getBody()->getContents(),
        ]);
        return $response;
    });
    
  2. Validate Responses Use Laravel’s response()->json() helper to validate JSON responses:

    $data = $response->getBody();
    $json = json_decode($data, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \RuntimeException('Invalid JSON response');
    }
    
  3. Test Locally Mock the HTTP client in tests using Laravel’s MockHttpClient or a custom mock:

    $mock = Mockery::mock(HttpClient::class);
    $mock->shouldReceive('get')
        ->once()
        ->andReturn(new Response(200, [], '{"key": "value"}'));
    $this->app->instance(HttpClient::class, $mock);
    

Extension Points

  1. Custom Adapters Implement the DigitalLink\HttpClient\Adapter\AdapterInterface to support non-Guzzle/non-cURL backends (e.g., Symfony HTTP Client):

    class SymfonyAdapter implements AdapterInterface {
        public function sendRequest(RequestInterface $request): ResponseInterface {
            // Convert request to Symfony format and send
        }
    }
    
  2. Plugin System Extend functionality via plugins (e.g., rate limiting, caching):

    $client->usePlugin(new RateLimitPlugin($client, 100)); // 100 requests/minute
    
  3. Event Dispatching Listen for request/response events (if the package supports it):

    event(new HttpClientRequestEvent($request));
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor