如何在同一端点上使用不同参数获得多个响应?

22

我们正在考虑使用API Blueprint。有些情况下,我们希望一个请求返回一个正确的响应,而另一个请求返回一个“错误”的响应,比如一个400 bad request,以便其他开发人员可以在apiary.io上使用模拟API,并处理它们的应用程序中的两种类型的响应。

下面是我创建的一个完全任意的示例:

## Thing [/thing/{id}]
Gets a thing but the thing id must be a prime number!


+ Parameters
    + id (string) ... ID of the thing, a prime number!

+ Model (application/json)

    The thing itself.

    + Body

            {
                "description": "It is green"
            }

### Retrieve a Single Gist [GET]
+ Response 200

    [Gist][]

现在我想为/thing/40添加一个响应。

+ Response 400
    {  "error" : "Invalid request" }

但我不确定如何在API Blueprint中实现这一点。在apiary.io上的“旧”样式下可以实现这一点,但我们想转移到新语法。

2个回答

12

要记录多个响应,请在Response 200之后添加它,例如:

## Thing [/thing/{id}]
Gets a thing but the thing id must be a prime number!

+ Parameters
    + id (string) ... ID of the thing, a prime number!

+ Model (application/json)

    The thing itself.

    + Body

            {
                "description": "It is green"
            }

### Retrieve a Single Gist [GET]
+ Response 200

    [Thing][]

+ Response 400 (application/json)

        {  "error" : "Invalid request" }

请注意,目前没有专门的语法来讨论返回此响应时的条件。您可以以任何您喜欢的方式进行讨论,例如:

+ Response 400 (application/json)

    This response is returned when no `Thing` for given `id` exists.

    + Body

如果您正在使用Apiary模拟,请记住,默认情况下返回列出的第一个响应,除非您使用prefer HTTP header指定其他返回。


我明白了 - 所以我不能为/thing/40创建特定的描述/响应。我能在某个地方提交功能请求吗? - Mendhak
1
不以结构化的方式呈现。您只能口头评论它。我可以问一下您的用例/为什么需要它吗? - Zdenek
3
计划是在未来的API Blueprint版本中增加对它的支持,主要是为了提高蓝图的可测试性- https://github.com/apiaryio/api-blueprint/issues/21,https://gist.github.com/zdne/01e287fe18d232672d43#new-payload-structure-in-1b。您可以在https://github.com/apiaryio/api-blueprint/issues/milestones上查看和贡献API Blueprint路线图。 - Zdenek
3
现在API Blueprint规范中提供了多个请求/响应对的示例,称为"Multiple Transactions" - bernhardw

1
您可以使用模板,并在通用响应后指定特定的用例,例如:

预订 [/reservation/{reservation_key}]

预订对象具有以下属性:

  • 房间号
  • reserved_at - ISO8601日期,表示发布问题的时间。
  • booker_details - 一个Booker对象。

  • 参数

    • reservation_key(必填,文本,1)...预订密钥ash

查看预订详情 [GET]

  • Response 200 (application/json)

    {
        "room_number": 55,
        "reserved_at": "2014-11-11T08:40:51.620Z",
        "booker_details": 
            {
                "name": "Jon",
                "last_name": "Doe",
            }
    }
    

预订 [/reservation/notarealreservation123]

使用不存在的预订 (请在示例中使用 notarealreservation123) 返回未找到


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接