@kallinen/openapi-axios-client
v0.5.2
Published
A lightweight TypeScript library to generate fully typed API clients from OpenAPI specifications.
Readme
OpenAPI Axios Client
This library leverages OpenAPI types to create a fully typed client API, providing a consistent interface with your backend services.
Installation
This package can be installed in any JS/TS project.
npm install @kallinen/openapi-axios-clientBasic usage
Types can be generated with following command
npx @kallinen/openapi-typings-gen spec.json > spec.tsCreating a new API
import spec from '<path to openapi json>'
const config = {
url: 'localhost:3000',
timeout: 30000,
headers: {}
}
const api = createTypedApi<OperationMethods, PathsDictionary>(spec, {
url: config.url,
timeout: config.timeout,
headers: config.headers,
})
const anotherApi = await createTypedApi<OperationMethods, PathsDictionary>('path/to/json', {
url: config.url,
timeout: config.timeout,
headers: config.headers,
})
const remoteApi = await createTypedApi<OperationMethods, PathsDictionary>('https://example.com/openapi.json', {
url: config.url,
timeout: config.timeout,
headers: config.headers,
})Applying validation to API responses
⚠️ This feature is experimental and may change in future releases.
import { apiResponseValidators } from /path/to/generated/types
const clientValidatedApi = await createTypedApi<OperationMethods, PathsDictionary>('https://example.com/openapi.json', {
url: config.url,
timeout: config.timeout,
headers: config.headers,
validators: apiResponseValidators
})
Api calls
const response = await api.getTodos({ id: 1 })
if (response.ok) {
// Handle successful api call
handleSuccess(response.data)
} else {
// Handle errors. Response contains originalError, statusCode and problem.
}