You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 7下Nelmio API Doc无法正常生成接口文档问题

Nelmio API Doc无法加载@OA注解内容问题排查

问题描述

使用Nelmio API Doc生成Swagger接口文档时,浏览器可正常访问/api/doc路由,但文档仅显示注释块中的普通文本,所有@OA开头的注解定义的参数、请求体、响应等内容均无法加载。怀疑是否因使用注解(annotation)而非属性(attribute)导致问题。

待文档化的UserController代码

<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\RegisterType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use App\Utils\HelperFunctions;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use OpenApi\Annotations as OA;

#[Route('/api', name: "api_user_")]
class UserController extends AbstractController
{
    use HelperFunctions;
    public function __construct(
        private UserPasswordHasherInterface $passwordHasher,
        private EntityManagerInterface $entityManager
    ) {
    }


    /**
     * @OA\Post(
     *     path="/register",
     *     tags={"register"},
     *     summary="Register a new user",
     *     description="Register a new user",
     *     operationId="registerUser",
     *     @OA\RequestBody(
     *         required=true,
     *         description="User data",
     *         @OA\JsonContent(ref="#/components/schemas/User")
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="User registered successfully",
     *         @OA\JsonContent(ref="#/components/schemas/User")
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="Invalid data provided"
     *     )
     * )
     */
    #[Route('/register', name: 'register', methods: ['POST'])]
    public function register(Request $request): JsonResponse
    {
        $userData = json_decode($request->getContent(), true);

        $user = new User();

        $form = $this->createForm(RegisterType::class, $user);

        $form->submit($userData);

        if (!$form->isValid()) {
            $this->extractFormErrors($form);
        }

        $user->setPassword($this->passwordHasher->hashPassword($user, $user->getPassword()));

        $this->entityManager->persist($user);
        $this->entityManager->flush();

        $response = $this->json([
            'message' => "User has been registred successfully",
            "user" => $user
        ], 201);

        return $response;
    }
}

Nelmio API Doc配置

nelmio_api_doc:
  documentation:
    info:
      title: Asco
      description: This is an awesome app!
      version: 1.0.0
  areas: # to filter documented areas
    path_patterns:
      - ^/api(?!/doc$) # Accepts routes under /api except /api/doc

排查与解决方案

1. 开启注解支持

Nelmio API Doc默认可能未启用注解解析,需在配置文件中添加注解启用项:

nelmio_api_doc:
  documentation:
    info:
      title: Asco
      description: This is an awesome app!
      version: 1.0.0
  areas:
    path_patterns:
      - ^/api(?!/doc$)
  # 新增以下配置开启注解支持
  annotations:
    enabled: true

2. 确保Doctrine注解组件正常工作

若使用Symfony 6+,需先安装doctrine/annotations包:

composer require doctrine/annotations

同时检查config/services.yaml中是否配置了注解阅读器:

services:
  Doctrine\Common\Annotations\AnnotationReader: ~
  Doctrine\Common\Annotations\CachedReader:
    arguments:
      $reader: '@Doctrine\Common\Annotations\AnnotationReader'
      $cache: '@cache.app'

3. 切换为PHP 8属性写法(可选)

若注解方式始终无法生效,可改用PHP 8属性替代注释式注解,修改控制器方法的注解部分:

#[OA\Post(
    path: "/register",
    tags: ["register"],
    summary: "Register a new user",
    description: "Register a new user",
    operationId: "registerUser",
    requestBody: new OA\RequestBody(
        required: true,
        description: "User data",
        content: new OA\JsonContent(ref: "#/components/schemas/User")
    ),
    responses: [
        new OA\Response(
            response: 201,
            description: "User registered successfully",
            content: new OA\JsonContent(ref: "#/components/schemas/User")
        ),
        new OA\Response(
            response: 400,
            description: "Invalid data provided"
        )
    ]
)]

确保zircote/swagger-php版本支持属性(需^4.0及以上):

composer require zircote/swagger-php:^4.0

4. 清除缓存

修改配置或代码后,执行缓存清除命令确保生效:

php bin/console cache:clear

内容的提问来源于stack exchange,提问作者user23627026

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:08:14