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

Php Http Client Laravel Package

sendgrid/php-http-client

Lightweight PHP HTTP client for quickly accessing RESTful (or REST-like) APIs. Simple request building and response handling, ideal for integrating services like SendGrid or any JSON API. Requires PHP 7.3+ and installs via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sendgrid/php-http-client
    

    Ensure your composer.json includes "sendgrid/php-http-client": "^4.1.3" (or latest).

  2. First Use Case: Initialize the client with a base URL and headers (e.g., API key for authentication):

    use SendGrid\Client;
    
    $client = new Client('https://api.example.com', [
        'Authorization' => 'Bearer YOUR_API_KEY',
        'Content-Type'  => 'application/json'
    ]);
    
  3. First Request: Fetch data from /users endpoint:

    $response = $client->get('/users');
    $users = json_decode($response->body(), true);
    

Where to Look First

  • README.md: Quick-start examples and installation.
  • USAGE.md: Detailed usage patterns (e.g., query params, headers, concurrency).
  • Client.php: Core class for method chaining (e.g., $client->your()->api()->_($param)).

Implementation Patterns

1. Method Chaining for API Paths

Leverage fluent interfaces to build complex API paths dynamically:

$response = $client
    ->v1()          // Versioned path (e.g., /v1/)
    ->users()       // Resource (e.g., /users)
    ->_('123')      // ID (e.g., /users/123)
    ->call()        // Prepare request
    ->get();        // Execute GET

2. Request Customization

  • Headers/Query Params:

    $response = $client->post('/data', [
        'name' => 'John'
    ], [
        'X-Custom-Header' => 'value'
    ], [
        'page' => 1
    ]);
    

    Parameters: post(path, body, headers, queryParams)

  • Concurrent Requests (v3.9.0+):

    $requests = [
        $client->get('/users'),
        $client->get('/posts')
    ];
    $responses = $client->send($requests);
    

3. Response Handling

  • Status Code Check:
    if ($response->statusCode() === 200) {
        $data = json_decode($response->body(), true);
    }
    
  • Error Handling:
    try {
        $response = $client->get('/invalid');
    } catch (\SendGrid\Exception\InvalidRequest $e) {
        log($e->getMessage()); // CURL error details
    }
    

4. Integration with Laravel

  • Service Provider: Bind the client to Laravel’s container in AppServiceProvider:
    public function register()
    {
        $this->app->singleton(Client::class, function () {
            return new Client(config('services.api.base_url'), [
                'Authorization' => 'Bearer ' . config('services.api.key')
            ]);
        });
    }
    
  • Facade (Optional): Create a facade (ApiClient) to simplify usage:
    // app/Facades/ApiClient.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class ApiClient extends Facade { protected static function getFacadeAccessor() { return 'api.client'; } }
    
    Register in config/app.php:
    'api.client' => \SendGrid\Client::class,
    

5. Testing

  • Mocking Responses: Use Laravel’s HTTP tests or PHPUnit to mock the client:
    $mock = Mockery::mock(Client::class);
    $mock->shouldReceive('get')
         ->with('/users')
         ->andReturn(new \SendGrid\Response(200, [], '{"users": []}'));
    

Gotchas and Tips

Pitfalls

  1. Header Overrides:

    • Custom headers passed to methods (e.g., post()) overwrite default headers set in the constructor.
    • Fix: Use array_merge to preserve existing headers:
      $headers = array_merge($client->getDefaultHeaders(), ['X-Custom' => 'value']);
      $response = $client->post('/data', [], $headers);
      
  2. CURL Options:

    • Default CURL options (e.g., CURLOPT_FAILONERROR) may cause silent failures.
    • Fix: Explicitly set options in the constructor:
      $client = new Client('https://api.example.com', [], [
          CURLOPT_SSL_VERIFYPEER => false // Only for testing!
      ]);
      
  3. Concurrency Limits:

    • send() for concurrent requests may hit system limits (e.g., open files).
    • Fix: Limit concurrent requests:
      $client->setConcurrencyLimit(5); // Default: 10
      
  4. SSL/TLS Issues:

    • If the server uses a self-signed certificate, CURL may fail.
    • Fix: Disable verification (temporarily):
      $client->setOption(CURLOPT_SSL_VERIFYPEER, false);
      

Debugging Tips

  1. Enable Verbose CURL Output:

    $client->setOption(CURLOPT_VERBOSE, true);
    // Log CURL output to a file:
    $client->setOption(CURLOPT_STDERR, fopen('curl.log', 'w'));
    
  2. Inspect Raw Response:

    var_dump($response->raw()); // Full CURL response
    
  3. Rate Limiting:

    • The library auto-retries on rate limits (v3.8.0+), but log the retry count:
      $client->setRetryCallback(function ($retries) {
          logger("Retry #$retries due to rate limit");
      });
      

Extension Points

  1. Custom Request/Response Classes: Extend SendGrid\Client to add middleware:

    class CustomClient extends \SendGrid\Client {
        public function __construct($baseUrl, array $headers = []) {
            parent::__construct($baseUrl, $headers);
            $this->addMiddleware(function ($request) {
                $request->headers['X-Middleware'] = 'enabled';
            });
        }
    }
    
  2. Plugin System: Use traits or decorators to add functionality (e.g., request signing):

    trait AuthPlugin {
        public function signRequest($request) {
            $request->headers['Authorization'] = $this->generateToken();
        }
    }
    
  3. Event Listeners: Hook into request/response lifecycle:

    $client->on('beforeSend', function ($request) {
        if ($request->path === '/admin') {
            abort(403);
        }
    });
    

Configuration Quirks

  • Environment Variables: Load headers from .env:

    $headers = [
        'Authorization' => 'Bearer ' . env('API_KEY'),
        'User-Agent'    => env('API_USER_AGENT', 'Laravel/1.0')
    ];
    $client = new Client(env('API_BASE_URL'), $headers);
    
  • Default Timeout: Set globally in the constructor:

    $client = new Client('https://api.example.com', [], [
        CURLOPT_TIMEOUT => 30 // 30 seconds
    ]);
    

Performance Tips

  1. Reuse Connections: The client reuses CURL handles by default. For high-throughput apps, disable this:

    $client->setOption(CURLOPT_FRESH_CONNECT, true);
    
  2. Compress Responses: Enable gzip/deflate:

    $client->setOption(CURLOPT_ENCODING, 'gzip');
    
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.
terminal42/code-quality-tools
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