DEV Community

Cover image for Efficient API Interaction And Consumption With Laravel: A Beginner's Guide
Emmanuel C. Okolie
Emmanuel C. Okolie

Posted on

Efficient API Interaction And Consumption With Laravel: A Beginner's Guide

Introduction

Laravel is a popular PHP framework for developing and building web applications and API. As a developer, there will come a time when you will need to create your API or Consume an External API, and Interact with it. this is one phase you can’t run away from, so as a Laravel Developer There are ways to consume and interact with an API which is what we will be looking at.
API is an acronym that stands for Application Programming Interface. API does Cool things and That is one reason developers accept it.
So without wasting much of Your Time, jump straight into This Tutorial.

Prerequisites

The prerequisites for creating and interacting with an API are as follows:

  1. PHP: Make sure you know PHP and how to use OOP to be precise. Laravel is a framework of PHP so you need to have PHP installed on your system. Note: you should have a PHP version greater than version 7.8 installed in your system.
  2. Composer: A PHP dependency management is called Composer. It is used to manage and install the dependencies that Laravel needs. The composer must be set up on your computer.
  3. Web Server: To serve your Laravel application, you'll need a web server like Xampp OR Wamp server. Both servers enable you to use MySQL.

Once you've met these requirements, you may go on to proceed and interact with an API in Laravel:
Now you are good to go!

Steps By Step Process: Interact And Consume an API using Laravel

To interact and consume an API using Laravel, there are two steps which I will show you below:
Two Steps to Consume An API**

  1. The first step is to consume a free API, using the routes/web.php to interact and consume the API. Below are Steps to achieve that.

Step 1: Install Laravel

  • Open your terminal and run the following command to create a new Laravel project:
  • composer create-project --prefer-dist laravel/laravel my-API-project
  • Change to the project directory:
  • cd my-api-project

Step 2: Get your API.
For the Sake of this project, we’ll be using Free API Which I got from Free API *****so you can get yours from there or any free API site. The API we are using is a Random Joke API.*
Step 3: Visit the web.php

  • Visit your routes/web.php in the project you just created:
  • Create a view using the Route::get() to interact and consume the API. We will be using the

welcome page to view the outcome of our API.
Below is the code snippet that you will code in your **routes/web.php**

    <?php
    use Illuminate\Support\Facades\Route;
    use Illuminate\Support\Facades\Http;

    Route::get('/', function(){
      $response = Http::get('https://official-joke-api.appspot.com/random_joke');
      $data = $response->json();

       return view('welcome', 
        ["type" => $data['type']],
        ["setup"=> $data['setup']],
        );
    });
Enter fullscreen mode Exit fullscreen mode

In summary, this code defines a route that, when accessed, requests an API to fetch a random joke. It then renders a view called "welcome" and passes the retrieved joke data to the idea for display or further processing. Note an API returns Extensible Markup Language (XML) OR JavaScript Object Notation(JSON).
Step4: Display The API In Your View
Now to view this API, my view is **welcome.blade.php** We will echo the value of the API in an HTML tag it will display the resource of the API on the browser. Let’s have an example of what I’m saying without wasting much of your time.
In your **views/welcome.blade.php** Below is the following code snippet to output what we wrote previously in the **routes/web.php** file. We used the **{{ }}** syntax to output the value of the variable in the generated HTML.

    <!DOCTYPE html>
    <html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">

            <title>API</title>

            <!-- Fonts -->
            <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

        </head>
          <body class="antialiased">

            <div class="container my-3">
              <div class="row justify-content-center">
                <div class="col-lg-6">
                  <div class="card shadow" style="width: 18rem;">
                    <div class="card-body">
                      <h3 class="fw-bold text-uppercase">{{ $type }}</h3>
                      <p class="card-text lead text-muted">{{ $setup }}</p>
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
          <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
        </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

Note: in the above code snippet we used Bootstrap 5 to have a better view, whenever you refresh the page in the browser the output will change. Below is how what we’ve done looks like.

An Output Of The entire code snippet

  1. The Second way is to consume an API with a key using the **app\Http\controllers\** to interact and consume the API. Below are Steps to achieve this.

First, visit the **routes/web.php**


  • Create a route that will take you to your desired controller.

Once you visit the web.php file you’ll write a line of code that’s the route that will be interacting with the Controller and API at the same time.
Below is the code snippet that you will code in your **routes/web.php**

    <?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\ConsumeController;

    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider and all of them will
    | be assigned to the "web" middleware group. Make something great!
    |
    */

    Route::get('/consume', [ConsumeController::class,'index']);
Enter fullscreen mode Exit fullscreen mode

The Code Above code snippet was named in my way, so you are free to use your naming conventions.
To make your Controller, you’ll write:

php artisan make:controller ConsumeController
Enter fullscreen mode Exit fullscreen mode

Then visit the **app\http\controllers\ConsumeController** on your folder directory, then you’ll see a file named **ConsumeController.php** Open the file you’ll see a code snippet like this.

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    class ConsumeController extends Controller
    {
      //
    }
Enter fullscreen mode Exit fullscreen mode

So because we’re going to be interacting with the API In this Controller what we need to do is to add a little code snippet above. The code snippet we’ll add above is the code, that will allow us to use the Http class from the Illuminate\Support\Facades namespace in your code.
Below is the code snippet to place above, before your class controller name.

    <?php
    use Illuminate\Support\Facades\Http;

So far here’s how your code will look like

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Http;
    class ConsumeController extends Controller
    {
      //
    }
Enter fullscreen mode Exit fullscreen mode

Secondly, you’ll create a function that will house all the API interactions. In this case, we will use the **index** naming convention for the naming of our process.

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Http;
    class ConsumeController extends Controller
    {
      public function index(){
         //   
      }
    }
Enter fullscreen mode Exit fullscreen mode

Now, the next thing to do is to get the API and API Keys and store them in a variable.
The name of our variable is **$apiKey** and **$apiUrl** Below is how to store the API in a variable.

    $apiKey = 'test_tf5WlMc5yVwKWk6dsQoeS4Qmz9mCkk8rZVnzCjjZ';
    $apiUrl = 'https://api.nettoolkit.com/v1/account/test-api-keys';
Enter fullscreen mode Exit fullscreen mode

The main purpose of storing your API in a variable is so you’ll be able to call the severally.
We’re going to get the HTTP of the API, what this does is that it enables you to link to the specified API and apiKey from your laravel project.
Below is an example of what I explained not too long ago!

    $response = Http::get($apiUrl, [
        'api_key' => $apiKey,
        // Add other parameters as needed
    ]);
Enter fullscreen mode Exit fullscreen mode

We saved the **HTTP** class in a variable called **$reponse** so we want to get the variable where our API is stored.
After getting it, we’ll do something like this!

$data = $reponse->json();
Enter fullscreen mode Exit fullscreen mode

This implies Structured data from an HTTP **$response** is assigned to the variable **$data** in this code, and the JSON format is translated and processed into a useful object or array for further manipulation and processing.
Then we redirect to where we want the API to display, in our case the ***`view/consume.blade.php to redirect to this page by using the return keyword*` below is an example.

return view('consume', ['data' => $data]);
Enter fullscreen mode Exit fullscreen mode

All that we’ve discussed in this section is just the entire controller, Decided to break it bit by bit.
Below is the code snippet.

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Http;
    class ContentController extends Controller
    {
        public function index() {
            $apiKey = 'test_tf5WlMc5yVwKWk6dsQoeS4Qmz9mCkk8rZVnzCjjZ';
            $apiUrl = 'https://api.nettoolkit.com/v1/account/test-api-keys';
            $response = Http::get($apiUrl, [
                'api_key' => $apiKey,
                // Add other parameters as needed
            ]);
            $data = $response->json();
            return view('consume', ['data' => $data]);
        }
    }
Enter fullscreen mode Exit fullscreen mode

After running this code, you’ll go to the view and look for the **consume.blade.php** inside it add the code snippet below to be able to view something in your browser.

    <h1>API Data:</h1>
    <pre>
        {{ json_encode($data, JSON_PRETTY_PRINT) }}
    </pre>
Enter fullscreen mode Exit fullscreen mode

After accomplishing the above task, refresh the page you’ll see the below content right on your screen.

The Output of The API From ConsumeController

We’ll talk more about API’s seat tight.

FAQ

What is Laravel API?
when we speak approximately Laravel API, we talk roughly about the API (software Programming Interface) improvement gear that the Laravel framework gives. a set of routes and strategies that permit interaction among outside programs and Laravel software is referred to as an API inside the context of Laravel.
What is RESTFUL API?
The architectural layout method called a RESTful API (Representational state switch API) is used to create networked programs. it's a method for creating web offerings that follow particular suggestions and boundaries resulting in web offerings that might be scalable, stateless, and simple to apply. Assets, which are things or entities the API can access, are the foundation of RESTful APIs.
RESTful APIs are popular because they are smooth to apply, scalable, and adaptable to many clients. They now function as the de facto enterprise general for creating net offerings, making an allowance for compatibility throughout diverse systems and operating systems.
What's the difference between JSON and XML?
even though XML and JSON are both commonly used facts transfer codecs, they range in phrases of syntax and functionality. JSON is a JavaScript item notation XML is an eXtensible Markup Language.
be aware: there are masses of variations, however, we’ll say few of them.
Subsequent are the principle variations between JSON and XML:**
1. clarity: JSON has a clean and recognizable shape just like JavaScript items, so it tends to be less complicated for human beings to recognize. due to its tag-based structure, XML can be more verbose and complex once in a while, making it tougher to read.

  1. statistics types:** handiest a small wide variety of statistics kinds, which include strings, numbers, booleans, arrays, objects, and null values, are supported through JSON. By way of default, XML translates all information as text and necessitates explicit type definitions.

Conclusion

Finally, We have come to the end of this Tutorial. Hope you were able to grab tons of value from it. Briefly, we have seen how to set up our laravel project and interact with API.
Note! Laravel provides a powerful framework for creating and interacting with APIs, offering developers a seamless and efficient way to build robust web applications.
With its comprehensive set of features and intuitive syntax, Laravel simplifies the process of designing, implementing, and managing APIs. Using Laravel, developers can effortlessly create API routes, define controllers, and handle HTTP requests and responses.
The framework's built-in authentication and authorization mechanisms ensure secure access to API endpoints, granting developers fine-grained control over user permissions.
Till next time, bye.

About The Author

Full-stack Laravel developer Emmanuel Okolie has 2+ years of experience in software development. He has developed full-fledged skills by combining software development, writing, and instructing others in what he does.
His stacks include ReactJ, Laravel, PHP, JavaScript, and other languages and frameworks.
He creates websites for clients as a freelancer and writes technical guides to show people how to do what he does.
If given the chance, Emmanuel Okolie would enjoy speaking with you. Please go to and follow him on his website, Facebook, Github, LinkedIn, and Twitter.

Top comments (0)