Symfony7.1自定义控制器用API Platform4.0生成OpenAPI遇阻求助
问题解决步骤
你的问题核心在于:添加_api_resource_class后API Platform接管了请求处理,但你返回的是JsonResponse而非BlocDto实例,且BlocDto未被标记为API资源,导致无法生成OpenAPI文档并触发异常。按以下步骤修改即可解决:
1. 将BlocDto标记为API资源
API Platform需要明确识别DTO作为可文档化的资源,给BlocDto添加ApiResource注解并配置对应操作:
<?php namespace App\DTO; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\Get; use Symfony\Component\Validator\Constraints as Assert; #[ApiResource( operations: [ new Get( uriTemplate: '/blocs/{id}', name: 'getBloc' ) ] )] class BlocDto { public function __construct( #[Assert\NotBlank] public string $id, #[Assert\NotBlank] public string $name, public string $description, public string $blocLowRes, public string $blocMedRes, public string $blocHighRes) { } }
2. 修改控制器返回DTO实例
去掉JsonResponse,直接返回BlocDto实例,让API Platform自动处理序列化和文档生成:
<?php namespace App\Controller; use App\DTO\BlocDto; use App\Repository\BlocRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Attribute\Route; class BlocsController extends AbstractController { private $blocRepository; public function __construct(BlocRepository $blocRepository) { $this->blocRepository = $blocRepository; } #[Route( path: '/blocs/{id}', name: 'get-bloc', methods: ['GET', 'HEAD'], defaults: [ '_api_resource_class' => BlocDto::class, '_api_operation_name' => 'getBloc' ] )] public function getBloc($id): BlocDto { $bloc = $this->blocRepository->find($id); return new BlocDto( $bloc->getId(), $bloc->getName(), $bloc->getDescription(), $bloc->getBlocLowRes(), $bloc->getBlocMedRes(), $bloc->getBlocHighRes() ); } }
3. 优化API Platform配置(可选)
在api_platform.yaml中明确指定默认格式为JSON,确保响应符合要求:
api_platform: title: Boulder Api version: 1.0.0 use_symfony_listeners: true defaults: stateless: true cache_headers: vary: ['Content-Type', 'Authorization', 'Origin'] formats: json: ['application/json']
验证效果
修改完成后:
- 访问
/blocs/{id}会返回符合BlocDto结构的JSON响应 - 访问
/api/docs可以看到该端点的OpenAPI描述,包含所有属性的定义和验证约束
内容的提问来源于stack exchange,提问作者TheCell
相关产品推荐
相关产品推荐

