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

Laravel Json Api Client Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dorvidas/laravel-json-api-client
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Dorvidas\JsonApiClient\JsonApiClientServiceProvider"
    
  2. 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',
            ],
        ],
    ],
    
  3. First Request:

    use Dorvidas\JsonApiClient\Facades\JsonApiClient;
    
    // Fetch a resource
    $posts = JsonApiClient::get('posts');
    
  4. Key Files:

    • config/json-api-client.php (config)
    • src/Dorvidas/JsonApiClient/ (core logic)
    • src/Dorvidas/JsonApiClient/Facades/JsonApiClient.php (facade)

Implementation Patterns

Common Workflows

1. Resource CRUD

// 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');

2. Relationships Handling

// 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'],
            ],
        ],
    ],
]);

3. Pagination

$posts = JsonApiClient::get('posts', ['page[number]' => 2, 'page[size]' => 10]);

4. Custom Endpoints

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');

5. Error Handling

try {
    $data = JsonApiClient::get('posts/999');
} catch (\Dorvidas\JsonApiClient\Exceptions\JsonApiException $e) {
    // Handle JSON:API errors (e.g., 404, validation errors)
    $errors = $e->getErrors();
}

Integration Tips

Laravel Eloquent Sync

Use the response data to seed or update Eloquent models:

$posts = JsonApiClient::get('posts');
Post::upsert($posts->data, ['id']);

API Versioning

Append version to the base URL in config:

'base_url' => 'https://api.example.com/v1',

Testing

Mock the client in tests:

JsonApiClient::shouldReceive('get')->once()->andReturn($mockResponse);

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • Last release in 2018—check for compatibility with Laravel 8/9/10.
    • May lack support for newer PHP features (e.g., named arguments, attributes).
  2. No Built-in Retry Logic:

    • Handle transient failures manually (e.g., with retry from spatie/laravel-retryable).
  3. Limited Middleware Support:

    • The package doesn’t natively support Laravel middleware for requests.
    • Workaround: Extend the JsonApiClient class or use a decorator pattern.
  4. No Automatic Type Casting:

    • Responses are raw arrays—manually cast to models/DTOs if needed.
  5. Config Overrides:

    • Headers/endpoints in config are merged, not replaced. Override carefully:
      JsonApiClient::setEndpoint('custom', [
          'base_url' => 'https://new.example.com',
          'headers' => ['X-Custom' => 'Header'],
      ]);
      

Debugging Tips

  1. Enable Debugging:

    JsonApiClient::setDebug(true); // Logs requests/responses to storage/logs/json-api-client.log
    
  2. Inspect Raw Responses:

    $response = JsonApiClient::get('posts', [], [], true); // Returns raw Guzzle response
    
  3. Common Issues:

    • 404 Not Found: Verify type and id in relationships.
    • 422 Unprocessable Entity: Check errors in the response for validation details.
    • CORS Issues: Ensure the API accepts requests from your Laravel app’s domain.

Extension Points

  1. 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;
    });
    
  2. Add Middleware: Extend the JsonApiClient class to support middleware:

    class CustomJsonApiClient extends \Dorvidas\JsonApiClient\JsonApiClient {
        public function withMiddleware($middleware) {
            $this->client->getEmitter()->attach($middleware);
        }
    }
    
  3. 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']);
    
  4. 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);
        });
    });
    

Pro Tips

  1. Use DTOs for Responses: Convert responses to DTOs for type safety:

    $post = JsonApiClient::get('posts/1')->toDto(PostDto::class);
    
  2. Batch Operations: Leverage JSON:API’s sparse fieldsets for efficient data fetching:

    $posts = JsonApiClient::get('posts', ['fields[posts]' => 'id,title']);
    
  3. Webhook Integration: Use the client to validate incoming webhook payloads against the API schema.

  4. Documentation: Since the package is minimal, refer to the JSON:API spec for advanced use cases.

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.
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
spatie/mailcoach-vapor