创建网站制作首页,手机网页版微信登录入口,境外服务器,视频号认证需要多少钱在现代 Web 开发中#xff0c;前后端分离已成为标准做法。这种架构允许前端和后端独立开发和扩展#xff0c;但同时也带来了如何高效交互的问题。FastAPI#xff0c;作为一个新兴的 Python Web 框架#xff0c;提供了一个优雅的解决方案#xff1a;自动生成客户端代码。本…在现代 Web 开发中前后端分离已成为标准做法。这种架构允许前端和后端独立开发和扩展但同时也带来了如何高效交互的问题。FastAPI作为一个新兴的 Python Web 框架提供了一个优雅的解决方案自动生成客户端代码。本文将介绍如何利用 FastAPI 的这一功能为你的前端应用生成 TypeScript 客户端代码。
1. OpenAPI 规范
FastAPI 遵循 OpenAPI 规范这意味着它可以生成易于理解和使用的 API 文档同时也支持自动生成客户端代码。
2. 为什么需要自动生成客户端代码
自动生成的客户端代码可以减少手动编写和维护 API 交互代码的工作量同时提供类型安全和错误提示提高开发效率和代码质量。
3. openapi-tsTypeScript 的 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 Noneapp.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 应用运行在 localhost 的 8000 端口并且 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 高效交互。通过自动化这个过程你可以节省时间减少错误并提高代码质量。