Using swagger-typescript-api to Generate Request Code in Frontend Projects
swagger-typescript-api? The docs read like a draft, so you still have to figure it out yourself. Those fancy modular options—what do they do besides throw errors? Just generate a single file, wrap it in a client, and save yourself the hassle every time.
目录4 个章节
Introduction
This swagger-typescript-api tool is pretty decent—it can generate TypeScript request code from a Swagger document
It includes type annotations, but unfortunately the docs aren't very detailed. I'm recording how to use it here so I don't have to search every time I generate code
Official docs: https://acacode.github.io/swagger-typescript-api/
Commands
Basic usage
npx swagger-typescript-api generate -p http://localhost:5000/swagger/v1/swagger.json -o src/api -n index.ts
If you're using bun, replace npx with bunx
After testing, I found that using this most basic command and putting all endpoints in a single file actually works best. Other options like --modular for modularization often cause the generated code to throw errors.
Available CLI Options Overview
(Compiled from the official docs and Fig.io)
-v,--versionOutput the current tool version-p,--path <路径或 URL>Specify the location of the Swagger/OpenAPI document (local path or network URL)-o,--output <目录路径>Directory for generated files (default./)-n,--name <文件名>Specify the output TypeScript API filename (defaultApi.ts)-t,--templates <模板路径>Use custom EJS templates to render the generation logic-d,--default-as-successAlso treat"default"response status codes as success responses (some Swagger specs usedefault), defaultfalse-r,--responsesGenerate extra request response information, including typings for error types--union-enumsGenerate all enums as TypeScript union types (T1 | T2 | TN)--add-readonlyAdd thereadonlymodifier to generated properties--route-typesGenerate type definitions related to API routes (such as parameter types)--client/--no-clientWhether to generate the API client class (default--client); using--no-clientgenerates only the types/data layer--enum-names-as-valuesUsex-enumNamesvalues as enum values, not just keys (defaultfalse)--extract-request-params/--extract-request-body/--extract-response-body/--extract-response-errorExtract request parameters, request body, response body, or error responses into standalone data contract types--modularSplit http client, data contracts, routes, and other code into multiple files (modular)--jsGenerate JavaScript modules and corresponding.d.tsdeclaration files--module-name-index <索引>When generating modularly, decide which part of the path to use for index grouping--module-name-first-tagSplit modules based on the API's first Tag- Network settings:
--disableStrictSSL(disable strict SSL verification)--disableProxy(disable proxy) - HTTP client selection:
--axios: generate request code with axios as the underlying client Others default to using fetch or an abstraction --unwrap-response-dataAutomatically unwrap thedatafield in the response and return the inner data directly--disable-throw-on-errorDo not throw an exception whenresponse.ok !== true(HTTP errors) (defaultfalse)--single-http-clientSupport passing in a single HTTP client instance when generating the API class (defaultfalse)- Output control:
--silent: only output error messages, otherwise silent - Type generation configuration:
--default-response <Type>: default type when the response schema is empty--type-prefix <前缀>/--type-suffix <后缀>: custom prefix/suffix for data model names - Other options:
--clean-output: clean the output directory (note: this deletes old files)--api-class-name <类名>: specify the generated API class name--patch: fix some minor errors in the Swagger source definition--debug: output extra debug information--another-array-type: generate arrays inArray<Type>form instead ofType[](defaultfalse)--sort-types: sort fields and types (defaultfalse)--extract-enums: extract all enums from inline interfaces into standalone TSenums - Help command:
--help,-h: list all command help information
Usage Example in Next.js
Taking the StarBlog API as an example
The directory structure in the Next.js project looks like this:
where photo.ts and blog.ts are generated
lib
├─ api
│ └─ starblog
│ ├─ photo.ts
│ ├─ client.ts
│ └─ blog.ts
└─ source.ts
You need to create a client.ts to make it easier to use. The code:
import { Api as BlogApi } from './blog';
import { Api as PhotoApi } from './photo';
// 直接导出类型
export type { Post, Photo, FeaturedPost, PostListApiResponse, PostApiResponsePaged } from './blog';
export type { PhotoApiResponsePaged } from './photo';
/**
* 获取API基础URL
* @param baseUrl 可选的基础URL
* @returns 最终的API基础URL
*/
function getApiBaseUrl(baseUrl?: string): string {
// 在服务端环境中,优先使用服务端API URL
return typeof window === 'undefined'
? (process.env.API_BASE_URL || baseUrl || process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:5000')
: (baseUrl || process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:5000');
}
/**
* 创建博客API客户端
* @param baseUrl 可选的基础URL
* @returns 博客API实例
*/
export function createBlogApi(baseUrl?: string): BlogApi<unknown> {
return new BlogApi({
baseUrl: getApiBaseUrl(baseUrl),
customFetch: fetch,
});
}
/**
* 创建照片API客户端
* @param baseUrl 可选的基础URL
* @returns 照片API实例
*/
export function createPhotoApi(baseUrl?: string): PhotoApi<unknown> {
return new PhotoApi({
baseUrl: getApiBaseUrl(baseUrl),
customFetch: fetch,
});
}
// 为了向后兼容,保留原有的函数名
export const createStarBlogApiClient = createBlogApi;
Making requests in a page
import {createBlogApi, createPhotoApi, Post, Photo} from '@/lib/api/starblog/client';
/**
* 获取推荐博客文章
*/
async function getFeaturedPosts(): Promise<Post[]> {
try {
const blogApi = createBlogApi();
const response = await blogApi.api.blogFeaturedList();
if (response.data?.successful && response.data?.data) {
return response.data.data;
}
return [];
} catch (error) {
console.error('获取推荐文章失败:', error);
return [];
}
}
/**
* 获取摄影作品
*/
async function getPhotos(): Promise<Photo[]> {
try {
const photoApi = createPhotoApi();
console.log('正在获取摄影作品,API基础URL:', process.env.NEXT_PUBLIC_API_BASE_URL);
const response = await photoApi.api.photoList({page: 1, pageSize: 8});
console.log('摄影作品API响应:', response.data);
if (response.data?.successful && response.data?.data) {
console.log('获取到的摄影作品数量:', response.data.data.length);
response.data.data.forEach((photo, index) => {
console.log(`摄影作品 ${index + 1}:`, {
id: photo.id,
title: photo.title,
filePath: photo.filePath,
fullUrl: `${process.env.NEXT_PUBLIC_API_BASE_URL}/media/photography/${photo.filePath}`
});
});
return response.data.data;
}
console.warn('摄影作品API响应不成功或无数据');
return [];
} catch (error) {
console.error('获取摄影作品失败:', error);
return [];
}
}
export default async function HomePage() {
// 在服务端并行获取数据
const [posts, photos] = await Promise.all([
getPosts(),
getPhotos()
]);
return (
<div>
<BlogPosts
posts={posts}
baseUrl={process.env.NEXT_PUBLIC_API_BASE_URL || ''}
/>
<PhotoGallery
photos={photos}
baseUrl={process.env.NEXT_PUBLIC_API_BASE_URL || ''}
/>
</div>
)
}
Done.
_EOF_
Using swagger-typescript-api to Generate Request Code in Frontend Projects
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
React + TypeScript + Taro前端开发小结
前言 项目到一段落,先来记录一下,本文以前端新手的角度记录React、TypeScript、Taro相关技术的开发体验以及遇到的问题和解决方法。 之前总说要学React(这篇博客:代码使我头疼之React初学习),这次项目需要做H5前端+小程序,我终于能用上React了~ 使用React的开发框架之前就听过京东的Taro,所以就这个了,直接开码。 关于React 不错,感觉比Vue的模板写法自由很
2022-04-22 · Web前端 · 约 1 分钟
NPM-Warn--ENOENT--no-such-file-or-directory
Now type the command to auto generate the package.json npm init --yes
2022-07-18 · Web前端 · 约 1 分钟
Next.js路由段配置选项笔记
Next.js的路由段配置选项?真有这么简单?官方文档写得倒是分散,自己整理下倒也罢了。动态渲染还是静态?缓存策略又该怎么定?开发者还是得自己琢磨。
2025-10-30 · Web前端 · 约 1 分钟
开始开发一个新博客了,复古风Metro风格,顺便diss一下js
emmm 我原本的博客是用wordpress搭建的,当年七牛云还是免费时用它做的CDN,但是现在收费了,如果维持目前的博客流量的话每个月都要支付不少费用,于是只好把七牛云给停了= =,这也导致我博客里面很多图片都访问不了,页面布局也出问题了,不想折腾了,而且wordpress用起来总觉得不顺手,还是自己做一个吧~ 计划 最近刚好在学SpringBoot啥的,本来想用springboot搭建一个博客
2022-07-18 · Web前端 · 约 1 分钟
讨论
共 0 条加载评论中…