跳到导航

什么是 OpenAPI 规范?

以 Markdown 格式查看

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

以下是 OpenAPI 文件的示例:

openapi.yml
openapi: 3.0.2
info:
title: Petstore - OpenAPI 3.0
description: |-
This is a sample Pet Store Server based on the OpenAPI 3.0 specification.
paths:
"/pet":
put:
tags:
- pet
summary: Update an existing pet
description: Update an existing pet by Id
operationId: updatePet
requestBody:
description: Update an existent pet in the store
content:
application/json:
schema:
"$ref": "#/components/schemas/Pet"
required: true
responses:
'200':
description: Successful operation
content:
application/json:
schema:
"$ref": "#/components/schemas/Pet"
'400':
description: Invalid ID supplied
'404':
description: Pet not found
'405':
description: Validation exception
security:
- api_key
components:
schemas:
Category:
type: object
properties:
id:
type: integer
format: int64
example: 1
name:
type: string
example: Dogs
Tag:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
Pet:
required:
- name
- photoUrls
type: object
properties:
id:
type: integer
format: int64
example: 10
name:
type: string
example: doggie
category:
"$ref": "#/components/schemas/Category"
photoUrls:
type: array
items:
type: string
tags:
type: array
items:
"$ref": "#/components/schemas/Tag"
status:
type: string
description: pet status in the store
enum:
- available
- pending
- sold
securitySchemes:
api_key:
type: apiKey
name: api_key
in: header

最佳实践

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

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

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

设置您的 fern 文件夹

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

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

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

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