Language:

Search

Cómo manejar múltiples conexiones API en Laravel

  • Share this:
Cómo manejar múltiples conexiones API en Laravel

Introduction

Working with APIs can be a complex and time-consuming process, requiring you to handle a wide range of tasks. The LaraClient package is designed to simplify this process, making it easy to work with APIs in Laravel.

Lara Client is a Laravel package that simplifies the process of working with multiple APIs in Laravel by allowing developers to set up API connections in a central configuration file, specifying the base URI, API key, and other settings for each connection. The package also includes a cache layer to speed up requests, and a logging system to track API requests and responses for debugging purposes. With Lara Client, developers can quickly integrate multiple APIs into their Laravel applications, reducing development time and effort, and making it easier to manage API integrations over time. It also provides support for other HTTP methods such as POST, PUT, and DELETE, making it easy to interact with a wide range of APIs.

Also Read: Top Laravel Interview Questions

One of the key benefits of LaraClient is its ease of use. Once you've set up your API connections in the configuration file, making API requests is as simple as calling a few methods on the LaraClient.php class.

Installation

To install the package, simply install it from composer.

composer require usamamuneerchaudhary/laraclient

Once the package is installed, run the migrations which will create the logging table

Also Read: One to Many Polymorphic Relationship in Laravel

php artisan migrate

and finally, don't forget to add the LaraClientServiceProvider to app.php

Usamamuneerchaudhary\LaraClient\LaraClientServiceProvider::class,

Also, publish the config file using the following command:

php artisan vendor:publish --provider="Usamamuneerchaudhary\LaraClient\LaraClientServiceProvider" --tag="config"

This will create a lara_client.php file in config directory of your Laravel app. This file contains all the connection strings to third party APIs.

For this example, we'll be using geoDB cities API and Weather API to demonstrate.

Our lara_client.php looks like this:

<?php
return [
    'default' => env('API_CLIENT', 'weatherapi'),
    'connections' => [
        'geodb' => [
            'base_uri' => env('GEODB_BASE_URI', 'https://wft-geo-db.p.rapidapi.com/v1/geo/'),
            'api_key' => env('GEODB_API_KEY', ''),
            'default_headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'X-RapidAPI-Key' => '23c6b0817bmsh5720c5bcb04bb86p151c03jxxxxxxxxxxx',
                'X-RapidAPI-Host' => 'wft-geo-db.p.rapidapi.com'
            ],
            'api_secret' => env('GEODB_API_SECRET', ''),
            'timeout' => env('GEODB_TIMEOUT', 30),
            'rate_limit' => [
                'limit' => env('GEODB_RATE_LIMIT', 60),
                'interval' => env('GEODB_RATE_LIMIT_INTERVAL', 60),
            ],
        ],
        'weatherapi' => [
            'base_uri' => env('WEATHERAPI_BASE_URI', 'https://weatherapi-com.p.rapidapi.com/'),
            'api_key' => env('WEATHERAPI_API_KEY', ''),
            'default_headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'X-RapidAPI-Key' => '23c6b0817bmsh5720c5bcb04bb86p151c03jxxxxxxxxxx'
            ],
            'api_secret' => env('WEATHERAPI_API_SECRET', ''),
            'timeout' => env('WEATHERAPI_TIMEOUT', 30),
            'rate_limit' => [
                'limit' => env('WEATHERAPI_RATE_LIMIT', 60),
                'interval' => env('WEATHERAPI_RATE_LIMIT_INTERVAL', 60),
            ],
        ],
    ],
];

you can put these environment variables into .env file.

Pro Tip for different app environments

You can also easily configure API keys and other settings for different environments like development, staging, or production using environment variables.

Also Read: Laravel API Development

In your .env file, add the required API keys and settings for your development environment:

MYAPI_BASE_URI=https://api.example.com/
MYAPI_API_KEY=your_development_api_key
MYAPI_API_SECRET=your_development_api_secret
MYAPI_TIMEOUT=30
MYAPI_RATE_LIMIT=60
MYAPI_RATE_LIMIT_INTERVAL=60

For different environments like staging or production, create new environment files like .env.staging or .env.production and add the API keys and settings specific to each environment:

When deploying your application to different environments, set the appropriate environment variables for each environment. You can use the php artisan config:cache command to cache the configuration files after setting the environment variables.

By using environment variables, you can easily configure your API keys and settings for different environments without changing your application code. This approach is secure and flexible, allowing you to manage sensitive data like API keys in a centralized location.

Use case

Now everything's set up, we can use our two defined APIs in our app. For this example, we're using the simpler approach.

Create a Laravel controller: 

php artisan make:controller ApiController
<?php
namespace App\Http\Controllers;
use Usamamuneerchaudhary\LaraClient\LaraClient;
class ApiController extends Controller
{
    
    
    public function geodbapi()
    {
        $client = new LaraClient('geodb');
        $response = $client->get('countries');
        $currentWeather = $response->getData();
    }
    public function weatherapi()
    {
        $client = new LaraClient('weatherapi');
        $response = $client->get('current.json', ['q' => 'london']);
        $currentWeather = $response->getData();
    }
}

You can return this data to a view or play around with the JSON data as you like:

Logging

This package also comes up with this cool logging system that tracks requests and responses for each call made to any API. This can be incredibly useful for debugging purposes, allowing you to see the exact data that was sent and received during each API interaction. The logs can be stored in the database, and can be accessed via custom route on your browser:

Also Read: Automate database backups in Laravel

http://yourwebsite.com/laraclient/logs

This will display a list of calls made with endpoints, time, request payload, and response body.

You can also filter logs via endpoint like:

http://yourwebsite.com/laraclient/logs?endpoint=https://weatherapi-com.p.rapidapi.com/current.json

Also Read: Standardise API Responses in Laravel

In this similar manner, we can make use of POST, PUT/PATCH calls as well.

Scenarios for integrating multiple APIs

Multiple APIs can be useful in a variety of scenarios. For example, if you're building an e-commerce application, you might use one API to handle payments, another API to manage shipping and logistics, and a third API to handle customer service inquiries. Alternatively, if you're building a social media platform, you might use one API to handle authentication and user data, another API to handle messaging, and a third API to handle media uploads and downloads. Multiple APIs can also be useful in scenarios where you need to integrate with third-party services such as weather or mapping APIs. By using multiple APIs, you can leverage the strengths of each service to build a more robust and flexible application.

Also Read: Laravel Livewire comments

Conclusion

In conclusion, the LaraClient package offers an intuitive and streamlined approach to working with APIs in Laravel. By simplifying authentication, rate limiting, error handling, and more, LaraClient can help developers to save time and effort while building API-driven applications. With its easy setup and logging features, LaraClient is a valuable tool for anyone looking to work with APIs in their Laravel applications.

Github Repository: LaraClient

TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques