什么是 API 定义?

以 Markdown 格式查看

API 定义是对您的 API 结构的机器可读规范,包括端点请求和响应模式,以及身份验证要求。API 定义能够自动生成这些工件,而不需要手动保持 SDK 和文档与 API 变更的同步。

Fern 集成了多种 API 定义格式:

OpenAPI 原称 Swagger,是最受欢迎的 API 定义格式。OpenAPI 可用于记录 RESTful API,并在 YAML 或 JSON 文件中定义。

此处查看 Petstore API 的 OpenAPI 规范示例

1openapi: 3.0.2
2tags:
3 - name: pet
4 description: Everything about your Pets
5paths:
6 /pet:
7 post:
8 tags:
9 - pet
10 summary: Add a new pet to the store
11 description: Add a new pet to the store
12 operationId: addPet
13 requestBody:
14 description: Create a new pet in the store
15 required: true
16 content:
17 application/json:
18 schema:
19 $ref: '#/components/schemas/Pet'
20 application/xml:
21 schema:
22 $ref: '#/components/schemas/Pet'
23 application/x-www-form-urlencoded:
24 schema:
25 $ref: '#/components/schemas/Pet'
26 responses:
27 '200':
28 description: Successful operation
29 content:
30 application/xml:
31 schema:
32 $ref: '#/components/schemas/Pet'
33 application/json:
34 schema:
35 $ref: '#/components/schemas/Pet'
36 '405':
37 description: Invalid input
38 components:
39 schemas:
40 Pet:
41 required:
42 - name
43 - photoUrls
44 properties:
45 id:
46 type: integer
47 format: int64
48 example: 10
49 name:
50 type: string
51 example: doggie
52 category:
53 $ref: '#/components/schemas/Category'
54 photoUrls:
55 type: array
56 xml:
57 wrapped: true
58 items:
59 type: string
60 xml:
61 name: photoUrl
62 tags:
63 type: array
64 xml:
65 wrapped: true
66 items:
67 $ref: '#/components/schemas/Tag'
68 xml:
69 name: tag
70 status:
71 type: string
72 description: pet status in the store
73 enum:
74 - available
75 - pending
76 - sold
77 xml:
78 name: pet
79 type: object

AsyncAPI 是用于定义事件驱动 API 的规范。它用于记录使用 WebSocket、MQTT 和其他消息传递协议的 API。

查看下面聊天应用程序的 AsyncAPI 规范示例:

1asyncapi: 2.0.0
2info:
3 title: Chat server
4 version: 1.0.0
5
6servers:
7 Production:
8 url: chat.com
9 protocol: ws
10
11channels:
12 "/application":
13 bindings:
14 ws:
15 query:
16 type: object
17 properties:
18 apiKey:
19 type: string
20 description: The API key for the client
21 minimum: 1
22 bindingVersion: 0.1.0
23 subscribe:
24 operationId: sendMessage
25 message:
26 $ref: '#/components/messages/SendMessage'
27 publish:
28 operationId: receiveMessage
29 message:
30 $ref: '#/components/messages/ReceiveMessage'
31
32components:
33 messages:
34 SendMessage:
35 payload:
36 message: string
37 ReceiveMessage:
38 payload:
39 message: string
40 from:
41 type: string
42 description: The userId for the sender of the message

OpenRPC 是用于描述 JSON-RPC 2.0 API 的规范。它为 JSON-RPC 生态系统提供了交互式文档和代码生成工具。

查看下面加密钱包服务的 OpenRPC 规范示例:

1# yaml-language-server: $schema=https://meta.open-rpc.org/
2$schema: https://meta.open-rpc.org/
3openrpc: 1.2.4
4info:
5 title: Basic Wallet API JSON-RPC Specification
6 description: A simple JSON-RPC API for querying wallet balances.
7 version: 0.0.1
8servers:
9 - url: https://wallet.example.com/json-rpc
10 name: Mainnet
11methods:
12 - name: getBalance
13 description: Get the balance of a wallet address.
14 params:
15 - name: address
16 required: true
17 description: The wallet address to query.
18 schema:
19 type: string
20 result:
21 name: balance
22 description: The balance of the wallet address.
23 schema:
24 type: number
25 examples:
26 - name: getBalance example
27 params:
28 - name: address
29 value: "0x1234567890abcdef1234567890abcdef12345678"
30 result:
31 name: balance
32 value: 42.5

gRPC 是由 Google 开发的现代开源 RPC 框架。它使用 Protocol Buffers 作为接口定义语言,支持多种编程语言,并具有高效的二进制序列化功能。

gRPC API 使用 Protocol Buffer(.proto)文件定义,这些文件指定服务和消息类型。查看下面的 gRPC 服务定义示例:

1syntax = "proto3";
2
3package petstore;
4
5// The pet store service definition
6service PetStoreService {
7 // Get a pet by ID
8 rpc GetPet(GetPetRequest) returns (Pet);
9
10 // Add a new pet to the store
11 rpc AddPet(AddPetRequest) returns (Pet);
12
13 // List all pets with optional filtering
14 rpc ListPets(ListPetsRequest) returns (ListPetsResponse);
15}
16
17// Request message for getting a pet
18message GetPetRequest {
19 int64 pet_id = 1;
20}
21
22// Request message for adding a pet
23message AddPetRequest {
24 string name = 1;
25 string category = 2;
26 repeated string photo_urls = 3;
27 PetStatus status = 4;
28}
29
30// Request message for listing pets
31message ListPetsRequest {
32 int32 page_size = 1;
33 string page_token = 2;
34 PetStatus status = 3;
35}
36
37// Response message for listing pets
38message ListPetsResponse {
39 repeated Pet pets = 1;
40 string next_page_token = 2;
41}
42
43// Pet message definition
44message Pet {
45 int64 id = 1;
46 string name = 2;
47 string category = 3;
48 repeated string photo_urls = 4;
49 PetStatus status = 5;
50}
51
52// Pet status enumeration
53enum PetStatus {
54 PET_STATUS_UNSPECIFIED = 0;
55 PET_STATUS_AVAILABLE = 1;
56 PET_STATUS_PENDING = 2;
57 PET_STATUS_SOLD = 3;
58}

Fern Definition 是我们对更简单 API 定义格式的理解。它采用最佳实践设计,同时支持 RESTful 和事件驱动 API,并针对 SDK 生成进行了优化。

Fern Definition 受到了 AmazonGooglePalantir、Twilio 和 Stripe 等公司内部 API Definition 格式的启发。这些公司拒绝了 OpenAPI 并构建了自己的版本。

查看下面的 Fern Definition 示例:

1types:
2 MovieId: string
3
4 Movie:
5 properties:
6 id: MovieId
7 title: string
8 rating:
9 type: double
10 docs: The rating scale is one to five stars
11
12 CreateMovieRequest:
13 properties:
14 title: string
15 rating: double
16
17service:
18 auth: false
19 base-path: /movies
20 endpoints:
21 createMovie:
22 docs: Add a movie to the database
23 method: POST
24 path: /create-movie
25 request: CreateMovieRequest
26 response: MovieId
27
28 getMovie:
29 method: GET
30 path: /{movieId}
31 path-parameters:
32 movieId: MovieId
33 response: Movie
34 errors:
35 - MovieDoesNotExistError
36
37errors:
38 MovieDoesNotExistError:
39 status-code: 404
40 type: MovieId

为什么要创建 API 定义?

一旦您拥有 API 定义,Fern 就会将其用作输入来生成诸如 SDK 和 API 参考文档等工件。每当您更新 API 定义时,都可以重新生成这些工件以确保它们始终保持最新状态。