swaggered
v2.6.1
Published
Generate client request code with TypeScript typings from Swagger OpenAPI JSON Schema.
Maintainers
Readme
Swaggered
从 Swagger JSON Schema 生成 TypeScript 客户端请求代码并带有严格的 TS 类型和丰富的注释。
Generate client request code with TypeScript typings and as many comments as possible from Swagger OpenAPI Schema.
Generated Example:
/** Comment about this service from schema description */
export const JobService = {
// 🔥 Grouped by path or tag, nicely organized. Give it a try by passing the `grouped` flag
prefix: '/api/model/v1/evaluate/job',
/**
* Comment about getJobDetail
*/
async getJobDetail(params: IGetJobDetailParams) {
return request<Data<IGetJobDetailResponseData>>(`${this.prefix}/${params.jobId}`, {
method: 'GET',
});
},
/**
* Comment about createJob
*/
async createJob(data: ICreateJobRequestData) {
return request<Data<ICreateJobResponseData>>(this.prefix, {
method: 'POST',
data: ICreateJobRequestData
});
},
/**
* Comment about stopJob
*/
async stopJob(params: IStopJobParams) {
return request<Data<IStopJobResponseData>>(`${this.prefix}/${params.jobId}`, {
method: 'POST',
});
},
};
// 🔥 Generate **Generic Response Type** from parsing your response structure intelligently!
type Data<T> = {
code: number;
data: T; // the response is in `data` field by default, you can change it by passing the `--data-container` flag
message: string;
}
// ... other types omittedFeatures
- [x] 🛡️ Strict TS Types: Generate client code with
strict TS typesand keep the originalcommentsintsdoc. - [x] 🔍 Filterable: You can generate only what you need using
filterbyapipath and HTTPmethod. - [x] 🤸♀️ Flexible Format:
- [x] You can generate standalone request functions or
- [x] 🔥 Grouped by path or tag. Nicely organized. Give it a try!
- [x] 🔥 Generate Generic Response Type from parsing your response structure intelligently!
- [x] 🌍 Multiple Sources: Both local file and remote URL are supported.
pnpx swaggered -i https://unoapi.codingmo.com/api/dd-openapi-v31.json --api 'topapi/v2/user/[c|u]'will generate code fortopapi/v2/user/createandtopapi/v2/user/updatefrom remote URL. - [x] 🔒 Respect JSON Schema Constraints: Respect
minLength,maxLength,minimum,maximum,exclusiveMinimum,exclusiveMaximum, andrequiredproperties of your OpenAPI specification. - [x] 🎨 Pretty Print: 🔥 Highlight output with
shikijs. - [x] ⚔️ Battlefield tested:
- [x] Support all Swagger OpenAPI versions and Node.js from
v16tov22. - [x] Unit testing & E2E testing: Coverage (2025-12-5) all files
line: 96, branch: 89, funcs: 99.
- [x] Support all Swagger OpenAPI versions and Node.js from
- [x] 🤹♂️ Flexible Usage: Can be used through CLI or programmatically.
Get Started
1. Use CLI RECOMMENDED
Generate request code with api path match foo only:
Output to stdout
pnpx swaggered --input ./assets/openapi.json --api fooCopy to clipboard
# macOS
pnpx swaggered --input ./assets/openapi.json --api foo | pbcopy
# Windows
pnpx swaggered --input ./assets/openapi.json --api foo | clipSave to file
pnpx swaggered --input ./assets/openapi.json --api foo > ./src/service/foo.ts┌───────────────┬───────────┬───────┬──────────────────────────────────────────────────────┬──────────┬─────────┐
│ (index) │ type │ short │ description │ required │ default │
├───────────────┼───────────┼───────┼──────────────────────────────────────────────────────┼──────────┼─────────┤
│ help │ 'boolean' │ 'h' │ 'Show this help message' │ '×' │ false │
│ input │ 'string' │ 'i' │ 'Input file path of swagger json' │ '√' │ │
│ api │ 'string' │ 'a' │ 'Generate typings match the API path' │ '×' │ '*' │
│ method │ 'string' │ 'm' │ 'Generate code match the HTTP method' │ '×' │ '*' │
│ debug │ 'boolean' │ 'd' │ 'Print debug info' │ '×' │ false │
│ types-only │ 'boolean' │ 't' │ 'Generate only types' │ '×' │ false │
│ function-only │ 'boolean' │ 'f' │ 'Generate only functions' │ '×' │ false │
│ return-type │ 'boolean' │ 'r' │ 'Explicitly specify return type of function' │ '×' │ true │
│ grouped │ 'boolean' │ 'g' │ 'Print functions by group' │ '×' │ true │
│ use-interface │ 'boolean' │ │ 'Generate interface instead of type' │ '×' │ false │
│ request │ 'boolean' │ │ 'Generate request function. `no-request` to disable' │ '×' │ false │
└───────────────┴───────────┴───────┴──────────────────────────────────────────────────────┴──────────┴─────────┘inputis required only.groupedis my favorite flag, it will generate request functions by group. Give it a try!
2. Use programmatically. generateTSFromSchema
import { prettyPrint, generateTSFromSchema } from 'swaggered';
const result = await generateTSFromSchema({
openapi: '3.0.1',
info: {
title: 'OpenAPI definition',
version: 'v0',
},
servers: [
{
url: 'http://127.0.0.1:8000',
description: 'Generated server url',
},
],
paths: {
'/api/bar/v1/baz/foo/list': {
get: {
tags: ['foo的相关接口'],
summary: '分页查询foo作业',
description: '分页查询foo作业',
operationId: 'listFoo',
parameters: [
{
name: 'req',
in: 'query',
required: true,
schema: {
$ref: '#/components/schemas/PageRequest',
},
},
],
responses: {
200: {
description: '服务Okay,但请求是否成功请看返回体里面的code',
content: {
'*/*': {
schema: {
$ref: '#/components/schemas/ResponsePageVOEvaluateFooResp',
},
},
},
},
},
},
},
},
components: {
schemas: {
PageRequest: {
required: ['current', 'pageSize'],
type: 'object',
properties: {
current: {
minimum: 1,
type: 'integer',
description: 'current',
format: 'int32',
},
pageSize: {
maximum: 1000,
type: 'integer',
description: 'pageSize',
format: 'int32',
},
},
},
EvaluateFooResp: {
type: 'object',
properties: {
id: {
type: 'integer',
format: 'int64',
},
name: {
type: 'string',
},
description: {
type: 'string',
},
status: {
type: 'string',
enum: ['XX', 'YY', 'COMPLETED', 'FAILED'],
},
bars: {
type: 'array',
items: {
type: 'string',
},
},
},
},
PageVOEvaluateFooResp: {
type: 'object',
properties: {
total: {
type: 'integer',
format: 'int64',
},
pageSize: {
type: 'integer',
format: 'int32',
},
current: {
type: 'integer',
format: 'int32',
},
list: {
type: 'array',
items: {
$ref: '#/components/schemas/EvaluateFooResp',
},
},
},
},
ResponsePageVOEvaluateFooResp: {
type: 'object',
properties: {
code: {
type: 'integer',
format: 'int32',
},
data: {
$ref: '#/components/schemas/PageVOEvaluateFooResp',
},
errorMsg: {
type: 'string',
},
success: {
type: 'boolean',
},
},
},
},
},
});
await prettyPrint(result);3. Use programmatically. Generate from file and prettyPrint automatically
import { swaggerToTS } from 'swaggered';
await swaggerToTS({
input: swaggerJsonFilepath,
api: 'baz',
// method: '*',
});4. Use Programmatically. Generate from file and prettyPrint result or do whatever you want
import { generateTSFromFile, prettyPrint } from 'swaggered';
const result = await generateTSFromFile(filepath, {
typesOnly: false,
filter: {
api,
method,
},
});
prettyPrint(result, { debug, typesOnly });interface IResult {
list: IGeneratedItem[];
total: number;
}
interface IGeneratedItem
/** API path */
path: string;
/** HTTP method */
method: string;
/** HTTP request parameters type */
requestParametersType: string;
/** HTTP request body type */
requestBodyType: string;
/** HTTP response type */
responseType: string;export async function list(params: PagedQueryBarsParams) {
return request<Data<PagedQueryBarsResponseData>>('/api/foo/v1/bars', {
method: 'GET',
params,
});
}
type Data<T> = {
code: number;
data: T;
message: string;
};
interface PagedQueryBarsParams {
/**
* 页码,必填,必须大于0
*/
page_number: number;
/**
* 每页数量,必填,必须大于等于1且小于21
*/
page_size: number;
/**
* bar name,模糊匹配,可空
*/
bar_name?: string | null;
/**
* bar状态,0:未激活,1:激活,2:已过期,3:已删除,可为空,也可以包含一个或多个
*/
status_list?: ("0" | "1" | "2" | "3")[] | null;
/**
* bar开始时间,可为空
*/
start_time?: string | null;
/**
* bar结束时间,可为空
*/
end_time?: string | null;
}
interface BaseResponsePagedQueryBarsResponse {
code: number;
message?: string | null;
data?: PagedQueryBarsResponseData | null;
}
interface PagedQueryBarsResponseData {
/**
* bars总数
*/
total: number;
bars: GetBarResponseData[];
}
interface GetBarResponseData {
/**
* bar id,必定存在
*/
bar_id: number;
/**
* bar name,必定存在
*/
bar_name: string;
/**
* bar的创建时间,必定存在
*/
created_time: string;
/**
* bar的上次更新时间,必定存在
*/
updated_time: string;
}Develop
npmas package manager.- start dev
node bin.mjs -i path/to/your/openapi-xxx.json --no-request --debug
# openapi v3
node bin.mjs -i https://petstore3.swagger.io/api/v3/openapi.json --api pet -m put
# swagger v2
node bin.mjs -i https://petstore.swagger.io/v2/swagger.json --api pet -m put- Testing: use node builtin test and coverage
node --test --experimental-test-coverage - Linting and Formatting: powered by biome
Credits
Thanks to:
- json-schema-to-typescript Compile JSON Schema to TypeScript typings.
- @apidevtools/json-schema-ref-parser Parse, Resolve, and Dereference JSON Schema $ref pointers.
- json-schema-traverse Traverse JSON Schema passing each schema object to callback.
- @shikijs/cli A CLI for shiki, A beautiful syntax highlighter based on TextMate grammars, accurate and powerful.
