fetch-api v0.0.2
Node React Native Fetch API
API wrapper for ES6's fetch method used with GitHub's fetch polyfill
Familiar with packages? Jump to Usage now
NPM | Bower* |
---|---|
npm install --save fetch-api | bower install --save fetch-api |
* You may need to bower install --save es6-promise
to support older browsers
What is this project about?
Use this package as a simple HTTP method wrapper for integrating your API in your Node and React Native projects. It's a better alternative, with less headaches (at least for me) for this use case than superagent and the default fetch Network method.
It supports and is tested for both client-side usage (e.g. with Bower, Browserify, or Webpack, with whatwg-fetch
) and also server-side (with node-fetch
).
Why not just use superagent
or fetch
?
See Background for more information.
Learning how to build an API with Node.js?
Read my article about building Node.js API's with authentication.
Index
Usage
Install the package:
NPM:
npm install --save fetch-api
Bower:
bower install --save fetch-api
Require it, set a base URI, and call some methods:
// require the module import API from 'fetch-api'; // instantiate a new API instance let api = new API({ baseURI: 'https://api.startup.com' }); // log in to our API with a user/pass api.post('/v1/login', (err, res, user) => { // you'll probably want to handle this // error better than just throwing it if (err) throw err; // set basic auth headers for all // future API requests we make api.auth(user.api_token); // now let's post a message to our API api.post( '/v1/message', { body: 'Hello' }, // if you wanted to pass JSON instead of plaintext: // { body: { message: 'Hello' } } (err, res, message) => { // again obviously handle this error better if (err) throw err; // do something with the response console.log('message', message); } ); });
API
import API from 'fetch-api';
API
is a function that optionally accepts an argument options
, which is an object full of options for constructing your API instance.
API
- accepts anoptions
object, with the following accepted options:baseURI
- the default URI to use as a prefix for all HTTP requests- If your API server is running on
http://localhost:8080
, then use that as the value for this option If you use React Native, then you most likely want to set
baseURI
as follows (e.g. making use of__DEV__
global variable):let api = new API({ baseURI: __DEV__ ? process.env.API_BASE_URI || 'http://localhost:8080' : 'https://api.startup.com' });
You could also set
API_BASE_URI
as an environment variable, and then set the value of this option toprocess.env.API_BASE_URI
(e.g.API_BASE_URI=http://localhost:8080 node app
)
- If your API server is running on
headers
- an object containing default headers to send with every requestauth
- will call theauth()
function below and set it as a default
Upon being invoked, API
returns an object with the following methods:
api.auth([ user, pass ])
- helper function that sets BasicAuth headers, and it acceptsuser
andpass
arguments- If you don't pass both
user
andpass
arguments, then it removes any previously set BasicAuth headers from priorauth()
calls - If you pass only a
user
, then it will setpass
to an empty string''
) - If you pass
:
then it will assume you are trying to set BasicAuth headers using your ownuser:pass
string - If you pass more than two keys, then it will throw an error (since we BasicAuth only consists of
user
andpass
anyways)
- If you don't pass both
All exposed HTTP methods require a
path
string andcallback
function arguments, and accept an optionaloptions
object:Accepted method arguments:
path
required - the path for the HTTP request (e.g./v1/login
, will be prefixed with the value ofbaseURI
mentioned earlier)options
optional - an object containing options, such as header values, a request body, form data, or a querystring to send along with the request, here are a few examples:To set a custom header value of
X-Reply-To
on aPOST
request:api.post('/messages', { headers: { 'X-Reply-To': '7s9inuna748y4l1azchi' } }, callback);
callback
required - a callback function that gets called with the arguments of(err, res, body)
:err
- contains an error object (ornull
)res
- the response from server (it contains status code, etc)body
- the parsed JSON or text response (ornull
)
List of available HTTP methods:
api.get(path, options, callback)
- GETapi.head(path, options, callback)
- HEAD (does not currently work - see tests)api.post(path, options, callback)
- POSTapi.put(path, options, callback)
- PUTapi.del(path, options, callback)
- DELETEapi.options(path, options, callback)
- OPTIONS (does not currently work - see tests)api.patch(path, options, callback)
- PATCH
Tests
This package is tested to work with whatwg-fetch
and node-fetch
.
This means that it is compatible for both client-side and server-side usage.
Development
Watch the src
directory for changes with npm run watch
and when you are done, run npm test
.
Background
Facebook recommends to use superagent
with React Native, but it does not work properly, therefore I went with the next best solution, their fetch
package. After having several issues trying to use fetch
and writing my own API wrapper for a project with it (and running into roadblocks along the way) -- I decided to publish this.
Here were the issues I discovered/filed related to this:
- https://github.com/github/fetch/issues/235
- https://github.com/facebook/react-native/issues/4376
- https://github.com/visionmedia/superagent/issues/636
- https://github.com/facebook/react-native/issues/863
- https://github.com/facebook/react-native/issues/370
- https://github.com/facebook/react-native/issues/10
I know that solutions like superagent
exist, but they don't seem to work well with React Native (which was my use case for this package).
In addition, the authors of the spec for ES6's fetch support throwing errors instead of catching them and bubbling them up to the callback/promise.
Therefore I created fetch-api
to serve as my API glue, and hopefully it'll serve as yours too.
Contributors
- Nick Baugh niftylettuce@gmail.com