npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

fastapi-ts-sdk

v1.0.1

Published

类型安全的 FastAPI 前后端工具链 - 自动生成TS类型、请求客户端、SSE流式支持

Downloads

529

Readme

fastapi-ts-sdk

English | 简体中文

从 FastAPI 的 OpenAPI schema 生成自包含、类型安全的 TypeScript 类型定义和 API 客户端。使用生成代码的应用在运行时无需安装或引入本 SDK。

特性

  • 端到端类型安全:覆盖路径参数、查询参数、请求体和响应
  • 自包含生成结果:生成的应用不包含 SDK 导入,也没有 SDK 运行时依赖
  • 原生 Fetch 客户端:支持浏览器和 Node.js 18+
  • SSE 流式响应:支持流解析和可配置的重试策略
  • 文件上传:基于原生 FormData
  • 请求自定义:支持请求头、拦截器、错误处理和请求取消
  • Watch 模式:OpenAPI schema 变化时自动重新生成
  • 客户端可选:生成类型也可配合 Axios 或项目现有的 Fetch 封装使用

环境要求

  • 运行生成器需要 Node.js 18 或更高版本
  • 使用生成的 Fetch 客户端需要现代浏览器或 Node.js 18+
  • FastAPI 应用需要暴露 OpenAPI schema,通常位于 /openapi.json

安装

将本包安装为开发依赖:

npm install --save-dev fastapi-ts-sdk
# 或
pnpm add -D fastapi-ts-sdk
# 或
yarn add --dev fastapi-ts-sdk

本包仅在生成代码时使用。生成的 types.ts、client.ts 和 index.ts 都是应用内的自包含代码,前端运行时无需保留本 SDK 依赖。

包名是 fastapi-ts-sdk,安装后提供的是 fastapi-ts 命令。因此在未安装的项目里直接调用时,请使用 npx fastapi-ts-sdk;本地安装后也可以直接运行 npx fastapi-ts。

快速开始

1. 生成客户端

启动 FastAPI 应用,然后运行:

npx fastapi-ts-sdk generate \
  --input http://localhost:8000/openapi.json \
  --output ./src/api

如果使用开发服务器代理,例如 Vite 的 /api 代理,请在生成时设置请求基础路径:

npx fastapi-ts-sdk generate \
  --input http://localhost:8000/openapi.json \
  --output ./src/api \
  --base-url /api

--base-url 优先于 OpenAPI servers 中的第一个 URL。通过生成参数配置请求地址,可以避免手动修改生成文件,并确保重新生成后的结果一致。

命令将生成以下文件:

src/api/
├── types.ts    # Schema 和 Paths 类型
├── client.ts   # 独立客户端、Fetch 实现、SSE 和 ApiError
└── index.ts    # 统一导出

2. 使用生成的客户端

import api, { ApiError } from './api';

const items = await api.get('/items', {
  query: { skip: 0, limit: 20 },
});

const item = await api.get('/items/{item_id}', {
  path: { item_id: 1 },
});

const created = await api.post('/items', {
  body: {
    name: '示例',
    price: 99.9,
  },
});

try {
  await api.get('/items/{item_id}', { path: { item_id: 1 } });
} catch (error) {
  if (ApiError.isValidationError(error)) {
    console.error('请求参数无效:', error.data);
  } else if (error instanceof ApiError) {
    console.error(error.status, error.statusText, error.data);
  }
}

3. 监听 schema 变化

npx fastapi-ts-sdk generate \
  --input http://localhost:8000/openapi.json \
  --output ./src/api \
  --base-url /api \
  --watch

包括 --base-url 在内的生成参数在 watch 模式下同样生效。

请求实现与现有 HTTP 客户端集成

生成的客户端直接使用原生 Fetch API:

  • JSON 请求体通过 JSON.stringify() 序列化。
  • multipart 文件上传使用 FormData。
  • 请求取消使用 AbortController。
  • SSE 请求同样使用 fetch,并通过 response.body.getReader() 和 TextDecoder 读取、解析响应,不使用 EventSource。

api.get()、api.post() 和 api.stream() 是可选的便捷封装,并非唯一使用方式。已有 HTTP 客户端的项目可以只导入生成的类型,完全忽略生成的客户端。

配合现有 Axios 实例

import axios from 'axios';
import type { Item, ItemCreate, Paths } from './api/types';

type ItemsQuery = Paths['/items']['get']['parameters']['query'];

const { data: items } = await axios.get<Item[]>('/api/items', {
  params: { skip: 0, limit: 20 } satisfies ItemsQuery,
});

const { data: created } = await axios.post<Item>('/api/items', {
  name: '示例',
  price: 99.9,
} satisfies ItemCreate);

这种方式可以保留项目现有的 Axios 实例、拦截器和鉴权流程。Axios 实例不能直接传给生成客户端的 fetch 配置,因为两者的调用接口不同。

配合现有 Fetch 请求封装

import type { Item } from './api/types';

const response = await fetch('/api/items?skip=0&limit=20');
if (!response.ok) {
  throw new Error(`请求失败: ${response.status}`);
}

const items: Item[] = await response.json();

只使用生成类型时,错误处理、请求取消、拦截器和 SSE 仍由项目自己的 HTTP 层负责。

CLI 命令

fastapi-ts generate

从 OpenAPI schema 生成 TypeScript 类型定义和独立客户端。

| 选项 | 说明 | 默认值 | | --- | --- | --- | | -i, --input <url\|path> | OpenAPI schema 的 URL 或本地文件路径 | http://localhost:8000/openapi.json | | -o, --output <dir> | 输出目录 | ./src/api | | -n, --name <name> | 生成的客户端变量名 | api | | --base-url <url> | 请求基础路径,覆盖 OpenAPI servers | - | | -w, --watch | 监听 schema 变化并重新生成 | false |

别名:fastapi-ts gen。

fastapi-ts init

在当前目录创建初始 fastapi-ts.config.json 配置文件:

npx fastapi-ts-sdk init

客户端 API

createFastAPIClient<Paths>(config)

生成的 client.ts 会导出此工厂函数和一个已配置的客户端实例。如需定义自己的客户端,可以在独立文件中导入工厂函数,无需修改生成文件:

import { createFastAPIClient } from './api/client';
import type { Paths } from './api/types';

export const api = createFastAPIClient<Paths>({
  baseUrl: '/api',
  credentials: 'include',
  headers: async (): Promise<Record<string, string>> => {
    const token = localStorage.getItem('token');
    return token ? { Authorization: `Bearer ${token}` } : {};
  },
  beforeRequest: (init, url) => {
    console.debug('请求地址:', url);
    return init;
  },
  onError: (error) => {
    console.error(error.status, error.message);
  },
});

ClientConfig

| 字段 | 类型 | 说明 | | --- | --- | --- | | baseUrl | string | 请求基础路径 | | headers | Record<string, string> \| (() => ...) | 静态请求头,或同步/异步请求头工厂函数 | | credentials | RequestCredentials | Fetch credentials 模式,例如 include | | fetch | typeof fetch | 可选的 Fetch 兼容实现 | | onError | (error: ApiError) => void | 全局错误回调 | | beforeRequest | (init, url) => RequestInit | 请求拦截器,可返回 Promise | | afterResponse | (response) => Response | 响应拦截器,可返回 Promise |

请求方法

客户端提供 get、post、put、patch、del、request 和 stream 方法。

await api.get('/items/{item_id}', {
  path: { item_id: 1 },
  query: { verbose: true },
});

await api.post('/items', {
  body: { name: '示例' },
});

await api.post('/upload', {
  form: { file: fileObject },
});

const controller = new AbortController();
await api.get('/slow-endpoint', { signal: controller.signal });

SSE 流式响应

const close = api.stream('post', '/chat', {
  body: { message: '你好', stream: true },
  onMessage: (message) => {
    console.log(message.event, message.data);
  },
  onError: (error) => console.error(error),
  onOpen: () => console.log('连接已建立'),
  onClose: () => console.log('连接已关闭'),
  reconnect: true,
  maxRetries: 5,
});

close();

JSON 事件数据会尽可能自动解析,其他事件数据保持为字符串。

ApiError

ApiError 包含 status、statusText、data、url 和 method 属性。

同时提供以下类型守卫:

  • isUnauthorized(error):判断 HTTP 401
  • isForbidden(error):判断 HTTP 403
  • isNotFound(error):判断 HTTP 404
  • isValidationError(error):判断 HTTP 422
  • isServerError(error):判断 HTTP 5xx

直接从生成代码中导入:

import { ApiError } from './api/client';

编程式生成

也可以在 Node.js 脚本或构建任务中调用生成器:

import { generate } from 'fastapi-ts-sdk/generator';

await generate({
  input: 'http://localhost:8000/openapi.json',
  outputDir: './src/api',
  clientName: 'api',
  baseUrl: '/api',
});

此导入仅用于开发阶段的代码生成,生成后的前端不需要它。

License

MIT