Skip to content
Haz edited this page Mar 27, 2017 · 1 revision

The API service (src/services/api) is a convenient wrapper around fetch.

Basic usage

import api from 'services/api'

// calling directly
api.post('/resources', { title: 'Hello, World!' })
   .then(data => console.log(data.title))
   .catch(...)

// or in a worker saga
const data = yield call([api, api.post], '/resources', { title: 'Hello, World!' })

As you can see, you don't need to specify the API domain. It'll automatically prepend apiUrl set on src/config.js. But you can, of course, pass another API domain:

api.get('https://api.github.com/users/octocat/orgs')

Setting access tokens

Another way to use that is by creating an API instance so you can set a state (like access tokens) once and use it within your application:

const apiInstance = api.create()

apiInstance.setToken('123')

// these requests will be sent with `Authorization: Bearer 123` header
apiInstance.post('/resources', { title: 'Hello, World!' })
apiInstance.get('/resources/1')

// these requests will be sent with no custom headers
api.post('/resources', { title: 'Hello, World!' })
api.get('/resources/1')
Clone this wiki locally