如何使用 Laravel 创建 REST API
您好!在本教程中,我们将在 laravel 中构建一个完整的 rest api 来管理任务。我将指导您完成从设置项目到创建自动化测试的基本步骤。
第 1 步:项目设置
创建一个新的 laravel 项目:
composer create-project laravel/laravel task-apicd task-apicode .
配置数据库:
在 .env 文件中,设置数据库配置:
db_database=task_apidb_username=your_usernamedb_password=your_password
生成任务表:
运行命令为任务表创建新的迁移:
php artisan make:migration create_tasks_table --create=tasks
在迁移文件(database/migrations/xxxx_xx_xx_create_tasks_table.php)中,定义表结构:
<?phpuse illuminatedatabasemigrationsmigration;use illuminatedatabaseschemalueprint;use illuminatesupportacadesschema;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 taskphp artisan make:controller taskcontroller --api
定义任务模型(app/models/task.php):
<?phpnamespace appmodels;use illuminatedatabaseeloquentactorieshasfactory;use illuminatedatabaseeloquentmodel;class task extends model{ use hasfactory; protected $fillable = ['title', 'description', 'completed'];}
第 3 步:定义 api 路由
在routes/api.php文件中,添加taskcontroller的路由:
<?phpuse apphttpcontrollers askcontroller;use illuminatesupportacadesoute;route::apiresource('tasks', taskcontroller::class);
第四步:在taskcontroller中实现crud
在taskcontroller中,我们将实现基本的crud方法。
<?phpnamespace apphttpcontrollers;use appmodels ask;use illuminatehttpequest;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 taskpost http://127.0.0.1:8000/api/tasks http/1.1content-type: application/jsonaccept: application/json{ "title": "study laravel"}### show tasksget http://127.0.0.1:8000/api/tasks http/1.1content-type: application/jsonaccept: application/json### show taskget http://127.0.0.1:8000/api/tasks/1 http/1.1content-type: application/jsonaccept: application/json### update taskput http://127.0.0.1:8000/api/tasks/1 http/1.1content-type: application/jsonaccept: application/json{ "title": "study laravel and docker", "description": "we are studying!", "completed": false}### delete taskdelete http://127.0.0.1:8000/api/tasks/1 http/1.1content-type: application/jsonaccept: application/json
此文件可让您使用 rest 客户端 扩展直接从 vs code 发送请求,从而轻松测试 api 中的每个路由。
第 6 步:测试 api
接下来,让我们创建测试以确保每条路线按预期工作。
首先,为任务模型创建一个工厂:
php artisan make:factory taskfactory
<?phpnamespace databaseactories;use illuminatedatabaseeloquentactoriesactory;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文件中,实现测试:
<?phpnamespace testseature;use appmodels ask;use illuminateoundation estingefreshdatabase;use tests estcase;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
*谢谢! *