Package Exports
- openapi-client-axios
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (openapi-client-axios) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
OpenAPI Client Axios
JavaScript client library for consuming OpenAPI-enabled APIs with axios
Features
- Create API clients by describing them in OpenAPI specification and importing them via YAML or JSON files or by just passing an object
- Call API operations with your preferred syntax:
client.updatePet(1, pet)
- operation methodsclient.query('updatePet', 1, pet)
- query methodclient.put('/pets/1', pet)
- axios method aliasesclient({ method: 'put', url: '/pets/1', data: pet })
- axios basic
- Built on top of the robust axios JavaScript library
- Isomorphic, works both in browser and Node.js
- Option to mock API backends using openapi-backend
- TypeScript types included
Quick Start
npm install --save openapi-client-axios
With promises / CommonJS syntax:
const OpenAPIClientAxios = require('openapi-client-axios').default;
const api = new OpenAPIClientAxios({ definition: 'https://example.com/api/openapi.json' });
api.init()
.then(client => client.getPetById(1))
.then(res => console.log('Here is pet id:1 from the api', res.data));
With async-await / ES6 syntax:
import OpenAPIClientAxios from 'openapi-client-axios';
const api = new OpenAPIClientAxios({ definition: 'https://example.com/api/openapi.json' });
api.init();
async function createPet() {
const res = await api.client.createPet({ name: 'Garfield' });
console.log('Pet created', res.data);
}
Calling API operations
After initalizing OpenAPIClientAxios
, an axios instance extended with OpenAPI capabilities is exposed.
Example:
const api = new OpenAPIClientAxios({ definition: 'https://example.com/api/openapi.json' });
api.init().then((client) => {
// ...
});
The exposed client
is an axios instance initalized with
baseURL from OpenAPI definitions and extended with extra methods for calling API operations.
There are four different ways to call API operations:
client.updatePet(1, pet)
- operation methodsclient.query('updatePet', 1, pet)
- query methodclient.put('/pets/1', pet)
- axios method aliasesclient({ method: 'put', url: '/pets/1', data: pet })
- axios basic
Example:
const api = new OpenAPIClientAxios({
definition: {
openapi: '3.0.1',
info: {
title: 'Petstore',
version: '1.0.0',
},
servers: [{ url: 'http://localhost:9000' }], // petstore api
paths: {
'/pets': {
get: {
operationId: 'getPets',
responses: {
200: { description: 'ok' },
},
},
},
},
},
});
async function test() {
const client = await api.init();
const res1 = await client.getPets();
const res2 = await client.query('getPets');
const res3 = await client.get('/pets');
const res4 = await client({ method: 'get', url: '/pets' });
assert.deepEqual(res1.data, res2.data);
assert.deepEqual(res1.data, res3.data);
assert.deepEqual(res1.data, res4.data);
}
test();
Operation methods
OpenAPIClientAxios operation methods take in 3 types of arguments:
client.operationId(pathParams?, data?, config?)
Path params
The first argument is the path parameters for the operation.
// GET /pets/{petId} - getPet
client.getPet(petId)
If the operation requires more than a single path parameter, use an object or an array.
Note that when using an array, the parameters should be in the same order as they appear in the path template of the operation.
// GET /pets/{petId}/owner/{ownerId} - getPetOwner
client.getPetOwner({ petId, ownerId })
// or
client.getPetOwner([petId, ownerId])
If no path parameters are required for the operation, the first argument is the data / payload argument (next section).
Data / Payload
The next argument the path parameters is the data argument. This allows you to send request body payloads with your API call.
// PUT /pets/1 - updatePet
client.updatePet(1, { name: 'Odie' })
If there are no path parameters for the operation, the data argument will be the first argument.
// POST /pets - createPet
client.createPet({ name: 'Garfield' })
Config object
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
, params
, timeout
, withCredentials
and many more.
// PUT /pets/1?fields=name - updatePet
client.updatePet(1, { name: 'Odie' }, { params: { fields: 'name' } });
If there are no path or data parameters for the operation, the config argument will be the first argument.
// GET /pets?query=dog - searchPets
client.searchPets({ params: { query: 'dog' } });
Any arguments passed after the config object will cause OpenAPI backend to throw an Error.
Mocking with OpenAPI Backend
Combining openapi-client-axios
with openapi-backend
allows you to
easily mock your API backend while developing client applications.
OpenAPI Backend uses OpenAPI examples objects
and JSON Schema definitions
to mock responses using your OpenAPI specification document. Routing and input validation is also automatically enabled
when using the handleRequest()
method.
Example:
import OpenAPIClientAxios from 'openapi-client-axios';
import OpenAPIBackend from 'openapi-backend';
const definition = './openapi.yml';
// create the mock API
const mockApi = new OpenAPIBackend({ definition });
mockApi.register({
notFound: () => [404, { err: 'not found' }],
validationFail: (c) => [400, { err: c.validation.errors }],
notImplemented: (c) => {
const { status, mock } = mockApi.mockResponseForOperation(c.operation.operationId);
return [status, mock];
},
});
// create the client with a mockHandler using OpenAPIBackend.handleRequest()
const api = new OpenAPIClientAxios({
definition,
mockHandler: (config) =>
mockApi.handleRequest({
method: config.method,
path: config.url,
query: config.params,
body: config.data,
headers: config.headers,
}),
});
// init both the mock api backend and the client
mockApi.init()
.then(() => api.init())
.then((client) => {
// all calls using OpenAPIClient will now be handled by the mocked OpenAPI backend
});
Contributing
OpenAPI Client Axios is Free and Open Source Software. Issues and pull requests are more than welcome!