External API Call in Laravel with HTTP Client and Services

In this article, we will learn how to make external API calls with laravel’s HTTP client using the service. Service helps to keep the code organized, clean and readable.

Endpoint That Should Return JSON Data Array

We can use any API, but here we will be using reqres’s API for better understanding, as these are available online. Reqres provides REST API to developers so that they can test their backend or frontend features. To check out click on this link

Since most APIs are related to users, that’s why in this article we will be creating files with User word.

Create User Controller

In the first step, create a user controller, it can be created with the below command,

php artisan make:controller UserController

After execution of this command, the controller would be created inside the app/Http/Controllers directory.

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
class UserController extends Controller
{
   
}

Create User Service

In the second step, create a service folder in the following directory,

laravel-project/app/Services

In the app directory, all folders’ names are camel cases. Therefore services folder’s first letter should be capitalized. Create a user service file inside the services directory,

laravel-project/app/Services/UserService.php

<?php
 
namespace App\Services;
 
class UserService
{
 
}

While creating files, we need to keep in mind that the file’s name should be following the camel case naming convention.

HTTP Client is Part of Laravel’s Version 7, 8 and 9

Laravel introduced the HTTP client from version 7, so the below tutorial would be fit for laravel’s versions 7, 8, and 9.

In the next step, the HTTP facade needs to import into the user service. So add HTTP facade just before class as like following,

use Illuminate\Support\Facades\Http;

Fetch User List

In this step, we will be fetching a users list by calling the list users endpoint. It accepts the get method and has a parameter that is page.

Let’s create list() method inside the user service class,

public function list()
{
    $response = Http::get('https://reqres.in/api/users?page=1');
 
    return $response->json();
}

Here HTTP facade’s method get() makes requests to the endpoint and returns data in JSON format. Now let’s use this method in the user controller as a service. First import the user service inside the user controller, to do that put the use command before the class starts in UserController.php.

use App\Services\UserService;

Then create the getUsers() method, where this service needs to be injected, and access the list() method.

public function getUsers(UserService $userService)
{
    return $userService->list();
}

Here user service has been directly injected into the getUsers() method. Now all methods can be accessed through the $userService variable.

Create Route to Access Method In Browser

We will be making requests in the browser to fetch data from external API, for that, we need to make a route that would map to the getUsers() method.

Route::get('/get-users', [UserController::class, 'getUsers']);

In the above line, get-users is the URL segment or part of the URL that tells Laravel to call the getUsers() the method from UserController class.

After this, execute the following command in the terminal or git bash, it depends on what do you use?

php artisan serve

This command runs the Laravel application on the development server and returns an IP with a port that can be used in the browser. Usually, it returns the following IP,

http://127.0.0.1:8000/

Almost all is done, now we are going to see the result. All we need to do is run the following URL in the browser,

http://127.0.0.1:8000/get-users

The above URL returns a JSON data array after fetching from an external API. Following is an example,

{
   "page": 2,
   "per_page": 6,
   "total": 12,
   "total_pages": 2,
   "data": [
      {
         "id": 7,
         "email": "xyz@reqres.in",
         "first_name": "Muiz",
         "last_name": "Ali",
         "avatar": "https://example.com/img/image.jpg"
      }
   ],
   "support": {
      "url": "https://reqres.in/#support-heading",
      "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
   }
}

In last, I would like to share the source code.

Code from UserService.php

<?php
 
namespace App\Services;
 
use Illuminate\Support\Facades\Http;
 
class UserService
{
    public function list()
    {
        $response = Http::get('https://reqres.in/api/users?page=2');
 
        return $response->json();
    }
}

Code from UserController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Services\UserService;
 
class UserController extends Controller
{
    public function getUsers(UserService $userService)
    {
        return $userService->list();
    }
}

Code from Laravel’s route web.php

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
 
Route::get('/get-users', [UserController::class, 'getUsers']);