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

Rest Client Laravel Package

brzuchal/rest-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require brzuchal/rest-client
    

    Register the service provider in config/app.php (if using Laravel):

    'providers' => [
        // ...
        Brzuchal\RestClient\RestClientServiceProvider::class,
    ],
    

    Publish config (optional):

    php artisan vendor:publish --provider="Brzuchal\RestClient\RestClientServiceProvider"
    
  2. First Request (Laravel): Use the facade for quick access:

    use Brzuchal\RestClient\Facades\RestClient;
    
    $response = RestClient::get('https://api.example.com/users');
    $data = $response->json();
    
  3. First Use Case: Fetch and deserialize a JSON API response into a Laravel Eloquent model:

    $user = RestClient::get('https://api.example.com/users/1')
        ->toEntity(User::class); // Assumes `User` implements `JsonSerializable`
    

Implementation Patterns

Core Workflow

  1. Fluent Request Building: Chain methods for clarity and reusability:

    $client = RestClient::create('https://api.example.com')
        ->withHeaders(['Authorization' => 'Bearer token'])
        ->withTimeout(30);
    $response = $client->get('/users')->withQuery(['active' => true]);
    
  2. Response Handling:

    • Raw Data: $response->getContent()
    • JSON: $response->json()
    • Entities: $response->toEntity(User::class)
    • Validation: $response->validate(function ($data) { ... })
  3. Laravel Integration:

    • Service Container Binding:
      $this->app->bind('api.client', function () {
          return RestClient::create(config('services.api.base_url'))
              ->withAuth(config('services.api.token'));
      });
      
    • Dependency Injection:
      public function __construct(private RestClient $client) {}
      
  4. Error Handling:

    • Global exceptions via RestClient::onError():
      RestClient::onError(function ($exception) {
          Log::error('API Error', ['exception' => $exception]);
          throw new \RuntimeException('API Unavailable');
      });
      
    • Per-request handling:
      try {
          $response = $client->get('/users')->throw();
      } catch (\Brzuchal\RestClient\Exception\ApiException $e) {
          // Handle 4xx/5xx responses
      }
      
  5. Testing:

    • Mock responses with RestClient::mock():
      RestClient::mock('https://api.example.com/users', [
          'id' => 1,
          'name' => 'Test User'
      ]);
      

Gotchas and Tips

Pitfalls

  1. Synchronous by Design:

    • Avoid blocking I/O in long-running tasks (e.g., CLI commands). Use queues for heavy API calls:
      dispatch(new FetchUsersFromApi($client));
      
  2. Entity Deserialization:

    • Ensure your entity classes implement JsonSerializable or use __construct(array $data):
      class User implements JsonSerializable {
          public function __construct(private array $data) {}
          public function jsonSerialize(): array { return $this->data; }
      }
      
  3. Symfony HttpClient Under the Hood:

    • Custom middleware (e.g., retry logic) requires extending Symfony\Contracts\HttpClient\HttpClientInterface. Use the exchange method for custom handling:
      $response = $client->get('/users')->exchange(function ($response) {
          return $response->getContent(); // Custom logic
      });
      
  4. Config Overrides:

    • Default config (published via vendor:publish) may conflict with Laravel’s config/services.php. Merge explicitly:
      config(['rest-client' => array_merge(
          config('rest-client'),
          ['timeout' => 60]
      )]);
      
  5. Rate Limiting:

    • No built-in rate limiting. Use middleware or a decorator:
      $client->withMiddleware(new RateLimitMiddleware());
      

Debugging Tips

  1. Enable Verbose Logging:

    $client->withOptions(['debug' => true]);
    

    Logs will include request/response bodies.

  2. Inspect Headers:

    $headers = $client->get('/users')->getHeaders();
    
  3. Test Locally: Use RestClient::mock() to avoid hitting external APIs during development.

Extension Points

  1. Custom Entity Mappers: Extend Brzuchal\RestClient\Mapper\EntityMapper for complex deserialization:

    class CustomMapper extends EntityMapper {
        protected function map(array $data, string $class): object {
            return new $class($data['custom_key']);
        }
    }
    
  2. Service Factory: For dynamic API clients (experimental):

    $factory = new \Brzuchal\RestClient\ServiceFactory();
    $client = $factory->create('stripe', [
        'base_uri' => 'https://api.stripe.com',
        'auth' => 'sk_test_...'
    ]);
    
  3. Event Listeners: Attach to rest-client.request and rest-client.response events (if using Laravel Events):

    event(new RestClientRequestEvent($request));
    
  4. Middleware Stack: Add custom middleware (Symfony-style):

    $client->withMiddleware(new class implements HttpClientInterface {
        public function __invoke(RequestStack $stack, $uri, array $options = []) {
            // Pre-process request
            $response = $stack->next($uri, $options);
            // Post-process response
            return $response;
        }
    });
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime