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

Api Bundle Laravel Package

bsll/api-bundle

Laravel bundle for building and organizing JSON API endpoints, with helpers for routing, request/response handling, and common API concerns. A lightweight starting point for integrating an API layer into an existing app or new project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require bsll/api-bundle
    

    Publish the bundle’s configuration (if available):

    php artisan vendor:publish --provider="Bsll\ApiBundle\ApiServiceProvider"
    
  2. Service Provider Ensure the ApiServiceProvider is registered in config/app.php under providers:

    Bsll\ApiBundle\ApiServiceProvider::class,
    
  3. First Use Case: Basic API Request Inject the API client into a controller or service:

    use Bsll\ApiBundle\Contracts\ApiClientInterface;
    
    class ExampleController extends Controller
    {
        public function __construct(private ApiClientInterface $apiClient) {}
    
        public function fetchData()
        {
            $response = $this->apiClient->get('endpoint');
            return response()->json($response);
        }
    }
    
  4. Configuration Check config/api.php (if published) for default settings like base URI, headers, or authentication.


Implementation Patterns

Common Workflows

1. Authenticated Requests

Pass credentials via the client or config:

$this->apiClient->withAuth('token')->get('protected-endpoint');

Or configure globally in config/api.php:

'auth' => [
    'token' => env('API_TOKEN'),
    'type' => 'bearer',
],

2. Request/Response Transformation

Use middleware or decorators to modify requests/responses:

$this->apiClient->withMiddleware(new CustomRequestTransformer())->post('data', $payload);

3. Rate Limiting & Retries

Configure retry logic in the client:

$this->apiClient->withRetry(3, 500)->get('unstable-endpoint');

4. Event-Driven Extensions

Listen for API events (if supported) to log or transform data:

event(new \Bsll\ApiBundle\Events\ApiRequestEvent($request));

5. Testing

Mock the ApiClientInterface in tests:

$mock = Mockery::mock(ApiClientInterface::class);
$mock->shouldReceive('get')->andReturn(['data' => 'test']);

$this->app->instance(ApiClientInterface::class, $mock);

Integration Tips

  • Laravel HTTP Client Bridge If the bundle supports it, integrate with Laravel’s built-in HTTP client for consistency:

    $this->apiClient->useHttpClient(app(\Illuminate\Http\Client\PendingRequest::class));
    
  • API Versioning Use route middleware to switch API versions dynamically:

    Route::middleware(['api-version:v2'])->group(function () {
        // Routes using v2 of the API
    });
    
  • Caching Responses Cache API responses with Laravel’s cache system:

    $response = Cache::remember('api_data', now()->addHours(1), function () {
        return $this->apiClient->get('data');
    });
    

Gotchas and Tips

Pitfalls

  1. No Official Documentation

    • The package lacks formal docs. Inspect src/ for undocumented features or behaviors.
    • Check description.md or README.md for hidden gems (e.g., default config keys).
  2. Dependency Conflicts

    • The bundle may rely on older Laravel versions or packages. Test thoroughly with your stack.
    • Example: If using Laravel 10+, ensure the bundle’s service providers are compatible.
  3. Global State Risks

    • Avoid storing sensitive data (e.g., tokens) in static/config without encryption.
    • Prefer dependency injection over static calls to ApiClient::getInstance().
  4. Error Handling

    • The bundle may not throw exceptions for HTTP errors (e.g., 4xx/5xx). Handle responses explicitly:
      try {
          $response = $this->apiClient->get('endpoint');
      } catch (\Bsll\ApiBundle\Exceptions\ApiException $e) {
          Log::error($e->getMessage());
      }
      
  5. Network Timeouts

    • Default timeouts may be too short for slow APIs. Configure in the client:
      $this->apiClient->withTimeout(30)->get('slow-endpoint');
      

Debugging Tips

  • Enable Guzzle Debugging If the bundle uses Guzzle, enable debug mode:

    $this->apiClient->withDebug(true); // Check if supported
    

    Or use Laravel’s logging:

    \Log::debug('API Request', ['request' => $request->toArray()]);
    
  • Inspect Raw Responses Dump responses to debug unexpected data:

    dd($this->apiClient->get('endpoint')->getBody());
    
  • Check for Middleware Conflicts Disable middleware temporarily to isolate issues:

    $this->apiClient->withoutMiddleware(CustomMiddleware::class);
    

Extension Points

  1. Custom Clients Extend the base client for domain-specific logic:

    class CustomApiClient extends \Bsll\ApiBundle\ApiClient
    {
        public function customMethod()
        {
            return $this->post('custom', ['key' => 'value']);
        }
    }
    
  2. Add New HTTP Methods If the bundle lacks a method (e.g., PATCH), extend the client:

    class ExtendedApiClient extends ApiClient
    {
        public function patch($uri, array $data = [])
        {
            return $this->request('PATCH', $uri, ['body' => $data]);
        }
    }
    
  3. Plugin System If the bundle supports plugins, create one to add functionality:

    class LoggingPlugin implements \Bsll\ApiBundle\Contracts\ApiPlugin
    {
        public function handle($request)
        {
            Log::info('API Call', ['uri' => $request->getUri()]);
            return $request;
        }
    }
    
  4. Service Provider Overrides Bind custom implementations in your AppServiceProvider:

    $this->app->bind(
        \Bsll\ApiBundle\Contracts\ApiClientInterface::class,
        \App\Services\CustomApiClient::class
    );
    

Configuration Quirks

  • Default Config Location The bundle may not publish config by default. Manually create config/api.php:

    return [
        'base_uri' => env('API_BASE_URI', 'https://api.example.com'),
        'timeout' => 10,
    ];
    
  • Environment Variables Prefix API-related env vars clearly (e.g., API_*):

    API_BASE_URI=https://api.example.com
    API_TOKEN=your_token_here
    
  • Fallback Behavior Test edge cases like:

    • Missing config keys.
    • Empty responses.
    • Rate-limited requests.
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
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