OpenAPI被用来描述基于HTTP的API,是目前被广泛接受和使用的API工业标准。
API描述文件是一个机器可读的API定义文件。它应该是尽量完整的、细致的、明确的。开发者可以使用API描述文件来自动生成API文档以及代码。
格式: JSON 或者 YAML
openapi: 3.1.0 # OpenAPI版本
info:
title: A minimal OpenAPI document
version: 0.0.1 # API版本
paths: {} # No endpoints defined
servers:
- url: https://{username}.server.com:{port}/{version}
variables:
username:
default: demo
description: This value is assigned by the service provider.
port:
enum:
- "8443"
- "443"
default: "8443"
version:
default: v1
paths:
/board: # URI
get: # HTTP方法
...
put:
...
get:
summary: Get the whole board
description: Retrieves the current state of the board and the winner.
responses:
"200":
description: "OK"
content:
...
post:
summary:
description:
response:
requestBody:
parameters:
paths:
/board:
get:
responses:
"200":
description: Everything went fine.
content:
...
"404": ...
content:
application/json:
...
text/html:
...
text/*:
...
content:
application/json:
schema:
type: integer
minimum: 1
maximum: 100
content:
application/json:
schema:
type: string
enum:
- Alice
- Bob
- Carl
content:
application/json:
schema:
type: array
minItems: 1
maxItems: 10
items:
type: integer
content:
application/json:
schema:
type: object
properties:
productName:
type: string
productPrice:
type: number
方法对象中的requestBody和parameters共同定义了HTTP请求中的数据。
requestBody:
required: true
content:
application/json:
schema:
type: string
enum: [".", "X", "O"]
paths:
/users/{id}:
get:
parameters:
- name: id # 必须有的,定义参数名
in: path # 必须有的,定义参数的来源,可以是 path, query, header中的一个
required: true # 可选的
schema:
type: integer
minimum: 1
maximum: 100
可以使用components和ref来重用一个对象,例如:
components:
schemas:
coordinate:
type: integer
minimum: 1
maximum: 3
parameters:
rowParam:
name: row
in: path
required: true
schema:
$ref: "#/components/schemas/coordinate"
columnParam:
name: column
in: path
required: true
schema:
$ref: "#/components/schemas/coordinate"
paths:
/board/{row}/{column}:
post:
parameters:
- $ref: "#/components/parameters/rowParam"
- $ref: "#/components/parameters/columnParam"
/page/{row}/{column}:
post:
parameters:
- $ref: "#/components/parameters/rowParam"
- $ref: "#/components/parameters/columnParam"
段落可以使用文本模式和折叠模式,文本模式中的段落会原样输出,而折叠模式将会自动换行。
文本模式输入:
description: |
This is a string
in multiple lines.
And an extra one.
文本模式输出:
This is a string
in multiple lines.
And an extra one.
折叠模式输入:
description: >
This is a string
in multiple lines.
And an extra one.
折叠模式输出:
This is a string in multiple lines.
And an extra one.
description对象中也支持markdown的语法
OpenAPI Generator可以根据OpenAPI的API描述文件自动生成客户端、服务器端代码以及API文档。使用homebrew安装的命令如下:
|$ brew install openapi-generator
生成代码的命令:
openapi-generator generate -i petstore.yaml -g ruby -o /tmp/test/
其中 -i
指定API描述文件,-g
指定代码语言,-o
指定输出路径。