TS-Swagger plugin generator CLI
CLI to generate Axios or other API client from Swagger schema
npm i -D tswagger
in project directory
npx tswagger https://petstore3.swagger.io/api/v3/openapi.json
in 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/bar
npx tswagger https://api.server.foo/swagger.json --mode request
import { createApi } from './lib/api'
const fetchApi = createApi((path, method, { params, formData, body }) => {
const url = new URL(`http://localhost${path}`)
const url.searchParams = (...)
return fetch(url, {
method,
body: formData ?? body ?? JSON.stringify(body),
})
}, response => 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": "..."
}
}
ISC License Copyright (c) 2023, Elevista