- Installation
- Getting Started
- Authentication
- Class OpenAPIClientAxios
- Axios Client Instance
- Operation Method
- Operation Method Arguments
- Request Config Object
- Paths Dictionary
- Typegen
npm install --save openapi-client-axios
ES6 import syntax:
import OpenAPIClientAxios from 'openapi-client-axios';CommonJS require syntax:
const OpenAPIClientAxios = require('openapi-client-axios').default;The main OpenAPIClientAxios class is exported as the default export for the 'openapi-client-axios' module.
OpenAPI Client Axios uses operationIds in OpenAPIv3 definitions to call API operations.
Below is a simple example of how you would call an operation called getPets() with openapi-client-axios.
const api = new OpenAPIClientAxios({ definition: './petstore.yml' });
const client = await api.init();
const res = await client.getPets(); // res.data will contain the result of the API callOpenAPI Client Axios can be used both in the browser or in the backend on Node.js.
In the browser, you generally want let the browser handle authentication for you, so make sure to initalise your
OpenAPIClientAxios with withCredentials: true so axios knows automatically to send cookies to the API.
// in the browser
const api = new OpenAPIClientAxios({
definition,
axiosConfigDefaults: {
withCredentials: true,
},
});With Node.js, you will need to handle authentication yourself. Make sure to send the appropriate headers alongside your requests. Here is an example of simple API key authentication:
// on Node.js
const api = new OpenAPIClientAxios({
definition,
axiosConfigDefaults: {
headers: {
'x-api-key': 'secret',
},
},
});OpenAPIClientAxios is the main class of this module. However, it's entire purpose is to create an axios client instance configured to consume an API described by the OpenAPI definition.
Creates an instance of OpenAPIClientAxios and returns it.
Example:
const api = new OpenAPIClientAxios({
definition: './openapi.yml',
withServer: 0,
axiosConfigDefaults: {
withCredentials: true,
headers: {
'Cache-Control': 'no-cache',
},
},
});Constructor options
The OpenAPI definition as a file path or Document object.
Type: Document | string
The default server to use. Either by index, description or a full server object to override with.
Type: number, string or [Server Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#serverObject
Optional. Default axios config for the instance. Applied when instance is created.
Type: AxiosRequestConfig
Optional. Override the default method name resolution strategy (default: use operationId as method name)
Type: (operationId: string) => string
For typegen: You can pass the transformOperationName using the -t ot --transformOperationName command line flag.
Optional. Transforms the returned operation method (default: do not transform)
Type: (operationMethod: UnknownOperationMethod, operationToTransform: Operation) => UnknownOperationMethod
The operation is also provided to the function, such that you can also conditionally transform the method.
Example:
const api = new OpenAPIClientAxios({
definition: 'https://example.com/api/openapi.json',
transformOperationMethod: (operationMethod, operation) => {
return (params, body, config) => {
// set default workspaceId for all operations
params.workspaceId = '63e90965-07a7-43b3-8f5d-d2e8fa90e8d0';
return operationMethod(params, body, config);
}
}
});Initalizes OpenAPIClientAxios
Returns a promise of the created member axios instance.
- Parses the input definition into a JS object. If the input definition is a URL, it will be resolved
- Dereferences the definition for use. Will resolve any remote $refs
- Creates the member axios instance
- Sets
api.initialised = trueand returns the created axios instance
Example:
await api.init();Synchronous version of .init()
Initalizes OpenAPIClientAxios and creates the axios client instance.
Note: Only works when the input definition is a valid OpenAPI v3 object and doesn't contain any remote $refs.
Example:
api.initSync();Returns a promise of the member axios instance. Will run .init() if API is not initalised yet.
Example:
const client = await api.getClient();Set the default server base url to use for client.
The default server to use. Either an index, description or a full server object to override with.
Example:
// by index
api.withServer(1);
// by description property
api.withServer('EU server');
// by server object (override)
api.withServer({ url: 'https://example.com/api/', description: 'Eu Server' });Type: number, string or Server Object
Gets the API baseurl defined in the servers property
Example:
const baseURL = api.getBaseUrl();
const baseURLForOperation = api.getBaseUrl('operationId');Optional. The Operation object or operationId that may override the baseURL with its own or path object's servers property.
Type: Operation or string (operationId)
Creates a generic request config object for operation + arguments top be used for calling the API.
This function contains the logic that handles operation method parameters.
Example:
const request = api.getRequestConfigForOperation('updatePet', [1, { name: 'Odie' }])The operation to call. Either as an operation object or string (operationId).
Type: Operation or string (operationId)
The operation method arguments.
Type: OperationMethodArguments
Creates a new axios instance, extends it and returns it.
While initalising with .init() or .initSync() OpenAPIClientAxios calls this function to create the member client.
Note: Requires the API to be initalised first if run outside of .init() methods.
Creates an axios config for operation + arguments to be used for calling the API.
This function calls .getRequestConfigForOperation() internally and maps the values to be suitable for axios.
Returns an AxiosRequestConfig object
Example:
const request = api.getAxiosConfigForOperation('getPets', [{ petId: 1 }])The operation to call. Either as an operation object or string (operationId).
Type: Operation or string (operationId)
The operation method arguments.
Type: OperationMethodArguments
When OpenAPIClientAxios is initalised, a member axios client instance is created.
The client instance can be accessed either directly via api.client getter, or api.getClient().
The member axios client instance is a regular instance of axios with Operation Methods created to provide an easy JavaScript API to call API operations.
In addition to operation methods, the Axios client instance baseURL is pre-configured to match the first OpenAPI definition servers property.
The parent OpenAPIClientAxios instance can also be accessed from the client via client.api.
Operation methods are the main API used to call OpenAPI operations.
Each method is generated during .init() and is attached as a property to the axios client instance.
Each operation method takes three arguments:
client.operationId(parameters?, data?, config?)The first argument is used to pass parameters available for the operation.
// GET /pets/{petId}
client.getPet({ petId: 1 })For syntactic sugar purposes, you can also specify a single implicit parameter value, in which case OpenAPIClientAxios will look for the first required parameter for the operation. Usually this is will be a path parameter.
// GET /pets/{petId} - getPet
client.getPet(1)Alternatively, you can explicitly specify parameters in array form. This method allows you to set custom parameters not defined in the OpenAPI spec.
// GET /pets?search=Garfield - searchPets
client.searchPets([{ name: 'search', value: 'Garfield', in: 'query' }])The type of the parameters can be any of:
- query
- header
- path
- cookie
The second argument is used to pass the requestPayload
// PUT /pets/1 - updatePet
client.updatePet(1, { name: 'Odie' })More complex payloads, such as Node.js streams or FormData supported by Axios can be used.
The first argument can be set to null if there are no parameters required for the operation.
// POST /pets - createPet
client.updatePet(null, { name: 'Garfield' })The last argument is the config object.
The config object is an AxiosRequestConfig object. You can use it to
override axios request config parameters, such as headers, timeout, withCredentials and many more.
// POST /user - createUser
client.createUser(null, { user: 'admin', pass: '123' }, { headers: { 'x-api-key': 'secret' } });A RequestConfig object gets created as part of every operation method call.
It represents a generic HTTP request to be executed.
A request config object can be created without calling an operation method using
.getRequestConfigForOperation()
import { RequestConfig } from 'openapi-client-axios';Example object
const requestConfig = {
method: 'put', // HTTP method
url: 'http://localhost:8000/pets/1?return=id,name', // full URL including protocol, host, path and query string
path: '/pets/1', // path for the operation (relative to server base URL)
pathParams: { petId: 1 }, // path parameters
query: { return: ['id', 'name'] }, // query parameters
queryString: 'return=id,name', // query string
headers: {
'content-type': 'application/json;charset=UTF-8',
'accept': 'application/json' ,
'cookie': 'x-api-key=secret',
}, // HTTP headers, including cookie
cookies: { 'x-api-key': 'secret' }, // cookies
payload: {
name: 'Garfield',
age: 35,
}, // the request payload passed as-is
}In addition to operationIds, OpenAPIClient also allows calling operation methods, using the operations' path and HTTP method.
The paths dictionary contains each path found in the OAS definition as keys, and an object with each registered operation method as the value.
Example:
client.paths['/pets'].get(); // GET /pets, same as calling client.getPets()
client.paths['/pets'].post(); // POST /pets
client.paths['/pets/{petId}'].put(1); // PUT /pets/1
client.paths['/pets/{petId}/owner/{ownerId}'].get({ petId: 1, ownerId: 2 }) ; // GET /pets/1/owner/2This allows calling operation methods without using their operationIds, which may be sometimes preferred.
openapi-client-axios comes with a tool called typegen to generate typescript type files (.d.ts) for
OpenAPIClient instances using an OpenAPI definition file.
$ npm install -g openapi-client-axios-typegen
$ typegen
Usage: typegen [file]
Options:
--help Show help [boolean]
--version Show version number [boolean]
Examples:
typegen ./openapi.yml > client.d.ts - generate a type definition file
The output of typegen exports a type called Client, which can be used for client instances.
Both the .getClient() and api.init() methods support passing in a Client type.
import { Client as PetStoreClient } from './client.d.ts';
const client = await api.init<PetStoreClient>();
const client = await api.getClient<PetStoreClient>();typegen supports using both local and remote URLs for OpenAPI definition files.
$ typegen ./petstore.yaml
$ typegen https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml
You can also use the typegen functionality in a programmatic way!
import { generateTypesForDocument } from 'openapi-client-axios'
const typesFileContent = (await generateTypesForDocument(document)).join('\n')