dorvidas/laravel-json-api-client
Laravel package for consuming JSON:API services with a simple client in Laravel apps. Helps you send requests, handle responses, and work with JSON:API resources in a structured way. Suitable for integrating external APIs with minimal boilerplate.
Installation:
composer require dorvidas/laravel-json-api-client
Publish the config file (if needed):
php artisan vendor:publish --provider="Dorvidas\JsonApiClient\JsonApiClientServiceProvider"
Configuration:
Edit config/json-api-client.php to define your API endpoints:
'endpoints' => [
'default' => [
'base_url' => 'https://api.example.com',
'headers' => [
'Accept' => 'application/vnd.api+json',
'Authorization' => 'Bearer YOUR_TOKEN',
],
],
],
First Request:
use Dorvidas\JsonApiClient\Facades\JsonApiClient;
// Fetch a resource
$posts = JsonApiClient::get('posts');
Key Files:
config/json-api-client.php (config)src/Dorvidas/JsonApiClient/ (core logic)src/Dorvidas/JsonApiClient/Facades/JsonApiClient.php (facade)// Create
$post = JsonApiClient::post('posts', [
'data' => [
'type' => 'posts',
'attributes' => ['title' => 'Hello World'],
],
]);
// Read
$posts = JsonApiClient::get('posts?filter[published]=true');
// Update
$post = JsonApiClient::patch('posts/1', [
'data' => [
'id' => '1',
'type' => 'posts',
'attributes' => ['title' => 'Updated Title'],
],
]);
// Delete
JsonApiClient::delete('posts/1');
// Fetch with included relationships
$post = JsonApiClient::get('posts/1', ['include' => 'author,comments']);
// Create with relationships
$post = JsonApiClient::post('posts', [
'data' => [
'type' => 'posts',
'attributes' => ['title' => 'Related Post'],
'relationships' => [
'author' => [
'data' => ['id' => '1', 'type' => 'users'],
],
],
],
]);
$posts = JsonApiClient::get('posts', ['page[number]' => 2, 'page[size]' => 10]);
Define a custom endpoint in config:
'endpoints' => [
'admin' => [
'base_url' => 'https://admin.example.com',
'headers' => ['Authorization' => 'Bearer ADMIN_TOKEN'],
],
],
Use it in code:
$stats = JsonApiClient::get('stats', [], 'admin');
try {
$data = JsonApiClient::get('posts/999');
} catch (\Dorvidas\JsonApiClient\Exceptions\JsonApiException $e) {
// Handle JSON:API errors (e.g., 404, validation errors)
$errors = $e->getErrors();
}
Use the response data to seed or update Eloquent models:
$posts = JsonApiClient::get('posts');
Post::upsert($posts->data, ['id']);
Append version to the base URL in config:
'base_url' => 'https://api.example.com/v1',
Mock the client in tests:
JsonApiClient::shouldReceive('get')->once()->andReturn($mockResponse);
Deprecated Package:
No Built-in Retry Logic:
retry from spatie/laravel-retryable).Limited Middleware Support:
JsonApiClient class or use a decorator pattern.No Automatic Type Casting:
Config Overrides:
JsonApiClient::setEndpoint('custom', [
'base_url' => 'https://new.example.com',
'headers' => ['X-Custom' => 'Header'],
]);
Enable Debugging:
JsonApiClient::setDebug(true); // Logs requests/responses to storage/logs/json-api-client.log
Inspect Raw Responses:
$response = JsonApiClient::get('posts', [], [], true); // Returns raw Guzzle response
Common Issues:
type and id in relationships.errors in the response for validation details.Custom Request Transformers:
Override the transformRequest method in a service provider:
JsonApiClient::macro('transformRequest', function ($data, $method) {
// Add custom logic (e.g., timestamp, auth tokens)
return $data;
});
Add Middleware:
Extend the JsonApiClient class to support middleware:
class CustomJsonApiClient extends \Dorvidas\JsonApiClient\JsonApiClient {
public function withMiddleware($middleware) {
$this->client->getEmitter()->attach($middleware);
}
}
Support for Non-JSON:API Endpoints:
Use the setBaseUrl and setHeaders methods dynamically:
JsonApiClient::setBaseUrl('https://legacy-api.example.com');
JsonApiClient::setHeaders(['Accept' => 'application/json']);
Caching Responses: Implement a decorator to cache responses:
JsonApiClient::macro('cachedGet', function ($endpoint, $params = [], $endpointName = 'default', $cacheFor = 60) {
return Cache::remember("jsonapi.{$endpoint}", $cacheFor, function () use ($endpoint, $params, $endpointName) {
return JsonApiClient::get($endpoint, $params, $endpointName);
});
});
Use DTOs for Responses: Convert responses to DTOs for type safety:
$post = JsonApiClient::get('posts/1')->toDto(PostDto::class);
Batch Operations:
Leverage JSON:API’s sparse fieldsets for efficient data fetching:
$posts = JsonApiClient::get('posts', ['fields[posts]' => 'id,title']);
Webhook Integration: Use the client to validate incoming webhook payloads against the API schema.
Documentation: Since the package is minimal, refer to the JSON:API spec for advanced use cases.
How can I help you explore Laravel packages today?