We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies.

We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies. Less

We use cookies and other tracking technologies... More

Login or register
to apply for this job!

Login or register
to save this job!

Login or register
to save interesting jobs!

Login or register
to get access to all your job applications!

Login or register to start contributing with an article!

Login or register
to see more jobs from this company!

Login or register
to boost this post!

Show some love to the author of this blog by giving their post some rocket fuel 🚀.

Login or register to search for your ideal job!

Login or register to start working on this issue!

Engineers who find a new job through WorksHub average a 15% increase in salary 🚀

Blog hero image

How to Integrate Third-Party APIs in Laravel

Magdalena Siljanoska Spinola 8 February, 2021 | 3 min read

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!

Author's avatar
Magdalena Siljanoska Spinola
Software engineer @ Ycode
    HTML
    CSS
    JavaScript
    PHP
    Laravel
    Docker
    Git
    Unit testing

Related Issues

cosmos / gaia
  • Open
  • 0
  • 0
  • Intermediate
  • Go
cosmos / gaia
  • Open
  • 0
  • 0
  • Intermediate
  • Go
cosmos / ibc
  • Open
  • 0
  • 0
  • Intermediate
  • TeX
cosmos / ibc
cosmos / ibc
  • Open
  • 0
  • 0
  • Intermediate
  • TeX
WorksHub / client
  • Started
  • 0
  • 28
  • Intermediate
  • Clojure
  • $150
viebel / klipse-clj
viebel / klipse-clj
  • Started
  • 0
  • 4
  • Intermediate
  • Clojure
viebel / klipse
  • Started
  • 0
  • 1
  • Intermediate
  • Clojure
viebel / klipse
  • 1
  • 0
  • Intermediate
  • Clojure

Get hired!

Sign up now and apply for roles at companies that interest you.

Engineers who find a new job through WorksHub average a 15% increase in salary.

Start with GitHubStart with Stack OverflowStart with Email