Попытка описать запрос и ответ с использованием структур данных в API Blueprint

Я пытаюсь задокументировать конечную точку с помощью API Blueprint, используя новые разделы спецификации Attributes и DataStructures.

Полезная нагрузка моего запроса выглядит так:

{
    "url": "http://requestb.in/11v7i7e1",
    "active": true,
    "types": [
        {
            "name": "sales",
            "version": "2.0"
        },
        {
            "name": "products",
            "version": "2.0"
        }
    ]
}

Полезная нагрузка моего ответа выглядит примерно так:

{
  "data": {
    "id": "dc85058a-a683-11e4-ef46-e9431a15be8c",
    "url": "http://requestb.in/11v7i7e1",
    "active": true,
    "types": [
      {
        "name": "products",
        "version": "2.0"
      },
      {
        "name": "sales",
        "version": "2.0"
      }
    ]
  }
}

Я попробовал следующую уценку API Blueprint:

FORMAT: 1A

# Vend REST API 2.0

# Group Webhooks

## api/2.0/webhooks [/webhooks]

### List all Webhooks [GET]
Returns a list of Webhooks created by the authorised application.

+ Response 200 (application/json)
    + Attributes (Webhook Collection)

### Add a new Webhook [POST]
Creates a new Webhook.

+ Attributes (Webhook Base)

+ Request (application/json)
    + Attributes (Webhook Base)

+ Response 200 (application/json)
    + Attributes (Webhook Response)

# Data Structures

## Webhook Base (object)
+ url: https://example.com/webhook (string, required) - The address where webhooks requests should be submitted.
+ active: true (boolean, required) - This field can be used to inspect or edit state of the webhook.
+ types: array[Webhook Type] (array[Webhook Type], required) - Collection of Webhook types which should trigger Webhook event.

## Webhook Response Base (Webhook Base)
+ id: dc85058a-a683-11e4-ef46-e8b98f1a7ae4 (string, required) - Webhook `id`.

## Webhook Response (object)
+ data: webhook (Webhook Response Base, required)

## Webhook Type (object)
+ name: sales (string, required) - One of: products, sales, customers, taxes
+ version: 2.0 (string, required) - Version of the payload to be delivered. Currently the only supported value is "2.0".

## Webhook Collection (object)
+ data: array[Webhook Response Base] (array[Webhook Response Base], required) - An array of Webhook objects.

Теперь, когда я смотрю на него в Apiary, он говорит мне, что это действительный документ API Blueprint, но это не то, как я просматриваю JSON для запроса и ответа. Можно ли вообще представить такие структуры в API Blueprint и красиво отобразить их в Apiary?


person Piotr Zurek    schedule 22.04.2015    source источник
comment
Эй, я думаю, это связано с комбинацией ошибок в вашем описании и небольшой ошибкой на пасеке. Дайте мне час или около того, и я должен дать вам больше информации.   -  person Pavan Kumar Sunkara    schedule 23.04.2015
comment
Великолепно! Я рад слышать, что это не просто невозможно. :-) Ждем вашего ответа.   -  person Piotr Zurek    schedule 23.04.2015


Ответы (1)


Это сочетание двух проблем:

  1. неправильный синтаксис
  2. ошибка в рендеринге

1. Синтаксис

Проблема, кажется, здесь:

## Webhook Collection (object)
+ data: array[Webhook Response Base] (array[Webhook Response Base], required) - An array of Webhook objects.

Глядя на + data: array[Webhook Response Base] (array[Webhook Response Base]). В основном, когда ожидается значение (после :), значение должно быть предоставлено. Вместо этого — в данном случае — у вас есть тип array[Webhook Response Base].

Позвольте мне продемонстрировать на более простом примере:

+ data: number (array[number])

неверно.

Правильная версия будет

+ data: 42 (array[number])

or

+ data (array[number])
    + 42

or

+ data (array)
    + 42 (number)

2. Ошибка в рендеринге

Даже если вы поправите чертеж, он не будет отображаться в Apairy. Это ошибка, которую мы обнаружили в нашем рендерере JSON. Об этом сообщалось здесь https://github.com/apiaryio/drafter.js/issues/26 мы планируем исправить это как можно скорее.

Это исправлено

Исправленный план

FORMAT: 1A

# Vend REST API 2.0

# Group Webhooks

## api/2.0/webhooks [/webhooks]

### List all Webhooks [GET]
Returns a list of Webhooks created by the authorised application.

+ Response 200 (application/json)
    + Attributes (Webhook Collection)

### Add a new Webhook [POST]
Creates a new Webhook.

+ Attributes (Webhook Base)

+ Request (application/json)
    + Attributes (Webhook Base)

+ Response 200 (application/json)
    + Attributes (Webhook Response)

# Data Structures

## Webhook Base (object)
+ url: https://example.com/webhook (string, required) - The address where webhooks requests should be submitted.
+ active: true (boolean, required) - This field can be used to inspect or edit state of the webhook.
+ types (array[Webhook Type], required) - Collection of Webhook types which should trigger Webhook event.

## Webhook Response Base (Webhook Base)
+ id: dc85058a-a683-11e4-ef46-e8b98f1a7ae4 (string, required) - Webhook `id`.

## Webhook Response (object)
+ data (Webhook Response Base, required)

## Webhook Type (object)
+ name: sales (string, required) - One of: products, sales, customers, taxes
+ version: 2.0 (string, required) - Version of the payload to be delivered. Currently the only supported value is "2.0".

## Webhook Collection (object)
+ data (array[Webhook Response Base], required) - An array of Webhook objects.

Надеюсь, что это ответ на ваш вопрос. Пожалуйста, дайте мне знать, если необходимы дополнительные разъяснения.

person Zdenek    schedule 23.04.2015
comment
Блестящий. На самом деле я допустил ошибку с использованием array[Webhook Response Base], когда отчаянно пытался отобразить его. Приятно видеть, что вы, ребята, работаете над исправлением ошибки. Я буду следить за ним на GtiHub, чтобы убедиться, что я попробую еще раз, когда он будет исправлен. - person Piotr Zurek; 23.04.2015
comment
@PiotrZurek Обратите внимание, что мы отредактировали план после вашего последнего комментария. - person Pavan Kumar Sunkara; 23.04.2015
comment
Ву ху! Я вижу, что сейчас это исправлено в Apiary. Спасибо ребята. - person Piotr Zurek; 08.05.2015
comment
Здравствуйте, мне кажется, что этот ответ справа от того, что мне нужно, не могли бы вы взглянуть на него? - stackoverflow.com/questions/ 31752483/ - person Stefan; 31.07.2015