-
Notifications
You must be signed in to change notification settings - Fork 293
API service
Haz edited this page Mar 27, 2017
·
1 revision
The API service (src/services/api
) is a convenient wrapper around fetch
.
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')
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')
Special thanks to @kybarg and @protoEvangelion for helping to write this Wiki. Please, feel free to edit/create pages if you think it might be useful (also, see #33)