We're planting a tree for every job application! Click here to learn more

How to Integrate Third-Party APIs in Laravel

Magdalena Siljanoska Spinola

8 Feb 2021

3 min read

How to Integrate Third-Party APIs in Laravel
  • API Integrations

Developing customized complex software systems is usually challenging, time-consuming and expensive, especially if it consists of multiple modules. One way to mitigate the cost of that is to integrate third-party APIs in our project and achieve what we need in less time, at a lower cost.

Understanding third-party integrations

The term third-party integration generally means adding external data that we need in our projects, by using different APIs that are not part of our project.

By using third-party APIs, we can develop things faster, as we don't create code from scratch, but we reuse already existing code by just sending a couple of calls to a third-party API.

Let's take a look at a couple of examples:

  1. We're developing an info website for a book store. This book store very often has discounts and they publish them on Twitter, so they want their Tweets Feed to be on their website as well. In this case, we come to a scenario where we should use a third-party API and in this case, it's the API of Twitter.

  2. Now let's say we're developing an e-commerce website where people can buy/sell products and there should be a chat feature. In this case, we don't necessarily have to use a third-party API, but to lower the cost and the time that it will take to develop such a feature, we can simply reuse some third-party API that provides a chat.

Integrations of third-party APIs in Laravel

Developing something that includes third-party APIs in Laravel is a breeze!

I strongly believe that the best way to learn something is by seeing an actual example, so to understand better how to do this, we will be following some steps to reach our goal.

We will assume that we have an up-and-running laravel application, so we'll skip the steps of installing one.

First, we have to install guzzlehttp/guzzle which is a PHP HTTP client that makes our lives easier when it comes to sending HTTP requests to third-party APIs. We can install this client by running the following command:

composer require guzzlehttp/guzzle

Now that we have it installed, we will jump to implementing a third-party API integration. In the demo project for this article, I'm using a public API of a very popular topic right now, COVID statistics.

In this example, we'll get the total confirmed, recovered and death cases in the Republic of North Macedonia.

So, we have a service that has one method which returns total cases by country and type, where the type can be one of these: confirmed, recovered, deaths.

<?php

namespace App\Services;

use Carbon\Carbon;

class CovidStatisticService
{
    public function getTotalCasesByCountryAndType($country, $type)
    {
        $today = Carbon::now()->toDateString();

        $httpClient = new \GuzzleHttp\Client();
        $request =
            $httpClient
                ->get("https://api.covid19api.com/total/country/${country}/status/${type}?from=${today}&to=${today}");

        $response = json_decode($request->getBody()->getContents());

        return $response[count($response) - 1];
    }
}

Here we send a request i.e. we call the third-party API using the guzzle HTTP client that we installed earlier and the response of that request gives us the data we want which then we can manipulate the way we need it and send it to the front end so that we can also see it.

In this case, we get the data, convert it to a readable JSON format by using json_decode and then return the last item of the response, as that would be the latest COVID statistics, which is what we want.

As I said above, if we want to send this data to the front end and show it, we can do it like this:

<?php

namespace App\Http\Controllers;


use App\Services\CovidStatisticService;
use Carbon\Carbon;

class HomeController extends Controller
{
    public function index(CovidStatisticService $covidStatisticService) {
        $today = Carbon::now()->toDateString();
        
        $confirmedCovidCasesUntilToday = $covidStatisticService->getTotalCasesByCountryAndType('macedonia', 'confirmed');
        $recoveredCovidCasesUntilToday = $covidStatisticService->getTotalCasesByCountryAndType('macedonia', 'recovered');
        $deadCovidCasesUntilToday = $covidStatisticService->getTotalCasesByCountryAndType('macedonia', 'deaths');

        return view('index', [
            'today' => $today,
            'confirmedCovidCasesUntilToday' => $confirmedCovidCasesUntilToday,
            'recoveredCovidCasesUntilToday' => $recoveredCovidCasesUntilToday,
            'deadCovidCasesUntilToday' => $deadCovidCasesUntilToday,
        ]);
    }
}

Here, we get the numbers of all the types of cases available and today's date, so that we can show it to the front end and at the moment of writing this article the results look like this:

covid-cases.png

Conclusion

I think we can all agree that developing something that includes third-party APIs in Laravel is a breeze!

I hope this article will help those that are trying to learn the basics of integrating third-party APIs in Laravel. 

The full code of this article can be found here. If you have any questions, don't think twice to reach out to me! I'm more than happy to help!

Keep coding, do awesome stuff and stay happy! 😊

Sign up to Functional Works for more articles like this!

Did you like this article?

Magdalena Siljanoska Spinola

Software engineer by profession. Plants, books, languages, teaching and art fanatic by nature. Software engineer @MyZenTeam

See other articles by Magdalena

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
hello@works-hub.com

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2024 WorksHub

Privacy PolicyDeveloped by WorksHub