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

API Platform中非实体关联接口如何添加date类型查询参数?

解决API Platform中日期查询参数无法识别的问题

问题原因

你之前的配置不符合OpenAPI规范:OpenAPI里的date类型需要通过string类型配合format: date来定义,直接指定type: date会导致API文档无法正确识别,从而显示为any类型并渲染纯文本框。

正确配置方式

修改QueryParameter的schema配置,明确指定类型为string并添加date格式,同时可以补充示例值提升文档可读性:

#[ApiResource(
    shortName: 'VAT',
    routePrefix: 'EU-vat',
    operations: [
        new Get(
            name: 'vat_get',
            uriTemplate: '/get-rate/{country_code}',
            uriVariables: [
                'country_code' => new Link(
                    description: 'ISO 3166-1 alpha-2国家代码',
                    schema: [
                        'type' => 'string',
                        'example' => 'IT',
                    ],
                ),
            ],
            parameters: [
                'date' => new QueryParameter(
                    description: '查询增值税率的日期',
                    schema: [
                        'type' => 'string',
                        'format' => 'date',
                        'example' => '2024-01-01',
                    ],
                    // 根据业务需求设置是否允许为空
                    nullable: false,
                ),
            ],
            output: GetVatRateResult::class,
            provider: VatStateProvider::class,
        ),
    ],
)]
class Vat
{
}

参数转换为\DateTime对象

配置完成后,API文档会正确渲染日期选择器。要将请求中的日期字符串转换为\DateTime对象,可在VatStateProvider的业务逻辑中处理:

class VatStateProvider implements ProviderInterface
{
    public function getItem(
        string $resourceClass,
        $id,
        string $operationName = null,
        array $context = []
    ): GetVatRateResult {
        $countryCode = $id;
        // 从请求上下文获取date参数(API Platform会自动解析查询参数到filters数组)
        $dateString = $context['filters']['date'] ?? date('Y-m-d');
        // 转换为DateTime对象
        $date = \DateTime::createFromFormat('Y-m-d', $dateString);
        
        // 这里编写根据国家代码和日期获取增值税率的逻辑
        $rate = // 业务逻辑获取税率值
        
        return new GetVatRateResult($rate, $date, $countryCode);
    }
}

验证效果

重新生成API文档后,date参数会被识别为日期类型,界面将显示日期选择器而非纯文本框,同时请求传入的日期字符串能正确转换为\DateTime对象供业务逻辑使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 13:52:38