It's a small wrapper to easily and quickly consume external APIs in Laravel
Install API Client Wrapper in your laravel app using
composer require softok2/api-client-wrapperPublishing the config file is optional:
php artisan vendor:publish --provider="Softok2\RestApiClient\Providers\ServiceProvider" --tag="config"To run this project, you will need to add the following environment variables to your .env file
REST_API_URL
REST_API_TIMEOUT
php artisan make:apic AuthThis command would be generate a resource classs under App\Services\API directory. This class look like this:
<?php
class Auth implements ClientResourceInterface
{
public function __construct(protected RestClientInterface $client)
{
}
/**
* Retrieve the 'slug' to hook this class into global service client...
*/
public static function getSlug(): string
{
return strtolower('Auth');
}
}Now you can define a login endpoint in this resources class:
<?php
public function login(array $data): mixed
{
return $this->client->post('/login', $data)
}You can even add custom callable functions to handle success and error response:
<?php
public function login(array $data): mixed
{
return $this->client->post('/login', $data)
}<?php
class AuthController extends Controller
{
public function index(RestClientInterface $client)
{
$data = [
'user' => request('user'),
'password' => request('password'),
]
try{
$token = $this->client->auth->login($data);
// Storage token and redirect ...
}catch(Exception $exception){
// Handle custom errors
}
}
}To run tests, run the following command
./vendor/bin/pest - Multiple apis