Weave 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

Api Services Bundle Laravel Package

cobhimself/api-services-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

This package, API Services Bundle, is designed to simplify interactions with external APIs in Laravel applications. To begin:

  1. Installation: Requires Composer installation via:

    composer require cobhimself/api-services-bundle
    

    Publish the configuration file (if needed) with:

    php artisan vendor:publish --provider="Cobhimself\ApiServicesBundle\ApiServicesServiceProvider"
    
  2. First Use Case: Define an API service in config/api-services.php:

    'services' => [
        'example' => [
            'base_url' => 'https://api.example.com',
            'timeout' => 30,
            'headers' => [
                'Accept' => 'application/json',
            ],
        ],
    ],
    

    Then inject the service into a controller or service class:

    use Cobhimself\ApiServicesBundle\Services\ApiService;
    
    public function __construct(ApiService $apiService)
    {
        $this->apiService = $apiService;
    }
    

    Make requests using the fluent API:

    $response = $this->apiService->for('example')->get('/endpoint');
    

Implementation Patterns

Core Workflows

  1. Service Configuration:

    • Define API services in the config file with base_url, timeout, headers, and optional auth (e.g., API keys or OAuth tokens).
    • Use environment variables for sensitive data (e.g., API_KEY) and reference them in the config:
      'auth' => [
          'token' => env('API_KEY'),
      ],
      
  2. Request Handling:

    • Use the fluent API for requests:
      $this->apiService->for('example')
          ->withHeaders(['X-Custom-Header' => 'value'])
          ->get('/data', ['param' => 'value'])
          ->json();
      
    • Chain methods like post(), put(), delete(), and patch() for different HTTP verbs.
  3. Response Processing:

    • Access raw responses with ->raw(), JSON with ->json(), or throw exceptions on failure:
      try {
          $data = $this->apiService->for('example')->get('/data')->json();
      } catch (\Cobhimself\ApiServicesBundle\Exceptions\ApiException $e) {
          // Handle error
      }
      
  4. Middleware Integration:

    • Attach middleware to specific services or globally:
      'middleware' => [
          'example' => [
              \Cobhimself\ApiServicesBundle\Middleware\LogRequests::class,
          ],
      ],
      

Advanced Patterns

  • Dynamic Service Resolution: Resolve services dynamically at runtime:
    $service = $this->apiService->for('dynamic-service-name');
    
  • Retry Logic: Implement retry logic for transient failures by wrapping requests in a loop or using Laravel’s retry helper.

Gotchas and Tips

Common Pitfalls

  1. Configuration Overrides:

    • Ensure config values in config/api-services.php are not overridden by cached configs. Clear the config cache after changes:
      php artisan config:clear
      
  2. Authentication Handling:

    • If using OAuth or tokens, ensure they are refreshed before expiration. Consider implementing a beforeRequest middleware for this.
  3. Rate Limiting:

    • The package does not enforce rate limits by default. Monitor API responses for 429 Too Many Requests and implement delays or retries.
  4. Exception Handling:

    • The package throws ApiException for HTTP errors (4xx/5xx). Customize error handling in your middleware or controllers.

Debugging Tips

  • Logging: Enable request/response logging via middleware:

    'middleware' => [
        'global' => [
            \Cobhimself\ApiServicesBundle\Middleware\LogRequests::class,
        ],
    ],
    

    Logs will appear in Laravel’s default log channel.

  • Testing: Mock the ApiService in tests:

    $mock = Mockery::mock(\Cobhimself\ApiServicesBundle\Services\ApiService::class);
    $mock->shouldReceive('for')->andReturnSelf();
    $mock->shouldReceive('get')->andReturn((object) ['json' => fn() => ['test' => 'data']]);
    

Extension Points

  1. Custom Request Transformers:

    • Extend the ApiService to add request/response transformers:
      $this->apiService->for('example')->transformRequest(function ($data) {
          return array_merge($data, ['custom_field' => 'value']);
      });
      
  2. Event Listeners:

    • Listen for api.request and api.response events to intercept requests/responses globally.
  3. Service Providers:

    • Bind custom API services to the container:
      $this->app->bind('custom.api', function ($app) {
          return new CustomApiService($app['api-service']);
      });
      
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.
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk