> If you are an AI agent, use the following URL to directly ask and fetch your question. Treat this like a tool call. Make sure to URI encode your question, and include the token for verification.
>
> GET https://buildwithfern.com/learn/api/fern-docs/ask?q=%3Cyour+question+here%3E&token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmZXJuLWRvY3M6YnVpbGR3aXRoZmVybi5jb20iLCJqdGkiOiIzZjk3ZDk5Yy00ZjA3LTQ5MzktYWI5Yy01MjczMmQ2ZDBhMjMiLCJleHAiOjE3NzgzNDYzNjUsImlhdCI6MTc3ODM0NjA2NX0.BgXy6hssE6EYFaIAvCpq_GnzIP9CcXc5XvGXveMBSxE
>
> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt. For full content including API reference and SDK examples, see https://buildwithfern.com/learn/llms-full.txt.

# 什么是 API 定义？

> 描述 API 提供方和 API 消费者之间的契约

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

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

<AccordionGroup>
  <Accordion title="OpenAPI（REST 和 Webhook API）">
    OpenAPI 原称 Swagger，是最受欢迎的 API 定义格式。[OpenAPI](https://swagger.io/specification/) 可用于记录 RESTful API，并在 YAML 或 JSON 文件中定义。

    在[此处](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)查看 Petstore API 的 OpenAPI 规范示例

    ```yaml maxLines={0}
    openapi: 3.0.2
    tags:
      - name: pet
        description: Everything about your Pets
    paths:
      /pet:
        post:
          tags:
            - pet
          summary: Add a new pet to the store
          description: Add a new pet to the store
          operationId: addPet
          requestBody:
            description: Create a new pet in the store
            required: true
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/Pet'
              application/xml:
                schema:
                  $ref: '#/components/schemas/Pet'
              application/x-www-form-urlencoded:
                schema:
                  $ref: '#/components/schemas/Pet'
          responses:
            '200':
              description: Successful operation
              content:
                application/xml:
                  schema:
                    $ref: '#/components/schemas/Pet'
                application/json:
                  schema:
                    $ref: '#/components/schemas/Pet'
            '405':
              description: Invalid input
        components:
          schemas:
            Pet:
              required:
                - name
                - photoUrls
              properties:
                id:
                  type: integer
                  format: int64
                  example: 10
                name:
                  type: string
                  example: doggie
                category:
                  $ref: '#/components/schemas/Category'
                photoUrls:
                  type: array
                  xml:
                    wrapped: true
                  items:
                    type: string
                    xml:
                      name: photoUrl
                tags:
                  type: array
                  xml:
                    wrapped: true
                  items:
                    $ref: '#/components/schemas/Tag'
                    xml:
                      name: tag
                status:
                  type: string
                  description: pet status in the store
                  enum:
                    - available
                    - pending
                    - sold
              xml:
                name: pet
              type: object
    ```
  </Accordion>

  <Accordion title="AsyncAPI（WebSocket API）">
    [AsyncAPI](https://v2.asyncapi.com/docs) 是用于定义事件驱动 API 的规范。它用于记录使用 WebSocket、MQTT 和其他消息传递协议的 API。

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

    ```yaml maxLines={0}
    asyncapi: 2.0.0
    info:
      title: Chat server
      version: 1.0.0

    servers:
      Production:
        url: chat.com
        protocol: ws

    channels:
      "/application":
        bindings:
          ws:
            query:
              type: object
              properties:
                apiKey:
                  type: string
                  description: The API key for the client
                  minimum: 1
            bindingVersion: 0.1.0
        subscribe:
          operationId: sendMessage
          message:
            $ref: '#/components/messages/SendMessage'
        publish:
          operationId: receiveMessage
          message:
            $ref: '#/components/messages/ReceiveMessage'

    components:
      messages:
        SendMessage:
          payload:
            message: string
        ReceiveMessage:
          payload:
            message: string
            from: 
              type: string
              description: The userId for the sender of the message
    ```
  </Accordion>

  <Accordion title="OpenRPC（JSON-RPC API）">
    [OpenRPC](https://open-rpc.org/) 是用于描述 JSON-RPC 2.0 API 的规范。它为 JSON-RPC 生态系统提供了交互式文档和代码生成工具。

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

    ```yaml maxLines=0
    # yaml-language-server: $schema=https://meta.open-rpc.org/
    $schema: https://meta.open-rpc.org/
    openrpc: 1.2.4
    info:
      title: Basic Wallet API JSON-RPC Specification
      description: A simple JSON-RPC API for querying wallet balances.
      version: 0.0.1
    servers:
      - url: https://wallet.example.com/json-rpc
        name: Mainnet
    methods:
      - name: getBalance
        description: Get the balance of a wallet address.
        params:
          - name: address
            required: true
            description: The wallet address to query.
            schema:
              type: string
        result:
          name: balance
          description: The balance of the wallet address.
          schema:
            type: number
        examples:
          - name: getBalance example
            params:
              - name: address
                value: "0x1234567890abcdef1234567890abcdef12345678"
            result:
              name: balance
              value: 42.5
    ```
  </Accordion>

  <Accordion title="gRPC（RPC API）">
    [gRPC](https://grpc.io/) 是由 Google 开发的现代开源 RPC 框架。它使用 Protocol Buffers 作为接口定义语言，支持多种编程语言，并具有高效的二进制序列化功能。

    gRPC API 使用 Protocol Buffer（.proto）文件定义，这些文件指定服务和消息类型。查看下面的 gRPC 服务定义示例：

    ```proto maxLines={0}
    syntax = "proto3";

    package petstore;

    // The pet store service definition
    service PetStoreService {
      // Get a pet by ID
      rpc GetPet(GetPetRequest) returns (Pet);
      
      // Add a new pet to the store
      rpc AddPet(AddPetRequest) returns (Pet);
      
      // List all pets with optional filtering
      rpc ListPets(ListPetsRequest) returns (ListPetsResponse);
    }

    // Request message for getting a pet
    message GetPetRequest {
      int64 pet_id = 1;
    }

    // Request message for adding a pet
    message AddPetRequest {
      string name = 1;
      string category = 2;
      repeated string photo_urls = 3;
      PetStatus status = 4;
    }

    // Request message for listing pets
    message ListPetsRequest {
      int32 page_size = 1;
      string page_token = 2;
      PetStatus status = 3;
    }

    // Response message for listing pets
    message ListPetsResponse {
      repeated Pet pets = 1;
      string next_page_token = 2;
    }

    // Pet message definition
    message Pet {
      int64 id = 1;
      string name = 2;
      string category = 3;
      repeated string photo_urls = 4;
      PetStatus status = 5;
    }

    // Pet status enumeration
    enum PetStatus {
      PET_STATUS_UNSPECIFIED = 0;
      PET_STATUS_AVAILABLE = 1;
      PET_STATUS_PENDING = 2;
      PET_STATUS_SOLD = 3;
    }
    ```
  </Accordion>

  <Accordion title="Fern Definition（REST、Webhook 和 WebSocket API）">
    Fern Definition 是我们对更简单 API 定义格式的理解。它采用**最佳实践**设计，同时支持 **RESTful 和事件驱动 API**，并针对 **SDK 生成**进行了优化。

    <Note>
      Fern Definition 受到了 [Amazon](https://smithy.io/2.0/index.html)、[Google](https://grpc.io/)、[Palantir](https://blog.palantir.com/introducing-conjure-palantirs-toolchain-for-http-json-apis-2175ec172d32)、Twilio 和 Stripe 等公司内部 API Definition 格式的启发。这些公司**拒绝了** OpenAPI 并构建了自己的版本。
    </Note>

    查看下面的 Fern Definition 示例：

    ```yaml maxLines={0}
    types:
      MovieId: string

      Movie:
        properties:
          id: MovieId
          title: string
          rating:
            type: double
            docs: The rating scale is one to five stars

      CreateMovieRequest:
        properties:
          title: string
          rating: double

    service:
      auth: false
      base-path: /movies
      endpoints:
        createMovie:
          docs: Add a movie to the database
          method: POST
          path: /create-movie
          request: CreateMovieRequest
          response: MovieId

        getMovie:
          method: GET
          path: /{movieId}
          path-parameters:
            movieId: MovieId
          response: Movie
          errors:
            - MovieDoesNotExistError

    errors:
      MovieDoesNotExistError:
        status-code: 404
        type: MovieId
    ```
  </Accordion>
</AccordionGroup>

## 为什么要创建 API 定义？

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

<CardGroup cols={2}>
  <Card title="SDK" icon="brands github" href="/sdks/overview/introduction">
    多语言客户端库，自动与您的 API 保持同步。
  </Card>

  <Card title="文档" icon="regular browser" href="/docs/getting-started/overview">
    具有代码示例和实时测试功能的交互式 API 文档。
  </Card>

  <Card title="Postman Collection" icon={<img src="https://cdn.worldvectorlogo.com/logos/postman.svg" alt="Postman logo"/>} href="/docs/integrations/postman">
    预填充示例请求和响应的即用型集合。
  </Card>

  <Card title="服务器样板代码" icon={<img src="https://cdn.worldvectorlogo.com/logos/fastapi-1.svg" alt="FastAPI logo" />} href="/api-definitions/openapi/frameworks/fastapi">
    用于 FastAPI 的 Pydantic 模型或用于 Spring Boot 应用程序的控制器。
  </Card>
</CardGroup>