如何使用 Laravel 创建 REST API
您好!在本教程中,我们将在 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><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 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的详细内容,更多请关注其它相关文章!