Rest

Utility functions for performing REST calls. Applications that interact with REST APIs should use fetch andpromises. This Rest module provides a few helper functions along the way.

Variables

headers
Accept and Content-Type headers for JSON APIs.

Methods

buildParams ({object})
Converts object to parameter array of strings of name=URI-encoded-value. Handles array values.
buildQuery ({object}|{Array})
Calls buildParams if passed an object. Then joins the params array with '&' and adds a '?' prefix if needed
processStatus ({response})
For use in a promisechain. Rejects promise if response is not ok.

Example

import { headers, buildQuery, processStatus } from 'grommet/utils/Rest';

export default class MyComponent extends Component {

  _getData (filters) {
    const query = buildQuery(filters);
    const options = { method: 'GET', headers: { ...headers, Auth: _token };
    fetch(`/rest/index/resources${query}`, options)
    .then(processStatus)
    .then(response => response.json())
    .then(result => this.setState({ result: result, error: undefined }))
    .catch(error => this.setState({ result: undefined, error: error }));
  }

})

Deprecated

The following methods and the embedding of superagent are deprecated and will be removed in a future release. The rationale for this is that fetch is a simple enough interface.

Deprecated Methods

del (uri)
Delete the resource indicated by the uri.
get (uri, object)
Get the resource indicated by the uri and optional query parameters. The second argument will be converted into a query string.
head (uri, object)
Chek the resource indicated by the uri and optional query parameters. The second argument will be converted into a query string.
patch (uri, data)
Update some of the resource indicated by the uri with the provided data.
post (uri, data)
Create a resource under the indicated uri with the provided data.
put (uri, data)
Create or update the resource indicated by the uri with the provided data.
setHeader (name, value)
Set a default HTTP header.
setHeaders (object)
Set multiple HTTP headers.
setTimeout
Set the default request timeout.

Note, the object returned from head, get, patch, post, put, and del is the superagent request object. You must call end() to actually perform the request.

Deprecated Example

export default class MyComponent extends Component {
  ...
  _onResponse (err, res) {
    if (err && err.timeout > 1000) {
      this.setState({error: 'Timeout', result: {}});
    } else if (res.status === 400) {
      Actions.logout();
    } else if (!res.ok) {
      this.setState({error: res.body || res.text, result: {}});
    } else {
      var result = res.body;
      this.setState({result: result, error: null});
    }
  }
  ...
  _getData () {
    Rest.get('/rest/index/resources', this.state.options.params)
      .end(this._onResponse);
  }
  ...
})