今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

Build a versioned Laravel API with auto-generated OpenAPI docs in 10 minutes

Denis Skripchenko 2026年06月11日 14:12 5 次阅读 来源:Dev.to

TL;DR — We'll install dskripchenko/laravel-api , write one controller, and end up with a versioned API ( /api/v1/... ) and interactive OpenAPI 3.0 docs at /api/doc — generated from the docblock you'd write anyway. Then we'll ship a v2 without copy-pasting a single controller. The problem Two things rot in every growing Laravel API: Versioning. v1 ships, then v2 needs to change three endpoints but keep the other twenty. You either copy-paste a V2 folder (and now bugfixes live in two places) or bolt if ($version === 2) branches into your controllers. Docs. The OpenAPI spec drifts from the code the moment you merge. Annotation libraries ( #[OA\Get(...)] , giant YAML files) ask you to describe your API twice — once in code, once in attributes. This package's bet: your controller already describes itself . The method name, the request fields, the response shape — write them once, as a normal PHPDoc, and let the package derive routes and docs from it. Versioning becomes plain PHP inheritance. Let's build it. What we'll build A tiny tasks API: POST /api/v1/task/list — list tasks POST /api/v1/task/create — create one interactive docs at GET /api/doc (raw spec per version at /api/doc/{version} ) then a v2 that adds an endpoint without touching v1 Total: ~4 small files. Step 0 — Install composer require dskripchenko/laravel-api Publish the config (optional, but handy to see the knobs): php artisan vendor:publish --tag = laravel-api-config // config/laravel-api.php return [ 'prefix' => 'api' , // → /api/... 'uri_pattern' => '{version}/{controller}/{action}' , 'available_methods' => [ 'get' , 'post' , 'put' , 'patch' , 'delete' ], 'openapi_path' => 'public/openapi' , 'doc_middleware' => [], // lock down /api/doc here ]; Step 1 — Write a controller Nothing exotic — it extends the package's ApiController , which gives you response helpers ( success() , error() , validationError() , created() , noContent() , notFound() ). The docblock is the documentation : <?php namespace App\Api

本文内容来源于互联网,版权归原作者所有
查看原文