jetcamp/laravel-json-api-client
Laravel package for consuming JSON:API services from your app. Provides a client layer to send requests and handle resources/relationships in a JSON:API-compatible way, aiming to simplify integration with external APIs.
Installation
composer require jetcamp/laravel-json-api-client
Publish the config (if needed):
php artisan vendor:publish --provider="Jetcamp\JsonApiClient\JsonApiClientServiceProvider"
Basic Usage
Define a client in config/json-api-client.php:
'clients' => [
'stripe' => [
'base_url' => 'https://api.stripe.com/v1',
'auth' => [
'type' => 'bearer',
'token' => env('STRIPE_SECRET_KEY'),
],
],
],
Use the client in a service or controller:
use Jetcamp\JsonApiClient\Facades\JsonApiClient;
$response = JsonApiClient::client('stripe')->get('/customers');
$data = $response->json();
First Use Case: Fetching Data
$users = JsonApiClient::client('stripe')->get('/users')->json();
AppServiceProvider:
JsonApiClient::extend('dynamic', function () {
return new \Jetcamp\JsonApiClient\Client([
'base_url' => 'https://api.example.com',
'auth' => ['type' => 'basic', 'username' => 'user', 'password' => 'pass'],
]);
});
.env for different environments (e.g., STRIPE_TEST_KEY, STRIPE_LIVE_KEY).$response = JsonApiClient::client('stripe')
->withHeaders(['X-Custom-Header' => 'value'])
->withQuery(['limit' => 10])
->get('/payments');
JsonApiClient::extend('stripe', function ($client) {
$client->onRequest(function ($request) {
$request->headers->set('X-App-Version', '1.0.0');
});
return $client;
});
$data = JsonApiClient::client('stripe')->get('/events')->json();
$response = JsonApiClient::client('stripe')->get('/webhooks');
$customData = json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR);
JsonApiClient::onError(function ($request, $response, $exception) {
Log::error("API Error: {$exception->getMessage()}");
throw new \RuntimeException('API request failed', 0, $exception);
});
use Jetcamp\JsonApiClient\Retry\RetryPolicy;
$client = JsonApiClient::client('stripe')->withRetryPolicy(
new RetryPolicy(3, 100) // Retry 3 times with 100ms delay
);
$this->app->bind('stripe.client', function () {
return JsonApiClient::client('stripe');
});
Usage in a controller:
public function __construct(private readonly \Jetcamp\JsonApiClient\Client $stripeClient) {}
dispatch(new SyncStripeCustomersJob($stripeClient));
JsonApiClient::client('stripe')->onRequest(function ($request) {
if ($request->headers->get('Authorization') === 'Bearer expired_token') {
$request->headers->set('Authorization', 'Bearer ' . $this->refreshToken());
}
});
'auth' => [
'type' => 'basic',
'username' => 'user',
'password' => base64_encode('pass'),
],
'debug' => env('JSON_API_CLIENT_DEBUG', false),
Logs requests/responses to storage/logs/json-api-client.log.$response = JsonApiClient::client('stripe')->get('/events');
$statusCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
// Bad: Creates a new client every time
JsonApiClient::client('stripe')->get('/...');
// Good: Reuse the client
$stripe = JsonApiClient::client('stripe');
$stripe->get('/...');
$cacheKey = 'stripe_customers';
$customers = Cache::remember($cacheKey, now()->addHours(1), function () {
return JsonApiClient::client('stripe')->get('/customers')->json();
});
ClientInterface for advanced features:
$client = new \GuzzleHttp\Client(['timeout' => 30]);
JsonApiClient::extend('custom', function () use ($client) {
return new \Jetcamp\JsonApiClient\Client($client);
});
$client = JsonApiClient::client('stripe');
$client->getMiddleware()->push(
new \Jetcamp\JsonApiClient\Middleware\CustomMiddleware()
);
'options' => [
'verify' => false,
],
Warning: Only use this in development.429 Too Many Requests with retries or exponential backoff.$page = 1;
do {
$response = JsonApiClient::client('stripe')
->withQuery(['page' => $page])
->get('/large_dataset');
$data = $response->json();
$page++;
} while ($response->getStatusCode() === 200 && isset($data['next_page']));
How can I help you explore Laravel packages today?