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

Call Rest Api Laravel Package

brunopicci/call-rest-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require brunopicci/call-rest-api
    

    Register the service provider in config/app.php under providers:

    Brunopicci\ServicesBundle\ServicesBundle::class,
    
  2. First Use Case: Inject the RestApiService into a controller or service:

    use Brunopicci\ServicesBundle\Services\RestApiService;
    
    public function __construct(RestApiService $restApiService) {
        $this->restApiService = $restApiService;
    }
    

    Make a simple GET request:

    $response = $this->restApiService->call('https://api.example.com/data', 'GET');
    

    Decode JSON response automatically:

    $decodedResponse = $this->restApiService->call('https://api.example.com/data', 'GET', true);
    

Implementation Patterns

Core Workflows

  1. Basic API Calls: Use the service for standard HTTP verbs (GET, POST, PUT, DELETE, etc.):

    $response = $this->restApiService->call(
        'https://api.example.com/users',
        'POST',
        false, // Decode JSON
        ['name' => 'John Doe'] // Request body
    );
    
  2. Headers and Authentication: Pass headers (e.g., for API keys or auth tokens) as an associative array:

    $response = $this->restApiService->call(
        'https://api.example.com/secure',
        'GET',
        true,
        null,
        ['Authorization' => 'Bearer token123']
    );
    
  3. Error Handling: Wrap calls in try-catch blocks to handle exceptions (e.g., network errors, invalid responses):

    try {
        $response = $this->restApiService->call('https://api.example.com/data', 'GET');
    } catch (\Exception $e) {
        Log::error("API call failed: " . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    
  4. Reusable API Clients: Create a dedicated service class for API-specific logic:

    class StripeService {
        public function __construct(RestApiService $restApiService) {
            $this->restApiService = $restApiService;
        }
    
        public function createCustomer(array $data) {
            return $this->restApiService->call(
                'https://api.stripe.com/v1/customers',
                'POST',
                true,
                $data,
                ['Authorization' => 'Bearer sk_test_...']
            );
        }
    }
    
  5. Configuration Management: Store API endpoints and default headers in config/services.php:

    'api' => [
        'base_url' => env('API_BASE_URL', 'https://api.example.com'),
        'default_headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
        ],
    ],
    

    Then inject the config into the service or use dependency injection.


Gotchas and Tips

Pitfalls

  1. No Built-in Retry Logic: The package lacks retry mechanisms for transient failures (e.g., rate limits). Implement a wrapper or use Laravel’s retry helper:

    \Illuminate\Support\Facades\Retry::retry(3, function () use ($restApiService) {
        return $restApiService->call('https://api.example.com/data', 'GET');
    });
    
  2. Limited Middleware Support: Unlike Guzzle or HTTP clients, this package doesn’t support middleware for request/response transformation. Use a decorator pattern or pre-process data manually.

  3. No Automatic Type Handling: JSON decoding returns raw arrays. For typed responses (e.g., Eloquent models), manually map responses:

    $data = $this->restApiService->call('https://api.example.com/users', 'GET', true);
    return User::create($data[0]);
    
  4. Underactive Development: The package is "under heavy development," so breaking changes may occur. Pin the version in composer.json:

    "brunopicci/call-rest-api": "1.0.*"
    

Debugging Tips

  1. Inspect Raw Responses: Pass false for decoding to debug raw HTTP responses:

    $rawResponse = $this->restApiService->call('https://api.example.com/data', 'GET', false);
    
  2. Log Headers and Payloads: Add logging before calling the service:

    \Log::debug('API Request', [
        'url' => 'https://api.example.com/data',
        'method' => 'GET',
        'headers' => ['Authorization' => 'Bearer token123'],
        'body' => null,
    ]);
    
  3. Validate API Responses: Check for HTTP status codes or custom error fields:

    $response = $this->restApiService->call('https://api.example.com/data', 'GET', true);
    if (isset($response['error'])) {
        throw new \RuntimeException($response['error']);
    }
    

Extension Points

  1. Custom Response Handling: Extend the service to add domain-specific logic:

    class CustomRestApiService extends RestApiService {
        public function callWithRetry($url, $method, $decode = true, $data = null, $headers = []) {
            return \Retry::retry(3, function () use ($url, $method, $decode, $data, $headers) {
                return parent::call($url, $method, $decode, $data, $headers);
            });
        }
    }
    
  2. Integration with Laravel HTTP Client: Use Laravel’s built-in HTTP client for advanced features (e.g., events, middleware):

    $response = Http::withHeaders(['Authorization' => 'Bearer token123'])
        ->get('https://api.example.com/data');
    
  3. Mocking for Tests: Mock the RestApiService in unit tests:

    $mock = Mockery::mock(RestApiService::class);
    $mock->shouldReceive('call')
         ->once()
         ->with('https://api.example.com/data', 'GET', true)
         ->andReturn(['key' => 'value']);
    
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui