如何为 multipart/form-data 接口生成符合 axios 的 TS 类型?
解读
国内面试常把“FastAPI 写接口”与“前端 TS 调用”串起来考察,核心看三点:
- FastAPI 侧能否正确声明 multipart/form-data 参数,并给出 OpenAPI 描述;
- 能否利用 FastAPI 生成的 OpenAPI JSON,一键产生前端 TS 类型;
- 产生的类型如何与 axios 的泛型、请求头、FormData 组装无缝衔接,避免 any 或手动二次声明。
面试官往往追问:
- 为什么不用 application/json?
- 大文件分片上传时类型怎么扩展?
- 如果后端字段改名,如何低成本同步到前端?
知识点
- FastAPI 的
File()与Form()混用机制,以及python-multipart依赖; - OpenAPI 3.0 对 multipart 的 schema 描述规则(type: string, format: binary 或 base64);
openapi-typescript/swagger-typescript-api命令行工具,把 OpenAPI 转成 TS 声明;- axios 泛型接口
AxiosResponse<T>与FormData的组装技巧; - 国内工程化惯例:把生成的类型文件纳入
src/types/openapi.ts,通过 CI 校验“后端变更 -> 前端类型漂移”; - 大文件场景下,如何把
File[]声明成type: array, items: {type: string, format: binary},以及切片后字段的动态索引签名; - 类型安全与运行时校验的边界:TS 类型只在编译期存在,仍需后端 Pydantic 做最终校验。
答案
步骤一:FastAPI 侧精确声明接口
from fastapi import FastAPI, File, Form, UploadFile
from typing import List
app = FastAPI()
@app.post("/upload", summary="批量上传附件")
async def upload(
title: str = Form(..., description="文件标题"),
tags: List[str] = Form(default=[]), # 表单数组
files: List[UploadFile] = File(...) # 多文件
):
return {"title": title, "file_count": len(files)}
启动后访问 /openapi.json,可见:
"/upload": {
"post": {
"requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"properties": {
"title": {"type": "string"},
"tags": {"type": "array", "items": {"type": "string"}},
"files": {
"type": "array",
"items": {"type": "string", "format": "binary"}
}
},
"required": ["title", "files"]
}
}
}
}
}
}
步骤二:一键生成 TS 类型
国内团队普遍把脚本写在 package.json:
"scripts": {
"gen:api": "swagger-typescript-api -p http://localhost:8000/openapi.json -o ./src/types --modular --axios"
}
生成文件 src/types/Upload.ts:
export interface UploadRequest {
title: string;
tags?: string[];
files: File[]; // 工具已把 format:binary 映射成 File
}
export interface UploadResponse {
title: string;
file_count: number;
}
步骤三:前端 axios 调用保持类型安全
import { UploadRequest, UploadResponse } from '@/types/Upload';
import axios from 'axios';
export async function uploadApi(form: UploadRequest): Promise<UploadResponse> {
const fd = new FormData();
fd.append('title', form.title);
form.tags?.forEach(t => fd.append('tags', t));
form.files.forEach(f => fd.append('files', f));
// axios 泛型约束返回体
const { data } = await axios.post<UploadResponse>('/upload', fd, {
headers: { 'Content-Type': 'multipart/form-data' }
});
return data;
}
至此,前后端共用一份 OpenAPI,字段变动只需重新跑 npm run gen:api,TS 编译器会立即提示所有调用处需要适配,实现“零手工对齐”。
拓展思考
- 大文件分片上传:后端增加
chunk_index: int = Form(...)、total_chunks: int = Form(...),前端把File切成Blob,生成的 TS 类型里chunk_index与total_chunks一并暴露;同时利用axios.onUploadProgress做进度条,类型依然保持UploadChunkRequest。 - 字段安全重命名:国内项目常因产品调整改字段名,可在 Pydantic 里使用
Field(alias="oldName"),OpenAPI 仍输出新名字,前端生成类型自动跟随,实现“无痛重构”。 - 非 File 二进制场景:如上传图片并同步返回可访问 URL,可在 FastAPI 用
response_model声明{"url": HttpUrl},前端 TS 直接拿到string,避免手写any。 - 多端复用:同一套 OpenAPI 还能生成小程序、Flutter 的模型类,实现“后端一次编写,多端类型安全”。
- 性能与类型平衡:multipart 上传大文件时,Starlette 会把整个请求体读进内存,生产环境需搭配
nginx-upload-module或 S3 预签名直传,TS 类型层保持不变,仅替换底层实现,体现“接口契约优先”思想。