How to Create an API using Laravel

How to Create an API using Laravel

Creating a Laravel Task Manager API

What is an API?

An Application Programming Interface (API) enables applications to access data and functionalities from external software. APIs are popular among developers as they save time and resources by allowing integration with existing systems instead of building everything from scratch.

When an application sends a request to an API, the API processes it and returns the appropriate response.

Introduction to Laravel

Laravel is a robust PHP framework for building interactive websites and APIs. It supports real-time communication, API authentication, and job queues. Laravel simplifies the development process by offering built-in tools and templates. This tutorial walks you through the process of building a Laravel Web API.

Tutorial Goal

To build a simple task manager API using Laravel.

Prerequisites

  • Basic knowledge of PHP

  • Installed Composer

  • Installed XAMPP (includes Apache and MySQL)

Step 1: Creating the Project

You can create a new Laravel project using:

laravel new taskmanager

Alternatively:

composer create-project --prefer-dist laravel/laravel taskmanager

Place your project in the xampp/htdocs directory and access it via:

localhost/taskmanager/public/

Step 2: Creating the Database

  • Launch phpMyAdmin in XAMPP.

  • Create a database named tasks.

  • Open the Laravel project in an IDE like Visual Studio Code.

  • Update the .env file to match your database credentials:

DB_DATABASE=tasks
DB_USERNAME=root
DB_PASSWORD=

Step 3: Migration

Generate a model, factory, and migration using:

php artisan make:model Task -mf

Edit the migration file in database/migrations/:

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('description');
    $table->timestamps();
});

Run the migration:

php artisan migrate

Step 4: Seeding Data

Create a factory:

php artisan make:factory TaskFactory

Edit the factory file:

public function definition() {
    return [
        'title' => $this->faker->word,
        'description' => $this->faker->text,
    ];
}

Create a seeder:

php artisan make:seeder TaskTableSeeder

Edit the seeder:

public function run() {
    Task::factory()->times(50)->create();
}

Run the seeder:

php artisan db:seed

Step 5: Controller

Create a controller:

php artisan make:controller TaskController --resource

Edit TaskController.php to handle CRUD:

A) Index

public function index() {
    return Task::orderBy('created_at', 'asc')->get();
}

B) Show

public function show($id) {
    return Task::findOrFail($id);
}

C) Store

public function store(Request $request) {
    $this->validate($request, [
        'title' => 'required',
        'description' => 'required',
    ]);

    $task = new Task;
    $task->title = $request->input('title');
    $task->description = $request->input('description');
    $task->save();

    return $task;
}

D) Update

public function update(Request $request, $id) {
    $this->validate($request, [
        'title' => 'required',
        'description' => 'required',
    ]);

    $task = Task::findOrFail($id);
    $task->title = $request->input('title');
    $task->description = $request->input('description');
    $task->save();

    return $task;
}

E) Destroy

public function destroy($id) {
    $task = Task::findOrFail($id);
    if ($task->delete()) {
        return 'deleted successfully';
    }
}

Step 6: Registering Routes

Edit routes/api.php:

use App\Http\Controllers\TaskController;

Route::resource('tasks', TaskController::class);

Check registered routes:

php artisan route:list

Step 7: Testing the API

Use Postman or any other REST client to test the API endpoints:

  • GET /api/tasks – List all tasks

  • GET /api/tasks/{id} – View a specific task

  • POST /api/tasks – Create a new task

  • PUT /api/tasks/{id} – Update a task

  • DELETE /api/tasks/{id} – Delete a task

Conclusion

Laravel simplifies the process of creating powerful and secure APIs. With its built-in resource routing and elegant syntax, developers can quickly set up RESTful APIs. Laravel also offers great support for debugging and error handling, making it a preferred choice for backend development.

    Soeng Souy

    Soeng Souy

    Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

    Post a Comment

    CAN FEEDBACK
    close