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

API Platform 3.0+Symfony6.2中Swagger UI未显示API操作求助

问题描述

在Symfony 6.2(PHP 8.1)项目中安装API Platform Core v3.0.7后,创建首个API资源,但Swagger UI无法检测到资源操作。尝试Doctrine管理实体和普通PHP对象+数据提供者两种方式,Swagger仅在"Schemas"区域展示类,显示No operations defined in spec!。经测试API调用可正常返回数据,仅文档未展示操作。

现有配置如下:

配置文件 config/packages/api_platform.yaml

api_platform:
    mapping:
        paths: ['%kernel.project_dir%/src/Api/Model']

资源类 src/Api/Model/Team.php

<?php
# src/Api/Model/Team.php

namespace App\Api\Model;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use App\Api\State\TeamProvider;

#[ApiResource(provider: TeamProvider::class)]
class Team
{
    #[ApiProperty(identifier: true)]
    public int $id;

    public string $name;

    public string $slug;
}

数据提供者 src/Api/State/TeamProvider.php

<?php
# src/Api/State/TeamProvider.php

namespace App\Api\State;

use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Api\Model\Team;

/**
 * @implements ProviderInterface<Team>
 */
class TeamProvider implements ProviderInterface
{
    /**
     * {@inheritDoc}
     * @param array<string,mixed> $uriVariables
     * @param array<mixed> $context
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        $team = new Team();
        $team->id = 1;
        $team->name = "Test team"; // 修正原代码笔误:将id赋值改为name赋值
        $team->slug = "test-team";

        if ($operation instanceof CollectionOperationInterface) {
            return [$team];
        }

        return $team;
    }
}
解决方案

针对API Platform v3.x版本的问题,可通过以下步骤解决:

  1. 显式定义资源操作
    API Platform v3.x不会自动为资源生成操作,需在ApiResource注解中显式声明,并确保操作开启文档支持:
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;

#[ApiResource(
    operations: [
        new Get(),
        new GetCollection()
    ],
    provider: TeamProvider::class
)]

如果需要字段分组,可添加normalizationContext参数,比如new Get(normalizationContext: ['groups' => 'team:item'])。

  1. 确认OpenAPI配置启用
    检查api_platform.yaml,确保OpenAPI支持处于开启状态(默认开启,可显式配置):
api_platform:
    mapping:
        paths: ['%kernel.project_dir%/src/Api/Model']
    enable_openapi: true
    openapi:
        title: '你的API名称'
        version: '1.0.0'
  1. 清除Symfony缓存
    缓存可能导致文档未更新,执行命令清除缓存:
php bin/console cache:clear --env=dev

之后刷新Swagger UI页面(默认路径/api/docs)查看效果。

  1. 验证注解命名空间
    确保Get、GetCollection等操作注解的命名空间已正确导入,避免因类不存在导致操作未注册。

内容的提问来源于stack exchange,提问作者Émile Perron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:31:02