How to Call an External API Using Laravel

How to Call an External API Using Laravel (Tutorial)

In this tutorial, we’ll create a How to Call an External API Using Laravel . We’ll also implement buttons that trigger delete and update calls to the external API. Calling external APIs allow us to integrate with any third parties that exposes their functionality accordingly. You Can Learn How to Use Global Scope in Laravel

Note the data will be fetched externally but the updates and deletes will be simulated since the test API (jsonplaceholder.typicode.com) we’re using is read-only.

How to Call an External API Using Laravel

We will be using the Laravel built-in Http facade to send the API calls. While you could also use Guzzle to do this, using the Http facade is the recommended way to go about it. Using the Http facade offers a concise syntax that is in line with Laravel and adds more features like mocking HTTP responses for automated testing.

Let’s get started! How to Call an External API Using Laravel

Step 1: Set Up Your Laravel Project

Create a new Laravel project or use an existing one:

composer create-project  laravel/laravel blog-cms
cd blog-cms

Step 2: Create Controller

Create a controller by running:

php artisan make:controller PostController

Step 3: Add Controller Code

Now let’s add code to the PostController to implement methods to show, update, and delete posts by triggering calls to the external posts API:

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class PostController extends Controller
{
    public function index()
    {
        $response = Http::get('https://jsonplaceholder.typicode.com/posts');
        $posts = $response->json();

        return view('posts.index', ['posts' => $posts]);
    }

    public function edit($id)
    {
        $response = Http::get('https://jsonplaceholder.typicode.com/posts/' . $id);
        $post = $response->json();

        return view('posts.edit', ['post' => $post]);
    }

    public function update(Request $request, $id)
    {
        // Simulates update logic for a real application (not supported by this API)
        $response = Http::put('https://jsonplaceholder.typicode.com/posts/' . $id, [
            'title' => $request->input('title'),
            'body' => $request->input('body'),
        ]);

        // Simulated response for successful or failed update
        if ($response->successful()) {
            return redirect()->route('posts.index')->with('success', 'Post updated successfully!');
        } else {
            return redirect()->route('posts.index')->with('error', 'Failed to update post. Please try again.');
        }
    }

    public function destroy($id)
    {
        // Simulates deletion logic for a real application (not supported by this API)
        $response = Http::delete('https://jsonplaceholder.typicode.com/posts/' . $id);

        // Simulated response for successful or failed deletion
        if ($response->successful()) {
            return redirect()->route('posts.index')->with('success', 'Post deleted successfully!');
        } else {
            return redirect()->route('posts.index')->with('error', 'Failed to delete post. Please try again.');
        }
    }
}

Step 4: Define Routes

Define routes for post actions in routes/web.php as follows:

routes/web.php

use App\Http\Controllers\PostController;

Route::get('/', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{id}/edit', [PostController::class, 'edit'])->name('posts.edit');
Route::put('/posts/{id}', [PostController::class, 'update'])->name('posts.update');
Route::delete('/posts/{id}', [PostController::class, 'destroy'])->name('posts.destroy');

Step 5: Create a Base Layout

Let’s use a simple layout that is based on bootstrap 5 that can show any content along with any success or error message that may occur. Create a file resources/views/layouts/app.blade.php and add:

resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Other meta tags -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Other CSS -->
</head>
<body>

    <div class="container mt-4">

    <!-- Display success or error messages -->
    @if (session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    @if (session('error'))
        <div class="alert alert-danger">
            {{ session('error') }}
        </div>
    @endif

    @yield('content')

    </div>
</body>
</html>

Step 6: Create a View to Show Posts From API

Now let’s create the Blade view which displays the list of posts. Create a file at resources/views/posts/index.blade.php and add the following code:

resources/views/posts/index.blade.php

@extends('layouts.app')

@section('content')
    <div class="container mt-4">
        <h1>Posts</h1>
        <div class="table-responsive mt-3">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>Title</th>
                    <th>Body</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                @foreach($posts as $post)
                    <tr>
                        <td>{{ $post['title'] }}</td>
                        <td>{{ $post['body'] }}</td>
                        <td>
                            <div class="d-flex">
                                <a href="{{ route('posts.edit', $post['id']) }}" class="btn btn-sm btn-primary me-2">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <form action="{{ route('posts.destroy', $post['id']) }}" method="POST">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-sm btn-danger">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>
    </div>
@endsection

Step 7: Create Blade View for Edit Post From API

Create a Blade view for the post edit form in resources/views/posts/edit.blade.php. Include the form with populated data, the correct action/route, and @csrf:

resources/views/edit.blade.php

@extends('layouts.app')

@section('content')
    <div class="container mt-4">
        <h1>Edit Post</h1>
        <form action="{{ route('posts.update', $post['id']) }}" method="POST">
            @csrf
            @method('PUT')
            <div class="mb-3">
                <label for="title" class="form-label">Title</label>
                <input type="text" class="form-control" id="title" name="title" value="{{ $post['title'] }}">
            </div>
            <div class="mb-3">
                <label for="body" class="form-label">Body</label>
                <textarea class="form-control" id="body" name="body">{{ $post['body'] }}</textarea>
            </div>
            <button type="submit" class="btn btn-primary">Update</button>
        </form>
    </div>
@endsection

Step 8: Test the Application

Run your Laravel server using php artisan serve and navigate to http://localhost:8000 in your browser. You’ll have a paginated list of posts with functional delete and edit buttons, and an edit form ready for updates.

Note: The buttons will work to show edit form and trigger updates as well as deletes calls to the external API. However, the data in the API will not actually change since it is a public read-only API made for testing purposes.

Good job! You’ve successfully created a Laravel application that fetches and displays posts from an external API. You’ve also added buttons to delete posts and update by sending the respective API calls from your controller. I’ve also covered some basic error handling that redirects with either a success or an error message whichever applies. You Can Learn How to Upload and Download Files Using a Laravel API

While the placeholder API I showed here is read-only and the edits and deletes have no effect on the data, the principle is the same for a real API.

This Post Has 151 Comments

  1. На этом сайте можно ознакомиться с информацией о телешоу “Однажды в сказке”, развитии событий и главных персонажах. https://odnazhdy-v-skazke-online.ru/ Здесь представлены интересные материалы о производстве шоу, актерах и фактах из-за кулис.

  2. На данном сайте можно найти информацией о сериале “Однажды в сказке”, развитии событий и главных персонажах. тутhttps://odnazhdy-v-skazke-online.ru/ Здесь размещены интересные материалы о производстве шоу, актерах и фактах из-за кулис.

  3. 1win-casino-ng.com

    This site, you will find information about 1Win casino in Nigeria.
    It covers key features, such as the popular online game Aviator.
    1win casino
    You can also explore betting options.
    Take advantage of a seamless gaming experience!

  4. WilliamDon

    Сайт предлагает программное обеспечение для видеонаблюдения, которое позволяет создавать современные системы видеонаблюдения на базе IP-камер. Программа поддерживает все типы устройств с протоколом RTSP, что делает её универсальным инструментом для различных задач. Платформа включает VMS (систему управления видео) и CMS (систему централизованного мониторинга), позволяя записывать, просматривать и анализировать данные с камер видеонаблюдения. Ключевыми функциями программы являются распознавание лиц, распознавание номеров автомобилей и детекция движения, что делает её мощным инструментом для обеспечения безопасности. Программное обеспечение также поддерживает гибридное хранение данных, сочетающее облачные и локальные решения, что обеспечивает надежность и удобство доступа к информации. Встроенная видеоаналитика на основе искусственного интеллекта предоставляет расширенные возможности для мониторинга и анализа видео в реальном времени.

  5. RobertFaics

    На этом сайте у вас есть возможность приобрести виртуальные телефонные номера различных операторов. Они могут использоваться для регистрации профилей в разных сервисах и приложениях.
    В каталоге представлены как постоянные, так и одноразовые номера, что можно использовать для получения SMS. Это простое решение для тех, кто не хочет указывать личный номер в сети.
    турецкий номер телефона
    Процесс покупки очень простой: выбираете необходимый номер, оплачиваете, и он будет готов к использованию. Попробуйте сервис прямо сейчас!

  6. RobertFaics

    На данном сайте у вас есть возможность приобрести виртуальные мобильные номера различных операторов. Они подходят для подтверждения профилей в различных сервисах и приложениях.
    В ассортименте представлены как постоянные, так и временные номера, которые можно использовать чтобы принять SMS. Это удобное решение для тех, кто не желает указывать личный номер в интернете.
    номер телефона казахстан
    Оформление заказа очень удобный: выбираете подходящий номер, вносите оплату, и он сразу будет доступен. Попробуйте сервис уже сегодня!

  7. MatthewDit

    Эта компания помогает накрутить видеопросмотры и аудиторию в Twitch. Благодаря нашим услугам ваш стрим получит больше охвата и заинтересует новых зрителей. Накрутка зрителей на Твич с чатом Мы гарантируем реальные просмотры и активных пользователей, что улучшит статистику трансляции. Быстрая работа и выгодные тарифы позволяют развивать канал без лишних затрат. Удобное оформление заказа не требует сложных действий. Запустите раскрутку уже прямо сейчас и выведите свой Twitch-канал в топ!

  8. FrankIdepe

    Центр ментального здоровья — это место, где каждый может получить поддержку и профессиональную консультацию.
    Специалисты помогают разными запросами, включая повышенную тревожность, эмоциональное выгорание и депрессивные состояния.
    ww17.oldmountainbikes.com
    В центре применяются современные методы лечения, направленные на улучшение эмоционального баланса.
    Здесь организована безопасная атмосфера для доверительного диалога. Цель центра — помочь каждого клиента на пути к психологическому здоровью.

  9. BenitoFap

    Современная частная клиника обеспечивает высококачественные медицинские услуги для всей семьи.
    Мы гарантируем индивидуальный подход всестороннюю диагностику.
    Наши врачи — это лучшие специалисты в своей области, использующие передовые методики.
    Мы предлагаем все виды диагностики и лечения, в числе которых медицинские услуги по восстановлению здоровья.
    Забота о вашем здоровье — наши главные приоритеты.
    Обратитесь к нам, и восстановите ваше здоровье с нами.
    lintense.com

  10. Jamesaniff

    Clothing trends in next year will feature a blend of contemporary styles and classic touches. Bold shades and unique color schemes will dominate. Sustainable materials will be a major focus, with brands offering a wider range of organic fabrics. Relaxed-fit silhouettes and structured ensembles will stay relevant. Futuristic features, such as interactive clothing, will be incorporated into mainstream fashion.
    http://forum.pinoo.com.tr/viewtopic.php?pid=2681189#p268118988

  11. I all the time used to read article in news papers but now as I am a user of internet therefore from now
    I am using net for articles, thanks to web.

  12. Jamessmoow

    This online pharmacy provides an extensive variety of pharmaceuticals for budget-friendly costs.
    You can find various remedies for all health requirements.
    We strive to maintain trusted brands while saving you money.
    Fast and reliable shipping provides that your purchase is delivered promptly.
    Experience the convenience of shopping online on our platform.
    https://aengus.asta.tu-dortmund.de/lists/hyperkitty/list/psa@asta.tu-dortmund.de/thread/HIYLU2LKLQZHEN2IJQR6AFTHYSLCPBIL/

  13. Harryreoni

    На этом сайте вы можете найти самые актуальные события из автомобильной индустрии.
    Мы обновляем контент регулярно, чтобы держать вас в курсе всех важных событий.
    Новости авто охватывают разные стороны автомобильной жизни, включая новинки, технологии и события.
    mcomp.org
    Мы постоянно следим за всеми новыми трендами, чтобы предоставить вам самую свежую информацию.
    Если вы интересуетесь автомобилями, этот сайт станет вашим надежным источником.

Leave a Reply