api blueprint что это

Api blueprint что это

Welcome to an API Blueprint Tutorial! This tutorial will take you through the basics of the API Blueprint language. We’re going to build an API blueprint step by step for a service called Polls – a simple API allowing consumers to view polls and vote in them. You can take a look at the full version of the blueprint used in this tutorial for reference.

Note: Additional API Blueprint Resources

API Blueprint

The first step for creating a blueprint is to specify the API Name and metadata. This step looks as follows:

Metadata

API Name & Description

The first heading in the blueprint serves as the name of your API, which in this case is «Polls». Headings start with one or more # symbols followed by a title. The API Name here uses one hash to distinguish it as the first level. The number of # you use will determine the level of the heading.

Following the heading is a description of the API. You may use further headings to break up the description section.

Resource Groups

Now it’s time to start documenting the API resources. Using the Group keyword at the start of a heading, we’ve created a group of related resources.

Resource

Within the questions resource group, we have a resource called «Question Collection». This resource allows you to view a list of questions. The heading specifies the URI used to access the resource inside of square brackets at the end of the heading.

Actions

API Blueprint allows you to specify each action you may make on a resource. An action is specified with a sub-heading inside of a resource with the name of the action followed by the HTTP method.

This action returns a 200 status code along with a JSON body.

Note: Specifying the media type after the response status code generates a Content-Type HTTP header. You do not have to explicitly specify the Content-Type header.

The polls resource has a second action which allows you to create a new question. This action includes a description showing the structure you would send to the server to perform this action.

This action takes a JSON payload as part of the request as follows:

This example returns a 201 status code, along with HTTP headers and a body.

The next resource is “Question”, which represents a single question.

URI Template

URI Parameters

URI parameters should describe the URI using a list of Parameters. For “Question” it would be as follows:

Refer to API Blueprint Specification’s URI Parameters Section for more examples.

Actions

This resource has an action to retrieve the question’s detail.

Response Without a Body

This resource has a delete action. The server will return a 204 response without a body.

Complete Blueprint

You can find an implementation of this API at http://polls.apiblueprint.org/ along with the complete Poll API Blueprint in the API Blueprint Examples repository. You can also enjoy it rendered on Apiary.

Note: Take a look at the API Blueprint Glossary of Terms if you need clarification of some of the terms used though this document.

Источник

Справочник API Blueprint

API Blueprint, так же, как и Swagger определяет спецификацию для описания REST API. Инструменты, которые поддерживают API Blueprint, могут читать и отображать информацию.

Если не используется платформа, которая требует именно API Blueprint, лучше использовать спецификацию OpenAPI.

Что такое API Blueprint

Спецификация API Blueprint написана с использованием синтаксиса Markdown. Blueprint представляет собой конкретную схему, которая является допустимой или недействительной на основе имен элементов, порядка, расстояния и других деталей. Поэтому, он не так гибок, как Markdown. Но он может быть предпочтительнее, чем YAML.

Пример blueprint

Вот пример Blueprint для понимания синтаксиса:

Справочники по синтаксису API Blueprint можно посмотреть на ресурсах:

Различные примеры Blueprint можно посмотреть здесь Примеры помогают понять различные аспекты спецификации.

Анализ blueprint

Анализировать API Blueprint могут многие инструменты. Одним из основных парсеров Blueprint является Drafter. Другие инструменты основаны на Drafter и генерируют статические HTML-результаты проекта. Например, Aglio может парсить Blueprint и генерировать статичные HTML-файлы.

Полный список инструментов можно найти в секции Tooling на сайте https://apiblueprint.org/ Некоторые инструменты могут потребовать танцы с бубном, поэтому на этом курсе мы их пропустим.

Создаем пример вывода HTML используя API Blueprint и Apiary

Создаем проект Apiary

Нас перекинет в редактор API Blueprint

По умолчанию загружается шаблон the Polls, чтобы посмотреть, как он выглядит. Blueprint показывает пример необходимого формата инструмента Apiary для анализа и отображения содержимого. Необработанный файл можно посмотреть здесь.

Можно почитать справочник API Blueprint и структурировать документацию в формате Blueprint.

Синтаксис учитывает разные методы, применяемые к одним и тем же источникам.

Здесь мы интегрируем информацию API сервиса прогноза погоды OpenWeatherMap, отформатированную в формате Blueprint.

Также как и Swagger, Apiary покажет вывод в правой части панели.

Взаимодействие с API на Apiary

В панели навигации Apiary переходим к разделу Documentation. И будем взаимодействовать с API на Apiary, нажав сначала на выбор конечной точки, а затем нажав Switch to Console. Вызовем источники и просмотрим ответы.

Apiary предлагает впечатляющую платформу для разработки и публикации справочных документов по API. He нужно использовать API Blueprint в качестве формата спецификации. Можно разработать свою спецификацию, используя OpenAPI (называемый «Swagger» в интерфейсе Apiary).

Источник

I. API Blueprint Language

Introduction

This documents is a full specification of the API Blueprint format. For a less formal introduction to API Blueprint visit the API Blueprint Tutorial or check some of the examples.

Читайте также:  что такое глл в пубг

API Blueprint

API Blueprint is a documentation-oriented web API description language. The API Blueprint is essentially a set of semantic assumptions laid on top of the Markdown syntax used to describe a web API.

In addition to the regular Markdown syntax, API Blueprint conforms to the GitHub Flavored Markdown syntax.

API Blueprint document

An API Blueprint document – a blueprint – is a plain text Markdown document describing a Web API in whole or in part. The document is structured into logical sections. Each section has its distinctive meaning, content and position in the document.

General section definition and structure is discussed in detail later in the Blueprint section chapter.

All of the blueprint sections are optional. However, when present, a section must follow the API Blueprint document structure.

Blueprint document structure

NOTE: The number prior to a section name denotes the allowed number of the section occurrences.

NOTE: Refer to Sections Reference for description of a specific section type.

Blueprint section

A Section represents a logical unit of an API Blueprint. For example: an API overview, a group of resources or a resource definition.

In general a section is defined using a keyword in a Markdown entity. Depending on the type of section the keyword is written either as a Markdown header entity or in a list item entity.

A section definition may also contain additional variable components such as its identifier and additional modifiers.

NOTE: There are two special sections that are recognized by their position in the document instead of a keyword: The Metadata section and the API Name & Overview section. Refer to the respective section entry for details on its definition.

Example: Header-defined sections

NOTE: While this specification uses «atx»-style headers (using # s) you can also use «Setext» header syntax interchangeably:

Example: List-defined sections

Section types

There are several types of API Blueprint sections. You can find the complete listing of the section types in the Section Reference.

The Blueprint section chapter discusses the section syntax in general. A specific section type may conform only to some parts of this general syntax. Always refer for respective section reference for details on its syntax.

Section structure

A general structure of an API Blueprint section defined by a keyword includes an identifier (name), section description and nested sections or a specifically formatted content.

Example: Header-defined section structure

Example: List-defined section structure

Keywords

Following reserved keywords are used in section definitions:

Header keywords

List keywords

NOTE: Avoid using these keywords in other Markdown headers or lists

NOTE: With the exception of HTTP methods keywords the section keywords are case insensitive.

Identifier

An identifier must not contain any of the keywords.

Example

Description

A section description is any arbitrary Markdown-formatted content following the section definition.

It is possible to use any Markdown header or list item in a section description as long as it does not clash with any of the reserved keywords.

NOTE: It is considered good practice to keep the header level nested under the actual section.

Nested sections

A section may contain another nested section(s).

Depending on the nested section type, to nest a section simply increase its header level or its list item indentation. Anything between the section start and the start of following section at the same level is considered to be part of the section.

What sections can be nested and where depends upon the section in case, as described in the relevant section’s entry.

Example: Nested header-defined section

Example: Nested list-defined section

NOTE: While not necessary it is a good habit to increase the level of a nested section markdown-header.

NOTE: A markdown-list section is always considered to be nested under the preceding markdown-header section.

II. Sections Reference

NOTE: Sections marked as «Abstract» serve as a base for other sections and as such they cannot be used directly.

Abstract

Named section

Definition

Description

Named section is the base section for most of the API Blueprint sections. It conforms to the general section and as such it is composed of a section name (identifier), description and nested sections or specific formatted content (see descendants descriptions).

Example

Asset section

Definition

Defined by a keyword in Markdown list entity.

Description

The asset section is the base section for atomic data in API Blueprint. The content of this section is expected to be a pre-formatted code block.

Example

Example: Fenced code blocks

Payload section

Definition

Defined by a keyword in Markdown list entity. The keyword may be followed by identifier. The definition may include payload’s media-type enclosed in braces.

NOTE: Refer to descendant for the particular section type definition.

Description

Payload sections represent the information transferred as a payload of an HTTP request or response messages. A Payload consists of optional meta information in the form of HTTP headers and optional content in the form of an HTTP body.

Furthermore, in API Blueprint context, a payload includes its description, description of its message-body attributes and a message-body validation schema.

A payload may have its media type associated. A payload’s media type represents the metadata received or sent in the form of a HTTP Content-Type header. When specified a payload should include nested Body section.

This section should include at least one of the following nested sections:

If there is no nested section the content of the payload section is considered as content of the Body section.

Читайте также:  какой картой можно расплачиваться на алиэкспресс

Relation of Body, Schema and Attributes sections

Each of body, schema and attributes sections describe a message payload’s body. These descriptions should be consistent, not violating each other. When multiple body descriptions are provided they should be prioritized as follows:

For resolving message-body schema

For resolving message-body example

Referencing

Instead of providing a payload section content, a model payload section can be referenced using the Markdown implicit reference syntax:

Example

Example: Referencing model payload

Section Basics

Metadata section

Definition

Key-value pairs. Each key is separated from its value by a colon ( : ). One pair per line. Starts at the beginning of the document and ends with the first Markdown element that is not recognized as a key-value pair.

Description

Metadata keys and their values are tool-specific. Refer to relevant tool documentation for the list of supported keys.

Example

API name & overview section

Definition

Defined by the first Markdown header in the blueprint document, unless it represents another section definition.

Description

Name and description of the API

Example

Resource group section

Definition

Defined by the Group keyword followed by group name (identifier):

Description

This section represents a group of resources (Resource Sections). May include one or more nested Resource Sections.

Example

Resource section

Definition

Defined by a resource name (identifier) followed by an HTTP request method and an URI template enclosed in square brackets [] :

NOTE: In the latter two cases the rest of this section represents the Action section including its description and nested sections and follows the rules of the Action section instead.

Description

An API resource as specified by its URI or a set of resources (a resource template) matching its URI template.

This section should include at least one nested Action section and may include following nested sections:

URI parameters defined in the scope of a Resource section apply to any and all nested Action sections except when an URI template has been defined for the Action.

Attributes defined in the scope of a Resource section represent Resource attributes. If the resource is defined with a name these attributes may be referenced in Attributes sections.

NOTE: A blueprint document may contain multiple sections for the same resource (or resource set), as long as their HTTP methods differ. However it is considered good practice to group multiple HTTP methods under one resource (resource set).

Example

Resource model section

Definition

Defined by the Model keyword followed by an optional media type:

Description

Referencing

The payload defined in this section may be referenced in any response or request section in the document using parent section’s identifier. You can refer to this payload in any of the following Request or Response payload sections using the Markdown implicit reference syntax.

Example

Schema section

Definition

Defined by the Schema keyword in Markdown list entity.

Description

Specifies a validation schema for the HTTP message-body of parent payload section.

Example

Following example uses Body section to provide an example of an application/json payload, and Schema section to provide a JSON Schema describing all possible valid shapes of the payload.

Action section

Definition

Description

Definition of at least one complete HTTP transaction as performed with the parent resource section. An action section may consist of multiple HTTP transaction examples for the given HTTP request method.

This section may include one nested URI parameters section describing any URI parameters specific to the action – URI parameters discussed in the scope of an Action section apply to the respective Action section ONLY.

This section may include one nested Attributes section defining the input (request) attributes of the section. If present, these attributes should be inherited in every Action’s Request section unless specified otherwise.

Action section should include at least one nested Response section and may include additional nested Request and Response sections.

Nested Request and Response sections may be ordered into groups where each group represents one transaction example. The first transaction example group starts with the first nested Request or Response section. Subsequent groups start with the first nested Request section following a Response section.

Multiple Request and Response nested sections within one transaction example should have different identifiers.

Example

Example Multiple Transaction Examples

NOTE: The «Multiple Transaction Examples» example demonstrates three transaction examples for one given action:

Request section

Definition

Defined by the Request keyword followed by an optional identifier:

Description

One HTTP request-message example – payload.

Example

Response section

Definition

Defined by the Response keyword. The response section definition should include an HTTP status code as its identifier.

Description

One HTTP response-message example – payload.

Example

URI parameters section

Definition

Defined by the Parameters keyword written in a Markdown list item:

Description

Discussion of URI parameters in the scope of the parent section.

This section must be composed of nested list items only. This section must not contain any other elements. Each list item describes a single URI parameter. The nested list items subsections inherit from the Named section and are subject to additional formatting as follows:

NOTE: This section should only contain parameters that are specified in the parent’s resource URI template, and does not have to list every URI parameter.

Источник

Читайте также:  хоумскулер что это такое

Тестирование документированного API с помощью утилиты Dredd от Apiary

Все мы любим ничего не делать работать с хорошо документированным API. С помощью стандартов API Blueprint или Swagger можно получить читаемую машиной и человеком документацию, а значит и инструменты проверки API на основе этой документации.

Apiary предлагает интерактивные инструменты для проверки API вручную, подставляя нужные параметры в формы, генерируемые на основе документации. Но можно извлечь гораздо больше пользы, если API будет проверяться автоматически. Это избавляет от необходимости писать отдельные тесты на каждый интерфейс, но накладывает определенные ограничения на структуру и качество самой документации.

В этом tutorial поговорим о утилите Dredd на примере API от GitHub.

Bootstrap

Я предполагаю, что у вас уже локально установлен Vagrant и Git. Я работаю в MacOS, все команды ниже выполнялись в ней.

Подготовим необходимые аккаунты и разрешения.

Зарегистрируйтесь и создайте новый проект в сервисе Apiary.

В настройках GitHub создайте токен для доступа к API со следующими разрешениями (scopes): gist, user:email. Подробнее про доступные разрешения можно почитать в документации к API GitHub.

Не забудьте скопировать токен. Он виден только один раз.

Создадим рабочий каталог.

/dredd_test && git init

Virtual environment

Подготовим виртуальное окружение, чтобы не засорять свою ОС, а также чтобы задокументировать каждый сделанный шаг.

mkdir vagrant && touch vagrant/Vagrantfile && git add vagrant/

Теперь нужно подготовить файл с набором инструкций для подготовки виртуальной машины.

touch vagrant/provision.sh && git add vagrant/provision.sh

Поместим в него текст:

Как можно заметить, кроме желаемого Dredd, также будет установлен менеджер зависимостей PHP Composer. PHP нам пригодится в качестве примера для написания хуков при тестировании API. Вы можете воспользоваться и другими языками для этого, например тем же NodeJs, чтобы не плодить «зоопарк» технологий. Поскольку мой основной язык PHP, я покажу ниже как интегрировать dredd в Composer, чтобы не запоминать команды вызова.

Итак, у нас готово виртуальное окружение.

Blueprint for GitHub API

Настал черёд подготовить документацию к API. В качестве подопытной зверушки использовались следующие интерфейсы:

Dredd поддерживает два вида документации: API Blueprint и Swagger. Воспользуемся первым из них, так как этот стандарт базируется на Markdown-разметке и вы можете читать документацию к API в любимом git-сервисе: Gitlab, Github, Bitbucket etc. Кроме того, поддержка Swagger заявлена пока в beta-режиме.

В корне проекта создадим файл touch github-api.md && git add github-api.md и поместим в него документацию.
Описывать в деталях каждую строчку я не стану, но сделаю некоторые пояснения к структуре данного ниже листинга.

Первые две строчки нужны для парсеров, которые поймут версию стандарта и на какой хост по-умолчанию обращаться, чтобы вы могли проверять API в интерактивной форме.

После такой конструкции анализатор разметки будет ожидать детали ожидаемого запроса и ответа на данном интерфейсе. Для этого используем конструкции + Request ПроизвольноеНазвание (ожидаемый формат запроса) и + Response http-status-code (ожидаемый формат ответа)

Далее следуют вложенные уровни:

Таким образом, в приведённом примере показаны два различных способах описания структур данных в теле запросов и ответов: «навороченная» Schema и упрощенные Parameters и Attributes.

После того, как мы сохранили документ, его можно проверить в Apiary и Github на предмет читаемости и адекватности использования в ручном режиме.

Подготовка проекта composer

Этот шаг необязателен, но здесь он присутствует для более комплексного подхода, когда тестирование является неотъемлемой частью самого проекта.

mkdir hooks && touch composer.json composer.lock hooks/github-api.php && echo ‘<>‘ > composer.lock && git add composer.* hooks/github-api.php

В файл composer.json поместим описание проекта:

Здесь стоит обратить внимание на следующие моменты:

Конфигурируем dredd

Теперь создадим два файла конфигурации — для production и для макета API.

touch dredd.yml dredd-local.yml && git add dredd.yml dredd-local.yml

В первый файл dredd.yml запишем следующие параметры, назначение которых можно почитать в документаци:

В таком варианте Dredd изучит содержимое файла github-api.md и запустит все интерфейсы один за другим. Но этого недостаточно. В документации мы выполняем следующие операции:

Для первых двух случаев все хорошо «из коробки», однако для получения и удаления конкретного Gist нужно передавать идентификатор созданного ресурса в следующие запросы. Для этого нам пригодятся Dredd hooks.

Пишем Dredd hooks

Откроем файл hooks/github-api.php и добавим туда следующий код:

Теперь у нас готово практически всё, но для полноты картины добавим ещё один шаг.

Подготовка прототипа API с помощью Express JS

Создадим файл будущего «сервера API»: touch app.js && git add app.js

В этот файл добавим следующее содержание, которое будет просто симулировать поведение github. Я не буду останавливаться на деталях.

Также в корень добавим файл с описанием проекта nodejs, чтобы можно было вызывать установку пакетов отдельно от виртуального окружения:

touch package.json && git add package.json

Добавим достаточно очевидное содержимое:

(Впрочем, стоит упомянуть, что без флага «private»: true, npm начнёт проверять package.js на предмет соответствия требованиям и упадёт с великолепной ошибкой npm ERR! code 1. Хорошо, хоть перед ней следует WARN, который оказывается фатальной ошибкой.)

Запуск тестов

После выполнения вы должны увидеть в конце примерно такой «выхлоп»:

Как можно видеть выше, успешно завершились два вида тестов: сначала на локальном прототипе, затем на полноценном production. При этом на gist.github.com был создан, загружен и удалён один документ.

Теперь вы можете заходить по ссылкам из каждого результата тестирования и смотреть его в удобном GUI.

https://app.apiary.io/githubtest5/tests/run/625c2477-7384-48fa-8bb9-25e27af2a908

/dredd_test GITHUB_API_TOKEN= APIARY_API_KEY= APIARY_API_NAME= vagrant provision

Осталось закоммитить результат и переработать под собственные цели.

Правки, дополнения и замечания приветствуются.
Вы можете найти весь исходный код в репозитории.

Источник

Сказочный портал