如何使用 Laravel 创建 REST API

Patricia Arquette
发布: 2024-10-30 23:26:30
原创
891 人浏览过

How to Create REST API Using Laravel

您好!在本教程中,我们将在 Laravel 中构建一个完整的 REST API 来管理任务。我将指导您完成从设置项目到创建自动化测试的基本步骤。

第 1 步:项目设置

创建一个新的 Laravel 项目:

composer create-project laravel/laravel task-api
cd task-api
code .
登录后复制

配置数据库:
在 .env 文件中,设置数据库配置:

DB_DATABASE=task_api
DB_USERNAME=your_username
DB_PASSWORD=your_password
登录后复制

生成任务表:
运行命令为任务表创建新的迁移:

php artisan make:migration create_tasks_table --create=tasks
登录后复制

在迁移文件(database/migrations/xxxx_xx_xx_create_tasks_table.php)中,定义表结构:

<?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');
    }
};
登录后复制

运行迁移以创建表:

php artisan migrate
登录后复制

第 2 步:创建模型和控制器

为任务创建模型和控制器:

php artisan make:model Task
php artisan make:controller TaskController --api
登录后复制

定义任务模型(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'];
}
登录后复制

第 3 步:定义 API 路由

在routes/api.php文件中,添加TaskController的路由:

<?php

use App\Http\Controllers\TaskController;
use Illuminate\Support\Facades\Route;

Route::apiResource('tasks', TaskController::class);
登录后复制

第四步:在TaskController中实现CRUD

在TaskController中,我们将实现基本的CRUD方法。

<?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);
    }
}
登录后复制

步骤 5:测试端点(VS Code)

现在我们将使用名为 REST Client 的 VS Code 扩展手动测试每个端点 (https://marketplace.visualstudio.com/items?itemName=humao.rest-client)。如果您愿意,您还可以使用失眠邮递员

安装扩展程序后,在项目文件夹中创建一个包含以下内容的 .http 文件:

### 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
登录后复制

此文件可让您使用 REST 客户端 扩展直接从 VS Code 发送请求,从而轻松测试 API 中的每个路由。

第 6 步:测试 API

接下来,让我们创建测试以确保每条路线按预期工作。

首先,为任务模型创建一个工厂:

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 配置:

<?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 name="BCRYPT_ROUNDS" value="4" />
        <env name="CACHE_DRIVER" value="array" />
        <env name="DB_CONNECTION" value="sqlite" />
        <env name="DB_DATABASE" value=":memory:" />
        <env name="MAIL_MAILER" value="array" />
        <env name="PULSE_ENABLED" value="false" />
        <env name="QUEUE_CONNECTION" value="sync" />
        <env name="SESSION_DRIVER" value="array" />
        <env name="TELESCOPE_ENABLED" value="false" />
    </php>
</phpunit>
登录后复制

创建集成测试:

php artisan make:test TaskApiTest
登录后复制

在tests/Feature/TaskApiTest.php文件中,实现测试:

<?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]);
    }
}
登录后复制

运行测试

php artisan test
登录后复制

*谢谢! *

以上是如何使用 Laravel 创建 REST API的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板