Using the typescript-axios template
The typescript-axios template outputs a client SDK based on the axios that gives the following:
- Typed methods to call each endpoint
- Optionally, runtime response validation
It follows the standard axios pattern of rejecting any response that isn’t 2xx and thus can’t provide typed
error responses. If you’d like to have strong typing over your error responses consider using the typescript-fetch template.
Runtime request parameter validation is not currently supported.
See integration-tests/typescript-axios for more samples.
Install dependencies
First install the CLI and the required runtime packages to your project:
npm i --save-dev @nahkies/openapi-code-generator
npm i --save axios @nahkies/typescript-axios-runtimeSee also quick start guide
Run generation
Experimental support for runtime response validation is available behind the --enable-runtime-response-validation
flag.
Typespec
npm exec -- openapi-code-generator \
--input ./openapi.yaml \
--input-type openapi3 \
--output ./src/clients/some-service \
--template typescript-axios \
--schema-builder zod-v4Using the generated code
Running the above will output these files into ./src/clients/some-service:
./client.ts: exports a classApiClientthat implements methods for calling each endpoint./models.ts: exports typescript types./schemas.ts: exports runtime parsers using the chosenschema-builder(by default, usingzod)
Once generated usage should look something like this:
const client = new ApiClient({
// Pass a axios instance if you wish to use interceptors for auth, logging, etc
// axios: axios.create({...}),
basePath: `http://localhost:${address.port}`,
defaultHeaders: {
"Content-Type": "application/json",
Authorisation: "Bearer: <TOKEN>", // can pass auth headers here
},
})
// rejects if status code isn't 2xx, following typical axios behavior
const res = await client.createTodoListItem({
listId: list.id,
requestBody: {content: "test item"},
// optionally pass a timeout (ms), or any arbitrary axios options
// timeout?: number,
// opts?: AxiosRequestConfig
})
// data will be typed correctly
console.log(`id is: ${res.data.id}`)Escape Hatches - raw AxiosRequestConfig handling
For most JSON based API’s you shouldn’t need to reach for this, but there are sometime situations where the code generation tooling doesn’t support something you need (see also roadmap / compatibility).
To account for these situations, we accept a raw AxiosRequestConfig on client methods, that can be used
to override any of the request configuration.
Additionally, the result is a normal AxiosResponse exposing all available properties.
const res = await client.createTodoListItem({/**/}, undefined, {
maxRedirects: 1
// all axios request configuration can be overridden here
})