laravel-rest-client maintained by codecoz
CodeCoz Laravel REST Client
A powerful, Laravel-native REST API client package built on top of Illuminate\Http\Client. It provides a clean, fluent syntax for consuming external RESTful APIs with enterprise-grade features:
- Authentication handling (Bearer token, API key)
- Comprehensive request/response logging
- Intelligent response caching
- Robust exception handling with specific exception classes
- Easy creation of specific API wrappers
- Fully configurable and extensible
Website: https://codecoz.com
GitHub Repository: https://github.com/codecoz/laravel/rest-client
Features
- Built exclusively on Laravel's native
Illuminate\Http\Client(no direct Guzzle dependency) - Global and per-request authentication (Bearer token, API key, custom headers)
- Automatic request/response logging via Laravel HTTP Client events
- Smart caching with global and per-call control
- Advanced exception handling (4xx, 5xx, connection errors)
- Fluent, chainable API with Laravel-style syntax
- Support for building tailored API wrappers
- Fully configurable via published config file
- PSR-4 compliant, follows SOLID and KISS principles
- Compatible with Laravel 10, 11 and 12
Installation
Require the package via Composer:
composer require codecoz/laravel-rest-client
Publish Configuration
php artisan vendor:publish --provider="CodeCoz\Laravel\RestClient\RestClientServiceProvider" --tag="rest-client-config"
Configuration
After publishing, edit config/rest-client.php or use environment variables:
REST_CLIENT_BASE_URL=https://api.example.com
REST_CLIENT_LOGGING=true
REST_CLIENT_LOG_CHANNEL=stack
REST_CLIENT_LOG_SANITIZE=true
REST_CLIENT_LOG_PAYLOAD=true
REST_CLIENT_LOG_LEVEL=debug
REST_CLIENT_CACHING=false
REST_CLIENT_CACHE_STORE=file
REST_CLIENT_AUTH_TYPE=bearer
Key Configuration Options
return [
'base_url' => env('REST_CLIENT_BASE_URL', 'https://api.example.com'),
'default_auth' => [
'type' => env('REST_CLIENT_AUTH_TYPE', 'bearer'),
'header' => env('REST_CLIENT_AUTH_HEADER', 'Authorization'),
'token' => env('REST_CLIENT_AUTH_TOKEN'),
'param_key' => env('REST_CLIENT_API_KEY_PARAM', 'api_key'),
'provider' => null // \App\Services\MyTokenProvider::class
],
'logging' => [
'enabled' => env('REST_CLIENT_LOGGING', true),
'sanitize'=> env('REST_CLIENT_LOG_SANITIZE', true),
'payload' => env('REST_CLIENT_LOG_PAYLOAD', true),
'channel' => env('REST_CLIENT_LOG_CHANNEL', 'stack'),
'level' => env('REST_CLIENT_LOG_LEVEL', 'debug'),
],
'caching' => [
'enabled' => env('REST_CLIENT_CACHING', false),
'store' => env('REST_CLIENT_CACHE_STORE', 'file'),
'ttl' => env('REST_CLIENT_CACHE_LIFETIME', 3600), // 1 hour default
],
];
Usage
Basic HTTP Requests
use CodeCoz\Laravel\RestClient\Facades\RestClient;
// GET request
$response = RestClient::get('/posts');
// GET with query parameters
RestClient::get('/posts', ['page' => 2]);
// POST request
RestClient::post('/posts', ['title' => 'New Post', 'body' => '...']);
// Form data
RestClient::asForm()->post('/login', [
'email' => 'user@example.com',
'password' => 'secret'
]);
// Chain options
RestClient::cache(600)
->withoutLogging()
->get('/expensive-endpoint');
Authentication
Global (via config):
// config/rest-client.php
'auth' => [
'type' => 'bearer',
'token' => 'your-global-token-here',
]
Per-request override:
RestClient::withToken('temporary-token')->get('/protected-resource');
Logging
Logging is enabled by default and uses Laravel's log channels. Logs include URL, method, headers, and body. Disable for sensitive requests:
RestClient::withoutLogging()->post('/webhook', $payload);
Caching
Enable globally in config or per request:
// Cache response for 10 minutes
RestClient::cache(600)->get('/slow-endpoint');
// Disable caching for a specific call
RestClient::withoutCache()->get('/real-time-data');
Exception Handling
The package throws meaningful exceptions:
use CodeCoz\Laravel\RestClient\Facades\RestClient;
use CodeCoz\Laravel\RestClient\Exceptions\{
ClientErrorException,
ServerErrorException,
ConnectionException,
RestClientException
};
try {
$data = RestClient::get('/users/999')->json();
} catch (ClientErrorException $e) {
// 4xx errors (401, 403, 404, 422, etc.)
// Access API error details: $e->getResponseData()
return response()->json(['error' => $e->getMessage()], $e->getCode());
} catch (ServerErrorException $e) {
// 5xx errors
\Log::error('External API error', ['exception' => $e]);
} catch (ConnectionException $e) {
// Network / timeout / DNS issues
return response()->json(['error' => 'Service unavailable'], 502);
} catch (RestClientException $e) {
// Any other API-related error
}
Building Specific API Wrappers
Create clean, reusable clients for any external API:
// app/Services/GitHubApiClient.php
namespace App\Services;
use CodeCoz\Laravel\RestClient\Facades\RestClient;
class GitHubApiClient
{
public function __construct()
{
RestClient::withToken(config('services.github.token'))
->baseUrl('https://api.github.com');
}
public function getUser(string $username)
{
return RestClient::cache(300)
->get("/users/{$username}")
->json();
}
public function getRepos(string $username)
{
return RestClient::get("/users/{$username}/repos")->json();
}
public function createIssue(string $owner, string $repo, array $data)
{
return RestClient::post("/repos/{$owner}/{$repo}/issues", $data)->json();
}
}
Usage:
$github = new App\Services\GitHubApiClient();
$user = $github->getUser('torvalds');
Testing
The package includes unit tests using Orchestra Testbench. Run tests with:
composer test
Changelog
Please see CHANGELOG.md for recent changes.
Contributing
Contributions are welcome! Please follow the standard GitHub flow:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
Security
If you discover any security-related issues, please email hello@codecoz.com instead of using the issue tracker.
Credits
CodeCoz Team All contributors
License
The MIT License (MIT). Please see License File for more information.
This is the complete, production-ready `README.md` file for the `codecoz/laravel-rest-client` package, combining all previous features, code examples, and best practices into a single, well-structured Markdown document.