当前位置: 首页 > news >正文

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 BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str = Noneprice: floattax: 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 高效交互。通过自动化这个过程,你可以节省时间,减少错误,并提高代码质量。

http://www.lryc.cn/news/443594.html

相关文章:

  • 了解云容器实例云容器实例(Cloud Container Instance)
  • OpenStack Yoga版安装笔记(十三)neutron安装
  • [系列]参数估计与贝叶斯推断
  • 【Pyside】pycharm2024配置conda虚拟环境
  • 【RabbitMQ 项目】服务端:数据管理模块之消息队列管理
  • SDKMAN!软件开发工具包管理器
  • 《使用 LangChain 进行大模型应用开发》学习笔记(四)
  • gbase8s数据库常见的索引扫描方式
  • 边缘智能-大模型架构初探
  • 《python语言程序设计》2018版第8章18题几何circle2D类(上部)
  • nginx upstream转发连接错误情况研究
  • alias 后门从入门到应急响应
  • 【远程调用PythonAPI-flask】
  • [今日Arxiv] 思维迭代:利用内心对话进行自主大型语言模型推理
  • glTF格式:WebGL应用的3D资产优化解决方案
  • Unity3D入门(一) : 第一个Unity3D项目,实现矩形自动旋转,并导出到Android运行
  • 数据结构与算法——Java实现 8.习题——移除链表元素(值)
  • 如何理解MVCC
  • 在 Qt 中使用 QLabel 设置 GIF 动态背景
  • Flyway 数据库差异处理
  • CSS 选择器的分类与使用要点一
  • 无人机集群路径规划:麻雀搜索算法(Sparrow Search Algorithm, SSA)​求解无人机集群路径规划,提供MATLAB代码
  • harbor集成trivy镜像扫描工具
  • DMA学习
  • C语言18--头文件
  • vscode软件在 C发中常用插件
  • 【C++ Primer Plus习题】17.2
  • Vue Props传值
  • FreeSWITCH event_socket 配置从其他地址连接
  • 信息安全数学基础(19)同余式的基本概念及一次同余式