search
HomeBackend DevelopmentPHP TutorialHow to Create REST API Using Laravel

How to Create REST API Using Laravel

Hello! In this tutorial, we’ll be building a complete REST API in Laravel to manage tasks. I'll guide you through the basic steps, from setting up the project to creating automated tests.

Step 1: Project Setup

Create a new Laravel project:

composer create-project laravel/laravel task-api
cd task-api
code .

Configure the database:
In the .env file, set your database configurations:

DB_DATABASE=task_api
DB_USERNAME=your_username
DB_PASSWORD=your_password

Generate the tasks table:
Run the command to create a new migration for the tasks table:

php artisan make:migration create_tasks_table --create=tasks

In the migration file (database/migrations/xxxx_xx_xx_create_tasks_table.php), define the table structure:

<?php use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description')->nullable();
            $table->boolean('completed')->default(false);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('tasks');
    }
};

Run the migration to create the table:

php artisan migrate

Step 2: Creating the Model and Controller

Create the model and controller for the task:

php artisan make:model Task
php artisan make:controller TaskController --api

Define the Task model (app/Models/Task.php):

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'description', 'completed'];
}

Step 3: Defining API Routes

In the routes/api.php file, add the routes for the TaskController:

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

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

Step 4: Implementing CRUD in TaskController

In the TaskController, we’ll implement the basic CRUD methods.

<?php namespace App\Http\Controllers;

use App\Models\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    public function index()
    {
        $tasks = Task::all();
        return response()->json($tasks, 200);
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string'
        ]);
        $task = Task::create($request->all());
        return response()->json($task, 201);
    }

    public function show(Task $task)
    {
        return response()->json($task, 200);
    }

    public function update(Request $request, Task $task)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'completed' => 'boolean'
        ]);
        $task->update($request->all());
        return response()->json($task, 201);
    }

    public function destroy(Task $task)
    {
        $task->delete();
        return response()->json(null, 204);
    }
}

Step 5: Testing Endpoints (VS Code)

Now we’ll test each endpoint manually, using a VS Code extension called REST Client (https://marketplace.visualstudio.com/items?itemName=humao.rest-client). If you prefer, you can also use Insomnia or Postman!

After installing the extension, create an .http file in your project folder with the following content:

### Create New Task
POST http://127.0.0.1:8000/api/tasks HTTP/1.1
content-type: application/json
Accept: application/json

{
    "title": "Study Laravel"
}

### Show Tasks
GET http://127.0.0.1:8000/api/tasks HTTP/1.1
content-type: application/json
Accept: application/json

### Show Task
GET http://127.0.0.1:8000/api/tasks/1 HTTP/1.1
content-type: application/json
Accept: application/json

### Update Task
PUT http://127.0.0.1:8000/api/tasks/1 HTTP/1.1
content-type: application/json
Accept: application/json

{
    "title": "Study Laravel and Docker",
    "description": "We are studying!",
    "completed": false
}

### Delete Task
DELETE http://127.0.0.1:8000/api/tasks/1 HTTP/1.1
content-type: application/json
Accept: application/json

This file lets you send requests directly from VS Code using the REST Client extension, making it easy to test each route in your API.

Step 6: Testing the API

Next, let’s create tests to ensure each route works as expected.

First, create a factory for the Task model:

php artisan make:factory TaskFactory
<?php namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class TaskFactory extends Factory
{
    public function definition(): array
    {
        return [
            'title' => fake()->sentence(),
            'description' => fake()->paragraph(),
            'completed' => false,
        ];
    }
}

PHPUnit Configuration:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory>tests/Feature</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>app</directory>
        </include>
    </source>
    <php>
        <env name="APP_ENV" value="testing"></env>
        <env name="BCRYPT_ROUNDS" value="4"></env>
        <env name="CACHE_DRIVER" value="array"></env>
        <env name="DB_CONNECTION" value="sqlite"></env>
        <env name="DB_DATABASE" value=":memory:"></env>
        <env name="MAIL_MAILER" value="array"></env>
        <env name="PULSE_ENABLED" value="false"></env>
        <env name="QUEUE_CONNECTION" value="sync"></env>
        <env name="SESSION_DRIVER" value="array"></env>
        <env name="TELESCOPE_ENABLED" value="false"></env>
    </php>
</phpunit>

Create an integration test:

php artisan make:test TaskApiTest

In the tests/Feature/TaskApiTest.php file, implement the tests:

<?php namespace Tests\Feature;

use App\Models\Task;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TaskApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_create_task(): void
    {
        $response = $this->postJson('/api/tasks', [
            'title' => 'New Task',
            'description' => 'Task Description',
            'completed' => false,
        ]);

        $response->assertStatus(201);

        $response->assertJson([
            'title' => 'New Task',
            'description' => 'Task Description',
            'completed' => false,
        ]);
    }

    public function test_can_list_tasks()
    {
        Task::factory()->count(3)->create();

        $response = $this->getJson('/api/tasks');

        $response->assertStatus(200);

        $response->assertJsonCount(3);
    }

    public function test_can_show_task()
    {
        $task = Task::factory()->create();

        $response = $this->getJson("/api/tasks/{$task->id}");

        $response->assertStatus(200);

        $response->assertJson([
            'title' => $task->title,
            'description' => $task->description,
            'completed' => false,
        ]);
    }

    public function test_can_update_task()
    {
        $task = Task::factory()->create();

        $response = $this->putJson("/api/tasks/{$task->id}", [
            'title' => 'Update Task',
            'description' => 'Update Description',
            'completed' => true,
        ]);

        $response->assertStatus(201);

        $response->assertJson([
            'title' => 'Update Task',
            'description' => 'Update Description',
            'completed' => true,
        ]);
    }

    public function test_can_delete_task()
    {
        $task = Task::factory()->create();

        $response = $this->deleteJson("/api/tasks/{$task->id}");

        $response->assertStatus(204);

        $this->assertDatabaseMissing('tasks', ['id' => $task->id]);
    }
}

Run the tests:

php artisan test

*Thank you! *

The above is the detailed content of How to Create REST API Using Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.