Symfony 与 OpenApi

实际后端项目需要编写接口文档,尤其在前后端分离的情况。有接口文档情况下,可以加快对接效率,但是如果文档编写不规范,或者没有随着代码逻辑的更新而更新,却会造成不必要的麻烦,降低开发效率和开发体验。目前Restful接口文档编写开源规范有 OpenApi,然后具体实现和工具则有 Swagger 。
框架组合
目前主要是使用Symfony 框架,考虑的是有着良好的编码规范以及成熟的生态环境。然后使用 NelmioApiDocBundle 赋予框架通过注解和属性生成接口文档的能力。
示例
使用 PHP 的 Attribute 特性来增加接口文档的描述
<?php
namespace App\Controller\Api;
use App\Model\Dto\UserDto;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use OpenApi\Attributes as OA;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;
class UserController extends AbstractController
{
#[Route('/api/users', name: 'app_api_users', methods: ['GET'])]
#[OA\Response(
response: 200,
description: 'Returns the list of an user',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: UserDto::class))
)
)]
#[OA\Parameter(
name: 'username',
description: 'username for query filter',
in: 'query',
schema: new OA\Schema(type: 'string')
)]
#[OA\Tag(name: 'users')]
#[Security(name: 'Bearer')]
public function list(UserDto $dto): Response
{
return new JsonResponse([
$dto
]);
}
}
参考
Publish on 2024-04-11,Update on 2025-02-10