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

donkeycode/rest-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require donkeycode/rest-bundle
    

    Add to config/app.php under providers:

    Donkeycode\RestBundle\RestServiceProvider::class,
    

    Publish the config file:

    php artisan vendor:publish --provider="Donkeycode\RestBundle\RestServiceProvider" --tag=config
    
  2. Basic Usage Define a REST client in config/rest.php:

    'clients' => [
        'api' => [
            'base_uri' => 'https://api.example.com',
            'timeout'  => 30,
        ],
    ],
    

    Inject the client into a service:

    use Donkeycode\RestBundle\Client;
    
    class MyService {
        protected $client;
    
        public function __construct(Client $client) {
            $this->client = $client;
        }
    
        public function fetchData() {
            return $this->client->get('api', '/endpoint');
        }
    }
    
  3. First Use Case Fetch and decode JSON from an external API:

    $response = $this->client->get('api', '/users', [
        'query' => ['limit' => 10]
    ]);
    $users = json_decode($response->getBody(), true);
    

Implementation Patterns

Dependency Injection

  • Service Binding: Bind the Client interface to a specific implementation in AppServiceProvider:

    $this->app->bind('Donkeycode\RestBundle\Client', function ($app) {
        return new Donkeycode\RestBundle\Client($app['config']['rest.clients.api']);
    });
    
  • Named Clients: Use named clients (e.g., api, stripe) for multi-service apps:

    $this->client->get('stripe', '/customers');
    

Request Customization

  • Headers & Auth:

    $this->client->post('api', '/login', [], [
        'headers' => ['Authorization' => 'Bearer token123'],
    ]);
    
  • Middleware: Attach middleware for logging, retries, or auth:

    $this->client->withMiddleware(new \Donkeycode\RestBundle\Middleware\LoggingMiddleware())
                 ->get('api', '/data');
    

Response Handling

  • Streaming: Process large responses without loading into memory:

    $response = $this->client->get('api', '/large-file');
    $stream = $response->getBody();
    while (!$stream->eof()) {
        echo $stream->read(1024);
    }
    
  • Error Handling:

    try {
        $response = $this->client->get('api', '/unreachable');
    } catch (\Donkeycode\RestBundle\Exception\ClientException $e) {
        Log::error('API Error: ' . $e->getMessage());
    }
    

Integration with Laravel

  • Queue Jobs: Offload API calls to queues:

    dispatch(new FetchDataJob($client, 'api', '/data'));
    
  • Events: Trigger events on success/failure:

    $this->client->get('api', '/data')->then(function ($response) {
        event(new DataFetched($response));
    });
    

Gotchas and Tips

Configuration Quirks

  • Base URI Trailing Slash: Ensure base_uri in config does not end with / to avoid double slashes in requests.
  • Default Client: If no named client is provided, the bundle defaults to default. Define it explicitly:
    'clients' => [
        'default' => [...],
    ],
    

Debugging

  • Response Inspection: Use dd($response->getBody()->getContents()) to debug raw responses.
  • Timeouts: Increase timeout in config for slow APIs (default: 30 seconds).
  • SSL Issues: Disable SSL verification only for testing (not production):
    $this->client->withOptions(['verify' => false])->get('api', '/endpoint');
    

Extension Points

  • Custom Middleware: Extend Donkeycode\RestBundle\Middleware\AbstractMiddleware to add logic (e.g., rate limiting):

    class RateLimitMiddleware extends AbstractMiddleware {
        public function handle(RequestInterface $request, callable $next) {
            // Add rate limit logic
            return $next($request);
        }
    }
    
  • Response Transformers: Decouple API responses from your models:

    $this->client->get('api', '/users')->then(function ($response) {
        return User::hydrate(json_decode($response->getBody(), true));
    });
    

Performance Tips

  • Connection Pooling: Reuse the same client instance (Laravel’s DI handles this).
  • Caching: Cache responses for idempotent requests:
    Cache::remember('api_users', 3600, function () {
        return $this->client->get('api', '/users');
    });
    

Common Pitfalls

  • Case-Sensitive Headers: Ensure headers like Content-Type match the API’s expectations.

  • Query Parameters: URL-encode values manually if the bundle doesn’t handle it:

    $query = http_build_query(['q' => 'Laravel & REST']);
    $this->client->get('api', '/search', ['query' => $query]);
    
  • Async Calls: Avoid blocking the event loop in Laravel’s request lifecycle. Use queues or sync calls judiciously.

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky