A basic, opinionated, Laravel Api Client

Overview

Laravel Api Client

Installation

Install the pacakage via composer

composer require antonioprimera/laravel-api-client

If you want to use pre-configured clients and endpoints, rather than define authentication types, credentials, request methods and urls as part of your php code, you can create a new config file, named apiEndpoints.php.

Usage

The ApiClient can be used either based on a config file or by just creating and specifying all necessary authentication details in the code.

Example Usage without config

Create a Laravel Sanctum client. The Laravel Sanctum client will send its authentication token in the Authorization header, as the Bearer token.

    use AntonioPrimera\ApiClient\ApiClient;
    use AntonioPrimera\ApiClient\Clients\HttpClient;
    
    $response = ApiClient::makeSanctumClient()
        ->withToken('some-token')
        ->post('http://my-api-endpoint-url.com', ['id' => 15]);

Create a http client with basic authentication. This type of authentication requires the credentials to be set as an array with the username and password keys. These credentials will be encoded and sent in the Authorization header.

    use AntonioPrimera\ApiClient\ApiClient;
    use AntonioPrimera\ApiClient\Clients\HttpClient;

    $response = ApiClient::makeHttpClient()
        ->withAuthenticationType(HttpClient::AUTHENTICATION_TYPE_BASIC)
        ->withCredentials(['username' => 'my-user-name', 'password' => 'my-password'])
        ->get('http://my-api-endpoint-url.com', ['id' => 15]);

Create a http client with query authentication. For this type of authentication, the credentials are sent via query parameters in the url for get request or via the request body, for other request methods. You can provide any set of authentication data (not necessary username and password, like in the basic http authentication protocol).

The example below will make a get request to: http://my-api-endpoint-url.com?user=my-user-name&pass=my-pass&tk=my-token&id=15

    use AntonioPrimera\ApiClient\ApiClient;
    use AntonioPrimera\ApiClient\Clients\HttpClient;

    $response = ApiClient::makeHttpClient()
        ->withAuthenticationType(HttpClient::AUTHENTICATION_TYPE_QUERY)
        ->withCredentials(['user' => 'my-user-name', 'pass' => 'my-pass', 'tk' => 'my-token'])
        ->get('http://my-api-endpoint-url.com', ['id' => 15]);

Example Usage with config (see sample config below)

Create a laravel sanctum client based on the configured client 'mySanctumClient' and call a configured endpoint. If the api token is provided in the config, you can just call a configured endpoint or some other url. If the token is not available in the config, you must use the withCredentials(...) or setCredentials() method, before calling any endpoint / url.

    use AntonioPrimera\ApiClient\ApiClient;
    use AntonioPrimera\ApiClient\Clients\HttpClient;
    
    $response = ApiClient::getClient('mySanctumClient')
        ->callEndpoint('setTracks', ['tracks' => '...']);

Create a http client with basic authentication. If the credentials are provided in the config, you can just call a configured endpoint or some other url. If the credentials are not available in the config, you must use the withCredentials(...) method or the setCredentials(), before calling the endpoint.

    use AntonioPrimera\ApiClient\ApiClient;
    use AntonioPrimera\ApiClient\Clients\HttpClient;
 
    $response = ApiClient::makeClient('myBasicHttpClientWithCredentials')
        ->callEndpoint('getUser', ['user-id' => 15]);

Create a http client with query authentication. For this type of authentication, the credentials are sent via query parameters in the url for get request or via the request body, for other request methods.

    use AntonioPrimera\ApiClient\ApiClient;
    use AntonioPrimera\ApiClient\Clients\HttpClient;
    
    $response = ApiClient::getClient('myQueryHttpClient')
        ->callEndpoint('getMenu');
        

You can use a configured client to make calls to endpoints with a given url, so it's not mandatory to configure all endpoints. Just call the 'get' / 'post' / 'put' / 'patch' / 'delete' / 'head' method on the client and provide the necessary data.

    use AntonioPrimera\ApiClient\ApiClient;
    use AntonioPrimera\ApiClient\Clients\HttpClient;
    
    $response = ApiClient::getClient('myQueryHttpClient')
        ->post('http://my-api-endpoint-url.com', ['user' => ['id' => 15, 'name' => 'Gigi']]);

Config

By default, the config file apiEndpoints.php is used, so don't forget to create it if you want to use the api client based on config data.

If you want to use another config file, or to change the behavior of the ApiClient class, you must create your own ApiClient class in your project, inheriting the AntonioPrimera\ApiClient\ApiClient. Then you can override the static variable $config to point to your desider config file

use AntonioPrimera\ApiClient\ApiClient;

class MyApiClient extends ApiClient
{
    protected static $config = 'myApiConfig';
}

The Api client can be used also without a config, by specifying the http client type, the authentication type, the credentials, the url and the method to be used to make the request.

//sample config
return [

    //the name of the client, usually the name of an external api provider e.g. "github" / "instagram"
    'mySanctumClient' => [
        
        //mandatory to have at least the authentication type provided
        'authentication' => [
            'type'  => 'sanctum',
            
            //(optional) if not provided, must be provided at run-time
            'token' => env('MY_SANCTUM_TOKEN'),
        ],
        
        //(optional) if rootUrl is provided it will be prepended to each endpoint url
        'rootUrl' => 'https://localhost:8080/',
        
        //the list of all endpoints
        'endpoints' => [
        
            'setTracks' => [                //endpoint name, to be used in development (like a route name)
                'url'    => '/tracks/',     //url is mandatory
                'method' => 'post',         //(optional) by default: 'get'
            ],
            
            //endpoints with method 'get' can also be provided as strings
            'getPositions' => 'positions',
        ],
    ],
    
    //example of a provider with a basic http authentication
    'myBasicHttpClientWithCredentials' => [
        'authentication' => [
            'type' => 'http:basic',
            
            //optional
            'credentials' => [
                'username' => env('MY_HTTP_CLIENT_USERNAME'),
                'password' => env('MY_HTTP_CLIENT_PASSWORD'),
            ],
        ],
        
        'endpoints' => [
            //... all endpoints are the same, regardless of the authentication type
        ],
    ],
    
    //example of a provider with an authentication via query parameters (credentials are sent as part of the url)
    'myQueryHttpClient' => [
        'authentication' => [
            'type' => 'http:query',
            
            //credentials are optional (can be provided at runtime via method $client->setCredentials(...)
            'credentials' => [
                'key' 		 => 'my-key',
                'passphrase' => 'my-phrase',
                'token'		 => 'my-token',
            ],

        ],
        
        'endpoints' => [
            //... all endpoints are the same, regardless of the authentication type
        ],
    ],    
];
You might also like...
Laravel api tool kit is a set of tools that will help you to build a fast and well-organized API using laravel best practices.
Laravel api tool kit is a set of tools that will help you to build a fast and well-organized API using laravel best practices.

Laravel API tool kit and best API practices Laravel api tool kit is a set of tools that will help you to build a fast and well-organized API using lar

PHP Pi Horizon Client Library

phpi-sdk PHP Pi Horizon Client Library This is part of FASTLANE project for the pi payment gateway, as we are trying to build a pi wallet inside FASTL

PSR-15 middleware to geolocate the client using the ip address

middlewares/geolocation ![SensioLabs Insight][ico-sensiolabs] Middleware to geolocate the client using the ip address and Geocoder and save the result

This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science courses and the like.
This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science courses and the like.

Simple PHP API v.1.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science courses a

微信支付 API v3 的 PHP Library,同时也支持 API v2

微信支付 WeChatPay OpenAPI SDK [A]Sync Chainable WeChatPay v2&v3's OpenAPI SDK for PHP 概览 微信支付 APIv2&APIv3 的Guzzle HttpClient封装组合, APIv2已内置请求数据签名及XML转换器,应

This API provides functionality for creating and maintaining users to control a simple To-Do-List application. The following shows the API structure for users and tasks resources.
This API provides functionality for creating and maintaining users to control a simple To-Do-List application. The following shows the API structure for users and tasks resources.

PHP API TO-DO-LIST v.2.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science cours

API documentation API SCB EASY APP

SCB-API-EASY V3.0 API documentation SIAM COMMERCIAL BANK PUBLIC COMPANY LTD. API SCB Easy V3 endpoint = https://fasteasy.scbeasy.link 1.0. Get balance

Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota & International
Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota & International

Courier API Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota (dalam negeri) & International

LaraBooks API - Simple API for iOS SwiftUI app tests.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Releases(v1.3)
Owner
Antonio Primera
Developer: PHP Laravel, VueJs, ABAP. Entrepreneur: AgroCity - digital farm management software (Farm ERP).
Antonio Primera
Chargebee API PHP Client (for API version 2 and Product Catalog version 2.0)

chargebee-php-sdk Overview This package provides an API client for Chargebee subscription management services. It connects to Chargebee REST APIs for

GLOBALIS media systems 8 Mar 8, 2022
Laravel A2Reviews Client API lets you build apps, extensions, or plugins to get reviews from the A2reviews APP.

Overview Laravel A2Reviews Client API lets you build apps, extensions or plugins to get reviews from the A2reviews APP. Including adding reviews to a

Be Duc Tai 2 Sep 26, 2021
Laravel Client REST Camunda API

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Uriel Reyes 1 Nov 5, 2021
Simple Client for Airtable API

Airtable Client Bundle (Work In Progress) The Airtable Client bundle is a Symfony bundle that attempts to make the Airtable API easier to use. Retriev

Yoan Bernabeu 28 May 12, 2022
The efficient and elegant, PSR-7 compliant JSON:API 1.1 client library for PHP

Woohoo Labs. Yang Woohoo Labs. Yang is a PHP framework which helps you to communicate with JSON:API servers more easily. Table of Contents Introductio

Woohoo Labs. 160 Oct 16, 2022
PHP unofficial client to CryptoPanic.com API

PHP unofficial client to CryptoPanic.com API CryptoPanic.com is a news aggregator platform indicating impact on price and market for traders and crypt

null 6 Nov 2, 2022
Tuya Api PHP Client

Tuya Api PHP Client This is a simple php client to interact with devices that support the tuya api over the cloud. Requirements I believe all is neede

null 11 Sep 22, 2022
This is the PHP ApiDQ API client

ApiDQ API PHP Client This is the PHP ApiDQ API client. This library allows using of the actual API version. You can find more info in the documentatio

Nikita Krasnikov 2 Oct 5, 2021
Airbrake.io & Errbit integration for Symfony 3/4/5. This bundle plugs the Airbrake API client into Symfony project

AmiAirbrakeBundle Airbrake.io & Errbit integration for Symfony 3/4/5. This bundle plugs the Airbrake API client into Symfony project. Prerequisites Th

Anton Minin 8 May 6, 2022
Simple and effective multi-format Web API Server to host your PHP API as Pragmatic REST and / or RESTful API

Luracast Restler ![Gitter](https://badges.gitter.im/Join Chat.svg) Version 3.0 Release Candidate 5 Restler is a simple and effective multi-format Web

Luracast 1.4k Dec 14, 2022