TS-Swagger plugin generator CLI
CLI to generate Axios or other API client from Swagger schema
npm i -D tswaggerin project directory
npx tswagger https://petstore3.swagger.io/api/v3/openapi.jsonin script code
import { createApi } from './lib/api'
const api = createApi()
const foo = await api.foo.bar(1).post(requestBody) // Post /foo/{bar}
api.foo.bar.get() // GET /foo/barnpx tswagger https://api.server.foo/swagger.json --mode requestimport { createApi } from './lib/api'
const fetchApi = createApi((path, method, { params, formData, body }) => {
const url = new URL(`http://localhost${path}`)
// url.search = qs.stringify(params, { arrayFormat: 'brackets' })
return fetch(url, {
method,
body: formData ?? (body && JSON.stringify(body)),
})
}, response => {
if (response.status >= 400) throw new Error(...)
return response.json()
})
const {data} = await fetchApi.foo.bar(1).get(2) // GET /foo/{bar}
fetchApi.foo.bar.get() // GET /foo/bar
import axios, { AxiosError } from 'axios'
const axiosApi = createApi((path, method, { params, formData, body }) =>
axios({ url: path, method, params, data: formData ?? body }),
response => response.data)
const {data} = axiosApi.foo.bar(1).get(2)npx tswagger argument1 --option1 value1 --option2 value2| option | description | default | example |
|---|---|---|---|
| (first argument) | Swagger schema JSON path | (required) | http://.. or ./foo/swagger.json |
src |
same as first argument | first argument | same as above |
mode |
Code generation mode | axios |
request |
path |
Output path | lib/api |
api.ts |
export-name |
Export name | createApi |
''(export default) |
type-path |
Path for scheme type file | {dir of path}/types.ts |
./types/models.ts |
tag |
Tags to generate | (All tags) | --tag AA --tag BB |
Options can be an array
// import { TSwaggerOptions } from 'tswagger'
export default { src: '...' } // satisfies Partial<TSwaggerOptions>{
"tswagger": {
"src": "..."
}
}TSwagger supports only a subset of the OpenAPI / JSON Schema spec on purpose. The scope is based on what Spring (springdoc-openapi) and NestJS (@nestjs/swagger) generate.
- HTTP methods: only
get,post,put,patch,delete.head,optionsare skipped. - Parameters:
headerandcookieparameters are ignored. - Parameter
style,contentare not supported. - Request body: only
application/jsonandmultipart/form-data. - Response and error: only
application/jsonis used. Responses with other content types are typed asunknown. - Swagger 2.0: response and error types are not generated (typed as
unknown). $ref: only local references. External references are not supported.
typeproperties/itemsare used only withtype: 'object'/type: 'array'.typearray is supported only in the[type, 'null']form (either order), as another way to writenullable: true. In other forms such as['string', 'number'], only the first non-nulltype is used.
format: onlybinaryandbyteare used (asFile). Other formats are ignored.allOf/oneOf/anyOf- Only one is used when combined, in order of
allOf→oneOf→anyOf. anyOf: more than 4$refs, or any schema other than primitives and$refs, becomePartial<A & B & ...>.constwithouttypeis not treated as a primitive schema here, so it ends up inPartial<A & B & ...>.
- Only one is used when combined, in order of
- Keywords next to
$refare ignored, exceptnullable. additionalProperties: trueor{}is ignored.- Excluded:
prefixItems,patternProperties,not,discriminator,readOnly,writeOnly, and validation keywords such asminimum,maxLength,pattern,minItems. - TSDoc: only the values of
examplesare written.
Schema features Spring and NestJS can generate that TSwagger limits or excludes.
| Feature | Spring | NestJS | TSwagger |
|---|---|---|---|
type array |
types = {"string", "null"} (3.1) |
type?: string | string[] |
[type, 'null'] form only (either order) |
patternProperties |
patternProperties (3.1) |
Available | Excluded |
prefixItems |
prefixItems (3.1) |
Not available | Excluded |
discriminator |
discriminatorProperty / Mapping |
discriminator |
Excluded |
not, readOnly, writeOnly |
Available | Available | Excluded |
(3.1): Spring generates it only with springdoc.api-docs.version=openapi_3_1.
Sources: swagger-core @Schema, @nestjs/swagger SchemaObject, NestJS types and parameters
ISC License Copyright (c) 2023, Elevista