【问题标题】:How can I have multiple responses from a single endpoint with different parameters?如何从具有不同参数的单个端点获得多个响应?
【发布时间】:2014-01-22 09:39:58
【问题描述】:

我们正在考虑使用 API 蓝图。在某些情况下,我们希望一个请求返回正确的响应,而另一个请求返回一个“错误”响应,例如 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 蓝图来做到这一点。这在 apiary.io 上的“旧”样式下是可以实现的,但我们想继续使用新语法

【问题讨论】:

    标签: apiary.io apiblueprint


    【解决方案1】:

    要记录多个响应,只需将其添加到 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 另有说明。

    【讨论】:

    【解决方案2】:

    您可以使用模板并在对资源进行通用响应后指定特定用例,请参见示例:

    预订 [/reservation/{reservation_key}]

    Reservation 对象具有以下属性:

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

    • 参数

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

    查看预订详情 [GET]

    • 响应 200(应用程序/json)

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

    预订 [/reservation/notarealreservation123]

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2012-03-22
      • 2019-08-02
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多