自学内容网 自学内容网

FastAPI 的隐藏宝石:自动生成 TypeScript 客户端

在现代 Web 开发中,前后端分离已成为标准做法。这种架构允许前端和后端独立开发和扩展,但同时也带来了如何高效交互的问题。FastAPI,作为一个新兴的 Python Web 框架,提供了一个优雅的解决方案:自动生成客户端代码。本文将介绍如何利用 FastAPI 的这一功能,为你的前端应用生成 TypeScript 客户端代码。
在这里插入图片描述

1. OpenAPI 规范

FastAPI 遵循 OpenAPI 规范,这意味着它可以生成易于理解和使用的 API 文档,同时也支持自动生成客户端代码。

2. 为什么需要自动生成客户端代码?

自动生成的客户端代码可以减少手动编写和维护 API 交互代码的工作量,同时提供类型安全和错误提示,提高开发效率和代码质量。

3. openapi-ts:TypeScript 的 OpenAPI 客户端生成器

openapi-ts 是一个工具,它可以从 OpenAPI 规范生成 TypeScript 客户端代码,非常适合前端开发。

要自动化生成前端应用的 API 客户端代码,你可以使用 openapi-ts 工具,这是一个基于 OpenAPI 规范的 TypeScript 客户端生成器。以下是使用 openapi-ts 自动生成客户端代码的步骤:

步骤 1: 准备你的 FastAPI 应用

首先,确保你的 FastAPI 应用已经定义了遵循 OpenAPI 规范的 API。例如:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
async def create_item(item: Item):
    return {"name": item.name, "price": item.price}

@app.get("/items/")
async def read_items():
    return [{"name": "Item1", "price": 10.5}, {"name": "Item2", "price": 20.0}]
步骤 2: 安装 openapi-ts

在你的前端项目中,安装 openapi-ts

npm install @hey-api/openapi-ts typescript --save-dev
步骤 3: 添加生成脚本到 package.json

在你的前端项目的 package.json 文件中,添加一个脚本来生成客户端代码:

{
  "scripts": {
    "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/api/client --client axios"
  },
  "devDependencies": {
    "@hey-api/openapi-ts": "^0.27.38",
    "typescript": "^4.6.2"
  }
}

这里假设你的 FastAPI 应用运行在 localhost8000 端口,并且 OpenAPI 文档可以通过 /openapi.json 访问。

步骤 4: 运行生成脚本

在终端中运行以下命令来生成客户端代码:

npm run generate-client

这将生成客户端代码到 ./src/api/client 目录。

步骤 5: 使用生成的客户端代码

在你的前端应用中,你现在可以使用生成的客户端代码来与后端 API 交互。例如:

import { createItem, readItems } from './api/client';

async function addNewItem(item: any) {
  try {
    const response = await createItem({ item });
    console.log(response);
  } catch (error) {
    console.error('Error creating item:', error);
  }
}

async function getAllItems() {
  try {
    const items = await readItems();
    console.log(items);
  } catch (error) {
    console.error('Error fetching items:', error);
  }
}

// 示例调用
addNewItem({ name: 'New Item', price: 15.0 });
getAllItems();

4. 探索生成的客户端代码

查看 openapi-ts 生成的客户端代码,了解其结构和功能,包括服务文件和模型文件。

使用 openapi-ts 生成的 ./src/api/client 目录将包含根据你的 FastAPI 应用的 OpenAPI 规范自动生成的 TypeScript 客户端代码。具体的文件结构和内容会根据你的 API 设计和 openapi-ts 的配置有所不同,但通常你可能会看到以下类型的文件:

4-1. 服务文件(Service Files)

这些文件包含了与特定 API 端点交互的方法。例如,如果你有一个创建项目的端点和一个获取项目列表的端点,你可能会有类似以下的文件:

// Generated by openapi-ts
export class ItemsService {
  async createItem(body: { name: string; price: number; description?: string | null; tax?: number | null }): Promise<{ name: string; price: number }> {
    const response = await axios.post<{ name: string; price: number }>('http://localhost:8000/items/', body);
    return response.data;
  }

  async getItems(): Promise<{ name: string; price: number }[]> {
    const response = await axios.get<{ name: string; price: number }[]>('http://localhost:8000/items/');
    return response.data;
  }
}
4-2. 模型文件(Model Files)

这些文件定义了请求和响应的数据模型,基于你的 Pydantic 模型或其他类型定义。例如:

// Generated by openapi-ts
export interface Item {
  name: string;
  description?: string | null;
  price: number;
  tax?: number | null;
}

export interface CreateItemResponse {
  name: string;
  price: number;
}

export interface GetItemsResponse {
  items: Item[];
}
4-3. 索引文件(Index File)

这个文件通常用于集中导出所有服务和模型,方便在应用的其他部分导入使用:

// Generated by openapi-ts
export * from './ItemsService';
export * from './models';
4-4. 配置文件(Config File)

如果有必要,可能会有一个配置文件,用于定义客户端的一些配置,如基础 URL、请求头等。

4-5. 辅助工具文件(Utility Files)

有时,生成的代码可能包括一些辅助工具函数或类型,用于支持客户端的功能。

示例代码结构
./src/api/client
|-- index.ts
|-- ItemsService.ts
|-- models.ts
代码示例
  • ItemsService.ts:

    import { axios } from 'axios';
    export class ItemsService {
      async createItem(body: { name: string; price: number; description?: string | null; tax?: number | null }) {
        const response = await axios.post<{ name: string; price: number }>('http://localhost:8000/items/', body);
        return response.data;
      }
      async getItems() {
        const response = await axios.get<{ name: string; price: number }[]>('http://localhost:8000/items/');
        return response.data;
      }
    }
    
  • models.ts:

    export interface Item {
      name: string;
      description?: string | null;
      price: number;
      tax?: number | null;
    }
    
  • index.ts:

    export * from './ItemsService';
    export * from './models';
    

这些文件提供了一个类型安全的方式来与后端 API 进行交互,减少了手动编写和维护 API 客户端代码的工作量。

5. 在前端应用中使用客户端代码

将生成的客户端代码集成到你的前端应用中,开始与后端 API 进行交互。

结语

FastAPI 的自动客户端代码生成功能,为前后端分离的开发模式提供了一个强大的工具。通过 openapi-ts,你可以轻松地为你的 TypeScript 前端应用生成类型安全的 API 客户端代码,提高开发效率,减少错误。这是一个值得探索和利用的功能,尤其是在快速迭代和维护大型项目时。


本文介绍了如何利用 FastAPI 和 openapi-ts 自动生成 TypeScript 客户端代码,帮助你的前端应用与后端 API 高效交互。通过自动化这个过程,你可以节省时间,减少错误,并提高代码质量。


原文地址:https://blog.csdn.net/ylong52/article/details/142422197

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!