在 Laravel 12 中集成 OpenAPI/Swagger 可以按照以下步骤操作,使用最流行的 darkaonline/l5-swagger
扩展包:
1. 安装依赖包
composer require darkaonline/l5-swagger
2. 发布配置文件
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
3. 配置环境变量 (.env)
L5_SWAGGER_CONST_HOST=http://localhost:8000/api
# 或者使用动态配置:
# L5_SWAGGER_CONST_HOST=yourdomain.test/api
4. 基本配置 (config/l5-swagger.php)
return [
'api' => [
'title' => 'Laravel API',
'version' => '1.0.0',
'description' => 'Swagger UI for Laravel API',
],
'routes' => [
'api' => 'api/documentation', // 文档访问路径
'docs' => 'docs', // JSON 定义路径
],
'generate_always' => env('L5_SWAGGER_GENERATE_ALWAYS', true),
];
5. 添加控制器注解示例
在控制器方法中使用注解定义 API:
use OpenApi\Annotations as OA;
/**
* @OA\Info(
* title="用户管理 API",
* version="1.0.0",
* description="用户管理接口文档"
* )
*/
class UserController extends Controller
{
/**
* 获取用户列表
*
* @OA\Get(
* path="/api/users",
* tags={"Users"},
* summary="获取用户列表",
* description="返回分页用户列表",
* @OA\Parameter(
* name="page",
* in="query",
* description="页码",
* required=false,
* @OA\Schema(type="integer")
* ),
* @OA\Response(
* response=200,
* description="成功响应",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="data", type="array", @OA\Items(ref="#/components/schemas/User")),
* @OA\Property(property="meta", ref="#/components/schemas/Pagination")
* )
* )
* )
*/
public function index()
{
// 控制器代码...
}
}
6. 定义数据模型结构
在模型类中添加注解:
/**
* @OA\Schema(
* schema="User",
* required={"name", "email"},
* description="用户模型",
* @OA\Property(property="id", type="integer", format="int64", example=1),
* @OA\Property(property="name", type="string", example="John Doe"),
* @OA\Property(property="email", type="string", format="email", example="user@example.com"),
* @OA\Property(property="created_at", type="string", format="date-time"),
* )
*
* @OA\Schema(
* schema="Pagination",
* @OA\Property(property="current_page", type="integer"),
* @OA\Property(property="per_page", type="integer"),
* @OA\Property(property="total", type="integer"),
* )
*/
class User extends Model
{
// 模型代码...
}
7. 生成文档
php artisan l5-swagger:generate
8. 访问文档
启动服务后访问:
http://localhost:8000/api/documentation
高级配置技巧
1. 添加认证支持
/**
* @OA\SecurityScheme(
* securityScheme="bearerAuth",
* type="http",
* scheme="bearer",
* bearerFormat="JWT"
* )
*/
在需要认证的接口添加:
/**
* @OA\Get(
* security={{"bearerAuth":{}}},
* ...
* )
*/
2. 错误响应统一格式
在控制器基类中定义:
/**
* @OA\Schema(
* schema="ErrorResponse",
* @OA\Property(property="error", type="string", example="Unauthorized"),
* @OA\Property(property="message", type="string", example="Token expired"),
* @OA\Property(property="code", type="integer", example=401)
* )
*/
3. 自动生成命令 (可选)
在 composer.json
中添加:
"scripts": {
"swagger": "php artisan l5-swagger:generate"
}
最佳实践建议
- 文档版本控制:将 Swagger 配置与 API 版本绑定
- 接口分组:使用
tags
对接口分类管理 - 响应示例:添加实际响应示例提高文档可用性
- 参数复用:使用
components
复用公共参数定义 - CI/CD 集成:在部署流程中加入文档生成步骤
常见问题解决
Q: 文档不更新?
A: 确保配置 'generate_always' => true
或手动运行生成命令
Q: 注解无效?
A: 检查 PHP 注释格式是否正确,确保使用 /** ... */
格式
Q: 生产环境隐藏文档
// config/l5-swagger.php
'generate_always' => env('APP_ENV') !== 'production',
这样就可以在 Laravel 12 项目中拥有完善的 OpenAPI/Swagger 文档系统,支持交互式测试和自动化文档生成。