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

codememory/api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require codememory/api-bundle
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Codememory\ApiBundle\ApiServiceProvider" --tag="config"
    
  2. Basic Usage Register the bundle in config/app.php under providers:

    Codememory\ApiBundle\ApiServiceProvider::class,
    
  3. First API Call Use the facade to make a request:

    use Codememory\ApiBundle\Facades\Api;
    
    $response = Api::get('https://api.example.com/data');
    $data = $response->json();
    
  4. Key Config Check config/api.php for default settings (timeout, headers, etc.).


Implementation Patterns

Common Workflows

  1. Structured API Clients Create dedicated service classes for API interactions:

    namespace App\Services;
    
    use Codememory\ApiBundle\Facades\Api;
    
    class UserService {
        public function fetchUsers() {
            return Api::get('/users')->json();
        }
    }
    
  2. Request/Response Handling Use the Api facade for raw requests or chain methods:

    $response = Api::withHeaders(['Authorization' => 'Bearer token'])
                   ->post('/users', ['name' => 'John'])
                   ->json();
    
  3. Error Handling Centralize API error responses in a middleware or service:

    try {
        $data = Api::get('/data')->json();
    } catch (\Codememory\ApiBundle\Exceptions\ApiException $e) {
        Log::error('API Error: ' . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    
  4. Rate Limiting Configure retry logic in config/api.php:

    'retry' => [
        'max_attempts' => 3,
        'delay' => 1000, // milliseconds
    ],
    
  5. Testing Mock the facade in PHPUnit:

    $this->mock(Api::class)->shouldReceive('get')
        ->once()
        ->andReturn(new \Codememory\ApiBundle\Response('{"status": "success"}'));
    

Gotchas and Tips

Pitfalls

  1. No Built-in Caching The bundle doesn’t cache responses by default. Implement caching manually (e.g., Cache::remember):

    $data = Cache::remember('api_users', now()->addHours(1), function () {
        return Api::get('/users')->json();
    });
    
  2. Limited Middleware Support Custom middleware must extend Codememory\ApiBundle\Http\Middleware\ApiMiddleware or be applied via the facade:

    Api::withMiddleware(new CustomMiddleware())->get('/endpoint');
    
  3. No Automatic JSON Parsing Always call ->json() or ->text() explicitly to decode responses.

  4. Config Overrides Ensure config/api.php is published before customizing settings.

Debugging Tips

  • Enable Debug Mode Set 'debug' => true in config/api.php to log raw requests/responses.

  • Check Exceptions Catch Codememory\ApiBundle\Exceptions\ApiException for HTTP errors (4xx/5xx).

  • Verify Headers Use ->withHeaders() to ensure headers (e.g., Accept: application/json) are set.

Extension Points

  1. Custom Responses Extend the Response class to add domain-specific methods:

    class CustomResponse extends \Codememory\ApiBundle\Response {
        public function getUserId() {
            return $this->json()['id'];
        }
    }
    
  2. Add Request Transformers Create a transformer class to format requests:

    Api::withTransformer(new UserTransformer())->post('/users', $userData);
    
  3. Event Listeners Listen for api.request and api.response events to log or modify payloads:

    Event::listen('api.request', function ($request) {
        Log::debug('API Request:', $request->toArray());
    });
    
  4. Service Provider Hooks Override the default Api instance in the service provider:

    $this->app->singleton('api', function ($app) {
        return new CustomApiClient($app['config']['api']);
    });
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle