php中文网

如何使用 Laravel 创建 REST API

php中文网

您好!在本教程中,我们将在 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 illuminatedatabasemigrationsmigration;
use illuminatedatabaseschemablueprint;
use illuminatesupportfacadesschema;

return new class extends migration
{
    public function up(): void
    {
        schema::create('tasks', function (blueprint $table) {
            $table->id();
            $table-&gt;string('title');
            $table-&gt;text('description')-&gt;nullable();
            $table-&gt;boolean('completed')-&gt;default(false);
            $table-&gt;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 appmodels;

use illuminatedatabaseeloquentfactorieshasfactory;
use illuminatedatabaseeloquentmodel;

class task extends model
{
    use hasfactory;

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

第 3 步:定义 api 路由

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

<?php use apphttpcontrollerstaskcontroller;
use illuminatesupportfacadesroute;

route::apiresource('tasks', taskcontroller::class);

第四步:在taskcontroller中实现crud

在taskcontroller中,我们将实现基本的crud方法。

<?php namespace apphttpcontrollers;

use appmodelstask;
use illuminatehttprequest;

class taskcontroller extends controller
{
    public function index()
    {
        $tasks = task::all();
        return response()->json($tasks, 200);
    }

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

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

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

    public function destroy(task $task)
    {
        $task-&gt;delete();
        return response()-&gt;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 databasefactories;

use illuminatedatabaseeloquentfactoriesfactory;

class taskfactory extends factory
{
    public function definition(): array
    {
        return [
            'title' => fake()-&gt;sentence(),
            'description' =&gt; fake()-&gt;paragraph(),
            'completed' =&gt; 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><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>

创建集成测试:

php artisan make:test taskapitest

在tests/feature/taskapitest.php文件中,实现测试:

<?php namespace testsfeature;

use appmodelstask;
use illuminatefoundationtestingrefreshdatabase;
use teststestcase;

class taskapitest extends testcase
{
    use refreshdatabase;

    public function test_can_create_task(): void
    {
        $response = $this->postjson('/api/tasks', [
            'title' =&gt; 'new task',
            'description' =&gt; 'task description',
            'completed' =&gt; false,
        ]);

        $response-&gt;assertstatus(201);

        $response-&gt;assertjson([
            'title' =&gt; 'new task',
            'description' =&gt; 'task description',
            'completed' =&gt; false,
        ]);
    }

    public function test_can_list_tasks()
    {
        task::factory()-&gt;count(3)-&gt;create();

        $response = $this-&gt;getjson('/api/tasks');

        $response-&gt;assertstatus(200);

        $response-&gt;assertjsoncount(3);
    }

    public function test_can_show_task()
    {
        $task = task::factory()-&gt;create();

        $response = $this-&gt;getjson("/api/tasks/{$task-&gt;id}");

        $response-&gt;assertstatus(200);

        $response-&gt;assertjson([
            'title' =&gt; $task-&gt;title,
            'description' =&gt; $task-&gt;description,
            'completed' =&gt; false,
        ]);
    }

    public function test_can_update_task()
    {
        $task = task::factory()-&gt;create();

        $response = $this-&gt;putjson("/api/tasks/{$task-&gt;id}", [
            'title' =&gt; 'update task',
            'description' =&gt; 'update description',
            'completed' =&gt; true,
        ]);

        $response-&gt;assertstatus(201);

        $response-&gt;assertjson([
            'title' =&gt; 'update task',
            'description' =&gt; 'update description',
            'completed' =&gt; true,
        ]);
    }

    public function test_can_delete_task()
    {
        $task = task::factory()-&gt;create();

        $response = $this-&gt;deletejson("/api/tasks/{$task-&gt;id}");

        $response-&gt;assertstatus(204);

        $this-&gt;assertdatabasemissing('tasks', ['id' =&gt; $task-&gt;id]);
    }
}

运行测试

php artisan test

*谢谢! *

以上就是如何使用 Laravel 创建 REST API的详细内容,更多请关注php中文网其它相关文章!