Installation
composer require codememory/api-bundle
Publish the config file (if needed):
php artisan vendor:publish --provider="Codememory\ApiBundle\ApiServiceProvider" --tag="config"
Basic Usage
Register the bundle in config/app.php under providers:
Codememory\ApiBundle\ApiServiceProvider::class,
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();
Key Config
Check config/api.php for default settings (timeout, headers, etc.).
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();
}
}
Request/Response Handling
Use the Api facade for raw requests or chain methods:
$response = Api::withHeaders(['Authorization' => 'Bearer token'])
->post('/users', ['name' => 'John'])
->json();
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);
}
Rate Limiting
Configure retry logic in config/api.php:
'retry' => [
'max_attempts' => 3,
'delay' => 1000, // milliseconds
],
Testing Mock the facade in PHPUnit:
$this->mock(Api::class)->shouldReceive('get')
->once()
->andReturn(new \Codememory\ApiBundle\Response('{"status": "success"}'));
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();
});
Limited Middleware Support
Custom middleware must extend Codememory\ApiBundle\Http\Middleware\ApiMiddleware or be applied via the facade:
Api::withMiddleware(new CustomMiddleware())->get('/endpoint');
No Automatic JSON Parsing
Always call ->json() or ->text() explicitly to decode responses.
Config Overrides
Ensure config/api.php is published before customizing settings.
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.
Custom Responses
Extend the Response class to add domain-specific methods:
class CustomResponse extends \Codememory\ApiBundle\Response {
public function getUserId() {
return $this->json()['id'];
}
}
Add Request Transformers Create a transformer class to format requests:
Api::withTransformer(new UserTransformer())->post('/users', $userData);
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());
});
Service Provider Hooks
Override the default Api instance in the service provider:
$this->app->singleton('api', function ($app) {
return new CustomApiClient($app['config']['api']);
});
How can I help you explore Laravel packages today?