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

API Platform中隐藏/users/{id}端点遇到的问题求助

问题:隐藏API Platform中的/users/{id}端点

我想禁用/users/{id}这个端点,一开始直接这么配置:

#[ApiResource(
    shortName: 'Users',
    collectionOperations: ['GET'],
    itemOperations:[],
    normalizationContext: [
        'skip_null_values' => false,
    ],
)]

但访问/users时出现错误:No item route associated with the type "App\Entity\User"。

后来查资料试了下面的配置:

#[ApiResource(
    shortName: 'Users',
    collectionOperations: ['GET'],
    itemOperations: ['GET' => [
        "method" => "GET",
            "controller" => NotFoundAction::class,
            "read" => false,
            "output" => false
    ]],
    normalizationContext: [
        'skip_null_values' => false,
    ],
)]

这下/users恢复正常了,但/users/{id}端点又重新出现了。

补充说明
尝试用operations配置完全不行,IDE报错说当前库不存在operations,但vendor/api-platform/core/src/Annotation/ApiResource.php里明明有$itemOperations;另外也没法引用new Get(), new GetCollection()。


解决方法

要彻底隐藏/users/{id}同时保证/users正常,有两个可行方案:

方案1:自定义路由并设置不暴露

给itemOperations里的GET操作指定自定义路由名,然后在路由配置里标记为不暴露:

#[ApiResource(
    shortName: 'Users',
    collectionOperations: ['GET'],
    itemOperations: ['GET' => [
        "route_name" => "app_user_item_disabled",
        "controller" => NotFoundAction::class,
        "read" => false,
        "output" => false
    ]],
    normalizationContext: [
        'skip_null_values' => false,
    ],
)]

然后在config/routes.yaml中添加:

app_user_item_disabled:
    path: /users/{id}
    methods: ['GET']
    defaults:
        _controller: 'api_platform.action.not_found'
    requirements:
        id: '\d+'
    options:
        expose: false # 关键:不让这个路由出现在API文档里

方案2:通过openapi_context隐藏文档+返回404

如果只是不想让端点显示在Swagger/OpenAPI文档里,同时访问返回404,可以直接在操作配置里加openapi_context: ['hidden' => true]:

#[ApiResource(
    shortName: 'Users',
    collectionOperations: ['GET'],
    itemOperations: ['GET' => [
        "controller" => NotFoundAction::class,
        "read" => false,
        "output" => false,
        "openapi_context" => [
            'hidden' => true
        ]
    ]],
    normalizationContext: [
        'skip_null_values' => false,
    ],
)]

这样配置后,/users/{id}不会出现在API文档中,访问时返回404,/users也能正常访问。

另外关于版本差异的问题:
你当前用的是API Platform 2.x版本,这个版本确实只支持itemOperations和collectionOperations配置;而operations数组+Get()/GetCollection()操作类是3.x版本的新特性,所以你没法用这些语法。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:05:27