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

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require jetcamp/laravel-json-api-client
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Jetcamp\JsonApiClient\JsonApiClientServiceProvider"
    
  2. 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();
    
  3. First Use Case: Fetching Data

    $users = JsonApiClient::client('stripe')->get('/users')->json();
    

Implementation Patterns

1. Client Configuration & Reusability

  • Dynamic Clients: Register clients dynamically in AppServiceProvider:
    JsonApiClient::extend('dynamic', function () {
        return new \Jetcamp\JsonApiClient\Client([
            'base_url' => 'https://api.example.com',
            'auth' => ['type' => 'basic', 'username' => 'user', 'password' => 'pass'],
        ]);
    });
    
  • Environment-Based Clients: Use .env for different environments (e.g., STRIPE_TEST_KEY, STRIPE_LIVE_KEY).

2. Request Customization

  • Headers & Query Params:
    $response = JsonApiClient::client('stripe')
        ->withHeaders(['X-Custom-Header' => 'value'])
        ->withQuery(['limit' => 10])
        ->get('/payments');
    
  • Request Transformers: Extend the client to modify requests:
    JsonApiClient::extend('stripe', function ($client) {
        $client->onRequest(function ($request) {
            $request->headers->set('X-App-Version', '1.0.0');
        });
        return $client;
    });
    

3. Response Handling

  • Automatic JSON Decoding:
    $data = JsonApiClient::client('stripe')->get('/events')->json();
    
  • Custom Response Parsing: Override the default JSON parser:
    $response = JsonApiClient::client('stripe')->get('/webhooks');
    $customData = json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR);
    

4. Error Handling

  • Global Exception Handling: Use Laravel’s exception handler or middleware:
    JsonApiClient::onError(function ($request, $response, $exception) {
        Log::error("API Error: {$exception->getMessage()}");
        throw new \RuntimeException('API request failed', 0, $exception);
    });
    
  • Retry Logic: Implement retries for transient failures:
    use Jetcamp\JsonApiClient\Retry\RetryPolicy;
    
    $client = JsonApiClient::client('stripe')->withRetryPolicy(
        new RetryPolicy(3, 100) // Retry 3 times with 100ms delay
    );
    

5. Integration with Laravel Features

  • Service Containers: Bind clients to the container for dependency injection:
    $this->app->bind('stripe.client', function () {
        return JsonApiClient::client('stripe');
    });
    
    Usage in a controller:
    public function __construct(private readonly \Jetcamp\JsonApiClient\Client $stripeClient) {}
    
  • Queued Jobs: Offload API calls to queues:
    dispatch(new SyncStripeCustomersJob($stripeClient));
    

Gotchas and Tips

1. Authentication Pitfalls

  • Bearer Token Expiry: Ensure tokens are refreshed if the API requires it. Use middleware:
    JsonApiClient::client('stripe')->onRequest(function ($request) {
        if ($request->headers->get('Authorization') === 'Bearer expired_token') {
            $request->headers->set('Authorization', 'Bearer ' . $this->refreshToken());
        }
    });
    
  • Basic Auth Encoding: Manually encode credentials if the package doesn’t handle it:
    'auth' => [
        'type' => 'basic',
        'username' => 'user',
        'password' => base64_encode('pass'),
    ],
    

2. Debugging

  • Enable Debugging: Toggle debug mode in config:
    'debug' => env('JSON_API_CLIENT_DEBUG', false),
    
    Logs requests/responses to storage/logs/json-api-client.log.
  • Inspect Raw Responses: Access the raw response object:
    $response = JsonApiClient::client('stripe')->get('/events');
    $statusCode = $response->getStatusCode();
    $body = $response->getBody()->getContents();
    

3. Performance Tips

  • Connection Pooling: Reuse clients instead of creating new instances:
    // Bad: Creates a new client every time
    JsonApiClient::client('stripe')->get('/...');
    
    // Good: Reuse the client
    $stripe = JsonApiClient::client('stripe');
    $stripe->get('/...');
    
  • Caching Responses: Cache frequent API calls:
    $cacheKey = 'stripe_customers';
    $customers = Cache::remember($cacheKey, now()->addHours(1), function () {
        return JsonApiClient::client('stripe')->get('/customers')->json();
    });
    

4. Extension Points

  • Custom HTTP Clients: Use Guzzle’s ClientInterface for advanced features:
    $client = new \GuzzleHttp\Client(['timeout' => 30]);
    JsonApiClient::extend('custom', function () use ($client) {
        return new \Jetcamp\JsonApiClient\Client($client);
    });
    
  • Middleware: Add custom middleware to the client:
    $client = JsonApiClient::client('stripe');
    $client->getMiddleware()->push(
        new \Jetcamp\JsonApiClient\Middleware\CustomMiddleware()
    );
    

5. Common Issues

  • SSL Errors: Disable SSL verification (temporarily for testing):
    'options' => [
        'verify' => false,
    ],
    
    Warning: Only use this in development.
  • Rate Limiting: Handle 429 Too Many Requests with retries or exponential backoff.
  • Pagination: Manually handle pagination if the API doesn’t support cursor-based pagination:
    $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']));
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony