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 Bundle Laravel Package

chaplean/rest-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require chaplean/rest-client-bundle
    

    Ensure EightPointsGuzzleBundle is registered in AppKernel.php (dependency).

  2. Basic Configuration: Define a client in config.yml:

    eight_points_guzzle:
        clients:
            my_api:
                base_url: 'https://api.example.com'
                timeout: 30
    
  3. First Use Case: Inject the client service and make a request:

    use Chaplean\Bundle\RestClientBundle\Client\ClientInterface;
    
    class MyService
    {
        public function __construct(ClientInterface $client)
        {
            $this->client = $client;
        }
    
        public function fetchData()
        {
            return $this->client->get('my_api', '/endpoint');
        }
    }
    

Where to Look First

  • Documentation: Focus on the EightPointsGuzzleBundle for Guzzle configuration.
  • Client Interface: Chaplean\Bundle\RestClientBundle\Client\ClientInterface defines the core methods (get, post, put, delete, etc.).
  • Logging: If enabled, logs are stored in the database (Doctrine) or via Swiftmailer.

Implementation Patterns

Usage Patterns

  1. Service Integration: Bind the client to a service and reuse it for API interactions:

    // src/MyBundle/Service/MyApiService.php
    class MyApiService
    {
        public function __construct(private ClientInterface $client) {}
    
        public function createResource(array $data): array
        {
            return $this->client->post('my_api', '/resources', [
                'json' => $data,
            ]);
        }
    }
    
  2. Request Customization: Use Guzzle options directly:

    $this->client->get('my_api', '/endpoint', [
        'query' => ['filter' => 'active'],
        'headers' => ['Authorization' => 'Bearer token'],
    ]);
    
  3. Response Handling: Parse responses with Symfony’s JsonResponse or custom logic:

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

Workflows

  1. API Abstraction Layer: Create a dedicated service per API to encapsulate endpoints and logic:

    // src/MyBundle/Service/StripeService.php
    class StripeService
    {
        public function __construct(private ClientInterface $client) {}
    
        public function chargeCustomer(string $customerId, float $amount): array
        {
            return $this->client->post('stripe_api', '/charges', [
                'json' => ['amount' => $amount, 'customer' => $customerId],
            ]);
        }
    }
    
  2. Error Handling: Use Guzzle’s exception handling or wrap calls in try-catch:

    try {
        $this->client->get('my_api', '/sensitive-data');
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        // Log or rethrow with custom message
        throw new \RuntimeException('API request failed', 0, $e);
    }
    
  3. Configuration Management: Dynamically switch environments (e.g., dev vs. prod) via parameters.yml:

    # config_dev.yml
    eight_points_guzzle:
        clients:
            my_api:
                base_url: 'https://dev-api.example.com'
    

Integration Tips

  • Dependency Injection: Prefer constructor injection for testability. Use @autowire in services:

    services:
        App\Service\MyApiService:
            arguments:
                $client: '@chaplean_rest_client.client'
    
  • Middleware: Leverage Guzzle middleware (e.g., retry, logging) via EightPointsGuzzleBundle:

    eight_points_guzzle:
        clients:
            my_api:
                middleware:
                    - EightPoints\GuzzleBundle\Middleware\RetryMiddleware
    
  • Testing: Mock the ClientInterface in PHPUnit:

    $mockClient = $this->createMock(ClientInterface::class);
    $mockClient->method('get')->willReturn(new \GuzzleHttp\Psr7\Response(200, [], '{}'));
    
    $service = new MyApiService($mockClient);
    

Gotchas and Tips

Pitfalls

  1. Missing Dependencies:

    • Forgetting to register EightPointsGuzzleBundle will cause ClientInterface to fail.
    • Fix: Ensure the bundle is listed in AppKernel.php before ChapleanRestClientBundle.
  2. Logging Overhead:

    • Database logging (Doctrine) or email logging (Swiftmailer) can slow down requests.
    • Fix: Disable logging in config.yml if unused:
      eight_points_guzzle:
          logging: false
      
  3. Base URL Mismatches:

    • Incorrect base_url in config.yml leads to 404s or redirects.
    • Fix: Validate URLs with tools like curl or Postman before debugging.
  4. Response Parsing:

    • Responses may not always be JSON. Use getBody() directly if needed:
      $body = $this->client->get('my_api', '/plaintext')->getBody();
      

Debugging

  1. Enable Guzzle Debugging: Add a middleware to log requests/responses:

    eight_points_guzzle:
        clients:
            my_api:
                middleware:
                    - EightPoints\GuzzleBundle\Middleware\DebugMiddleware
    
  2. Check Headers: Missing or malformed headers (e.g., Content-Type: application/json) cause parsing errors.

    • Debug: Inspect raw responses with:
      var_dump($response->getHeaders());
      
  3. Timeouts: Default timeouts may be too short for slow APIs.

    • Fix: Adjust in config.yml:
      eight_points_guzzle:
          clients:
              my_api:
                  timeout: 60
      

Tips

  1. Reuse Clients: Define multiple clients in config.yml for different APIs:

    eight_points_guzzle:
        clients:
            stripe: { base_url: 'https://api.stripe.com' }
            paypal: { base_url: 'https://api.paypal.com' }
    
  2. Environment-Specific Configs: Use %kernel.environment% to switch configs:

    # config_%env%.yml
    eight_points_guzzle:
        clients:
            my_api:
                base_url: '%api_base_url%'
    
  3. Extend Functionality: Create custom clients by implementing ClientInterface:

    class CustomClient implements ClientInterface
    {
        public function get(string $clientName, string $endpoint, array $options = []): ResponseInterface
        {
            // Add pre-processing logic (e.g., auth tokens)
            return $this->guzzleClient->get($endpoint, $options);
        }
    }
    
  4. Rate Limiting: Use Guzzle’s delay option to avoid hitting API limits:

    $this->client->get('my_api', '/rate-limited', [
        'delay' => 1000, // 1-second delay
    ]);
    
  5. Security:

    • Never hardcode credentials in config.yml. Use Symfony’s parameter_bag:
      parameters:
          api_token: '%env(API_TOKEN)%'
      
    • Sanitize inputs before passing to API endpoints to avoid injection.
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver