什么是 OpenAPI 规范?

以 Markdown 格式查看

OpenAPI 规范 (OAS) 是开发人员用来记录 REST API 的框架。该规范以 JSON 或 YAML 格式编写,包含所有端点、参数、模式和身份验证方案。Fern 兼容最新的 OAS 版本,目前是 v3.1.1

以下是 OpenAPI 文件的示例:

openapi.yml
1openapi: 3.0.2
2info:
3 title: Petstore - OpenAPI 3.0
4 description: |-
5 This is a sample Pet Store Server based on the OpenAPI 3.0 specification.
6paths:
7 "/pet":
8 put:
9 tags:
10 - pet
11 summary: Update an existing pet
12 description: Update an existing pet by Id
13 operationId: updatePet
14 requestBody:
15 description: Update an existent pet in the store
16 content:
17 application/json:
18 schema:
19 "$ref": "#/components/schemas/Pet"
20 required: true
21 responses:
22 '200':
23 description: Successful operation
24 content:
25 application/json:
26 schema:
27 "$ref": "#/components/schemas/Pet"
28 '400':
29 description: Invalid ID supplied
30 '404':
31 description: Pet not found
32 '405':
33 description: Validation exception
34 security:
35 - api_key
36components:
37 schemas:
38 Category:
39 type: object
40 properties:
41 id:
42 type: integer
43 format: int64
44 example: 1
45 name:
46 type: string
47 example: Dogs
48 Tag:
49 type: object
50 properties:
51 id:
52 type: integer
53 format: int64
54 name:
55 type: string
56 Pet:
57 required:
58 - name
59 - photoUrls
60 type: object
61 properties:
62 id:
63 type: integer
64 format: int64
65 example: 10
66 name:
67 type: string
68 example: doggie
69 category:
70 "$ref": "#/components/schemas/Category"
71 photoUrls:
72 type: array
73 items:
74 type: string
75 tags:
76 type: array
77 items:
78 "$ref": "#/components/schemas/Tag"
79 status:
80 type: string
81 description: pet status in the store
82 enum:
83 - available
84 - pending
85 - sold
86 securitySchemes:
87 api_key:
88 type: apiKey
89 name: api_key
90 in: header

最佳实践

遵循这些最佳实践,确保您的 OpenAPI 规范生成高质量的 SDK 和文档:

  • 使用合适的项目结构进行组织。 按照项目结构中的说明,清晰地组织包含您的定义和其他相关文件的目录。
  • 为端点添加 operationId 为每个端点包含清晰的 operationId,以控制在 SDK 中生成的函数名称。(或使用扩展来自定义组和方法名称。)
  • 引用模式而不是内联。components/schemas 部分定义可重用的模式,并使用 $ref 引用它们。这促进了一致性,减少了重复,并使维护更容易。
    openapi.yml
    1paths:
    2 /pets:
    3 post:
    4 requestBody:
    5 content:
    6 application/json:
    7 schema:
    8 $ref: '#/components/schemas/Pet' # Clean reference
    9 responses:
    10 '200':
    11 content:
    12 application/json:
    13 schema:
    14 $ref: '#/components/schemas/Pet' # Reused easily
    15components:
    16 schemas:
    17 Pet: # Defined once, used everywhere
    18 type: object
    19 properties:
    20 name:
    21 type: string
    22 status:
    23 type: string
    24 enum: [available, pending, sold]
  • 使用覆盖层和 Fern 扩展进行自定义。 使用 Fern 扩展来自定义您的规范,这些扩展保存在覆盖层文件中。这使您能够修改生成行为,而不更改核心 OpenAPI 定义。

一旦您的 OpenAPI 规范遵循这些实践,您就可以设置 fern 文件夹了。

设置您的 fern 文件夹

正在考虑生成 OpenAPI 规范的选项?在这里获得实时支持

首先使用 OpenAPI 规范初始化您的 fern 文件夹

1fern init --openapi ./path/to/openapi

这将初始化如下所示的目录:

fern
fern.config.json
generators.yml
openapi
openapi.yml# 您的规范