Promise based HTTP client for browsers and React-Native based on fetch API
- Make HTTP request using fetch API
- Supports the Promise API
- Intercept request and response
- Cancel requests
- Automatic transforms for JSON data
$ yarn add api
$ npm install api
Performing a GET
request
import api from 'api'
// Make a request for a user with a given ID
api.request({
endpoint: 'users/?offset=0&limit=20',
method: 'GET'
})
.then(function (response) {
// handle success
})
.catch(function (error) {
// handle error
})
.finally(function () {
// always executed
})
// Optionally the request above could also be done as
api.get('users', {
params: {
offset: 0,
limit: 20
}
})
.then(function (response) {
// handle success
})
.catch(function (error) {
// handle error
})
.finally(function () {
// always executed
})
Performing a POST
request
api.post('users', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
// handle success
})
.catch(function (error) {
// handle error
});
Requests can be made by passing the relevant config to api
.
api({
method: 'get',
url: '/users/:uuid?',
params: {
uuid: 'ted'
}
})
.then(function (response) {
// handle success
});
For convenience aliases have been provided for all supported request methods.
You can create a new instance of api with a custom config.
import { createInstance } from 'api'
const instance = createInstance({
baseURL: 'https://domain.com/api/'
});
These are the available config options for making requests.
{
// `endpoint` is the server URL that will be used for the request
endpoint: '/users',
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
offset: 0,
limit: 20,
uuid: 'test'
},
// `paramsSerializer` is an optional function in charge of serializing `params`
paramsSerializer: function (params) {
return buildQueryParams(params)
},
// `method` is the request method to be used when making the request
method: 'get',
// `baseURL` will be prepended to `url`.
baseURL: 'https://domain.com/api/',
// `headers` are custom headers to be sent
headers: {'Content-Type': 'application/json'},
// `body` is the data to be sent as the request body
body: {
firstName: 'Fred'
},
// `signal` [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
//`isMultipartFormData` function that returns Boolean to detect if body should be converted to MultipartFormData
isMultipartFormData: function(body){
return true
},
//`prepareBody` function to customize body before sending request
prepareBody: function(body, isMultipartFormData){
if(isMultipartFormData){
return new FormData()
}
return JSON.stringify(body)
}
//`cache` https://developer.mozilla.org/en-US/docs/Web/API/Request/cache
cache: 'default',
//`credentials` https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
credentials: 'same-origin',
//`mode` https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
mode: 'same-origin'
}
The response for a request contains the following information.
{
// `data` is the response that was provided by the server
data: {},
// `request` is the request that generated this response
request: {}
}
You can specify config defaults that will be applied to every request.
api.defaults.baseURL = 'https://api.example.com'
api.defaults.headers['Authorization'] = AUTH_TOKEN
// Set config defaults when creating the instance
const instance = api.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers['Authorization'] = AUTH_TOKEN;
You can intercept requests or responses before they are handled by then
or catch
.
// Add a request interceptor
api.interceptors.request.use({
onSuccess: function (response) {
return response;
},
onError: function (error) {
return Promise.reject(error);
}
});
// Add a response interceptor
const remove = api.interceptors.response.use({
onSuccess: function (response) {
return response;
},
onError: function (error) {
return Promise.reject(error);
}
});
//remove interceptor
remove();
You can cancel a request using a AbortController.
const controller = new AbortController()
const signal = controller.signal
api.get({
endpoint: 'users',
signal: signal
})
controller.abort()