使用API Blueprint语法来编写API文档

1、资源Resource

# Gist Fox API Root [/]

在Blueprint里,所有的数据信息都是资源(resource),比如用户、视频、文章。
resource的定义以#开始,中间是resource的名称,最后是用中括号包围的路径(URI),需要注意的是URI是放在[]中的。URI是相对路径,在这里它就是个/。

2、资源描述Resource Description

# Gist Fox API Root [/]
Gist Fox API entry point.
This resource does not have any attributes. Instead it offers the initial API

我们可以用Markdown的语法在resource名称的后面加上包含API名称的说明。
在这里Gist Fox API是API名称,entry point是说明。

3、行为Action

## Retrieve Entry Point [GET]

行为action是一个HTTP请求的属性之一,在发送请求的时候会随数据一起发送到服务器。
我们在这里定义了一个action叫做Retrieve Entry Point (索引入口),它是一个GET类型的请求。我们可以在后面加上一些描述,
但是因为这个action的名字(Retrieve Entry Point)已经把这个行为解释的很清楚了,所以我们就跳过了这一步。

4、在Blueprint有以下四种action:

- GET : 获取数据
- POST : 添加数据
- PUT : 更新数据
- DELETE : 删除数据

5、回应Response

+ Response 200

在API Blueprint中一个action应该至少包括一个回应(response)。response是指当服务器收到一个请求(request)时候的响应。
在response中应该有一个状态码status code和数据payload。
在这里我们定义最常见的状态码:200,表示请求成功。

6、响应负载Response Payload

+ Response 200 (application/hal+json)
+ Headers
Link: <http:/api.gistfox.com/>;rel="self",<http:/api.gistfox.com/gists>;rel="gists"
+ Body
{
    "_links": {
        "self": { "href": "/" },
        "gists": { "href": "/gists?{since}", "templated": true }
    }
}

一个响应(response)经常包含一些负载(payload)。一个负载(payload)通常包含负载体(body)和负载头(header)两个部分。
在这个例子中,我们采用application/hal+json类型作为返回数据的类型。

7、URI模板URI Template

## Gist [/gists/{id}]

在URI中的变量需要遵守URI的模板格式,在这个例子中,Gist的编号(id)在URI中就是{id}。

8、URI参数URI Parameters

+ Parameters
+ id (string) ... ID of the Gist in the form of a hash.

这个id变量是这个resource中的一个参数(parameter),我们定义它的类型为string,并且在后面加上一些解释。

9、资源模型Resource Model

+ Model (application/hal+json)
HAL+JSON representation of Gist Resource. In addition to representing its state in the JSON form it offers affordances in the form of the HTTP Link header and HAL links.
+ Headers
Link: <http:/api.gistfox.com/gists/42>;rel="self", <http:/api.gistfox.com/gists/42/star>;rel="star"
+ Body
{
    "_links": {
        "self": { "href": "/gists/42" },
        "star": { "href": "/gists/42/star" },
    },
    "id": "42",
    "created_at": "2014-04-14T02:15:15Z",
    "description": "Description of Gist",
    "content": "String contents"
}

资源模型Resource Model是前面定义的资源的一个样例,它可以在任何一个request或者response需要的位置引用,一个资源模型有着和前面所说的payload一模一样的结构。
在前面的例子中,还包含了一个额外的描述,也就是在+ Model和+ Headers中间的那部分内容。

ps:下文将介绍aglio生成高大上的api文档

    原文作者:魏什么
    原文地址: https://segmentfault.com/a/1190000019384828
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞