1

我在一个 ApiResource 上有三个集合操作,它们具有不同的normalization_contextfilters.

  • /equipments检索所有设备(根据当前用户过滤)
  • /equipments/A检索所有符合规则 A 的设备
  • /equipments/B检索所有符合规则 B 的设备

一些过滤器是在嵌套属性(相关实体的 ID)上设置的。我想为 API 使用者提供可用于某些过滤器的值。假设我有一个由所有端点共享的公司过滤器。

  • 允许的/equipments值为 1,2,3
  • 允许的/equipments/A值为 4,5,6
  • 允许的/equipments/B值为 1,3,5

我看到的解决方案是.../filters为每个将返回具有允许值的过滤器的操作添加端点。

GET /equipments/filters

[
    {
        'name': 'company',
        'type': integer,
        'choices': [
            'Company 1': 1,
            'Company 2': 2,
            'Company 3': 3,
        ]
    },
    {
        'name': 'operator',
        'type': autocomplete,
        'url': /equipments/filters/operator?q={q}
    }
]

额外问题:如果这是一个好的解决方案,我可以在哪里以及如何在 JSON-LD/Hydra 文档中添加这些操作?

4

1 回答 1

1

大多数 API 文档格式,包括 Swagger 和 JSON-LD(由 API 平台支持)都允许为过滤器指定有效值,而无需进行自定义操作。

使用 Swagger,您可以使用对象enum的属性parameter来定义有效值:https ://swagger.io/docs/specification/2-0/enums/

paths:
  /equipments/B:
    get:
      parameters:
        - in: query
          name: company
          description: A company filter
          type: integer
          enum: [1, 3, 5]

如果您更喜欢使用 Hydra,您可以使用模板链接来实现您想要的:

{
  "@context": "http://www.w3.org/ns/hydra/context.jsonld",
  "@type": "IriTemplate",
  "template": "/equipments/B{?company}",
  "mappings": [
    {
      "@type": "IriTemplateMapping",
      "variable": "company",
      "property": "http://example.com/myCompanyType"
    }
  ]
}

然后,您需要通过添加返回适用值的端点来动态返回值,或者如果列表是静态的(例如http://schema.org/ActionStatusType),则需要直接在词汇表中的词汇表中返回值。

要将此类信息添加到 API 平台,您需要装饰生成文档的内置服务。Swagger 示例:https ://github.com/api-platform/docs/blob/master/core/swagger.md#override-swagger-documentation

于 2017-08-23T09:16:18.627 回答