Code Monkey home page Code Monkey logo

react-native-rest-client's Introduction

React Native REST Client

npm version js-semistandard-style

Simplify the RESTful calls of your React Native app.

Instalation

npm install --save react-native-rest-client

Simple usage

Create your own api client by extending the RestClient class

import RestClient from 'react-native-rest-client';

export default class YourRestApi extends RestClient {
  constructor () {
    // Initialize with your base URL
    super('https://api.myawesomeservice.com');
  }
  // Now you can write your own methods easily
  login (username, password) {
    // Returns a Promise with the response.
    return this.POST('/auth', { username, password });
  }
  getCurrentUser () {
    // If the request is successful, you can return the expected object
    // instead of the whole response.
    return this.GET('/auth')
      .then(response => response.user);
  }
};

Then you can use your custom client like this

const api = new YourRestApi();
api.login('johndoe', 'p4$$w0rd')
  .then(response => response.token)   // Successfully logged in
  .then(token => saveToken(token))    // Remember your credentials
  .catch(err => alert(err.message));  // Catch any error

Advanced usage

import RestClient from 'react-native-rest-client';

export default class YourRestApi extends RestClient {
  constructor (authToken) {
    super('https://api.myawesomeservice.com', {
      headers: {
        // Include as many custom headers as you need
        Authorization: `JWT ${authToken}`
        // Content-Type: application/json
        // and
        // Accept: application/json
        // are added by default
      },
      // Simulate a slow connection on development by adding
      // a 2 second delay before each request.
      devMode: __DEV_,
      simulatedDelay: 2000
    });
  }
  getWeather (date) {
    // Send the url query as an object
    return this.GET('/weather', { date })
      .then(response => response.data);
  }
  checkIn (lat, lon) {
    return this.POST('/checkin', { lat, lon });
  }
};

Reference

super(baseUrl [, options])

You must call the parent constructor as shown in the example above.

Parameter Type Required Default
baseUrl String Yes undefined
options Object No {}

options object

Supports the following values

Key Type Required Default Comments
headers String No {} Headers to be appended to the request. RestApi will always include Content-Type: application/json and Accept: application/json.
devMode Boolean No false When true, it enables the simulatedDelay.
simulatedDelay Number No 0 Useful for simulating a slow connection. Number of milliseconds to wait before making the request. NOTE: It will only take effect if devMode is true.

this.GET(route [, query])

this.POST(route [, body])

this.PUT(route [, body])

this.DELETE(route [, query])

Each one of these methods returns a Promise with the response as the parameter.

Parameter Type Required Default Comments
route String Yes '' Partial route to be appended to the baseUrl
query Object No {} Object to be encoded and appended as the query part to the URL
body Object No {} Data to be sent as the JSON body of the message

Limitations

  • This library only supports JSON request and response bodies. If the response is not a JSON object, it will throw a JSON parse error. If the response is empty, it will return undefined.
  • It is labeled as React Native, even when it has no RN dependencies and could (in theory) be used in any JavaScript project. The reason behind this is that the stack used (ES6 and fetch) comes out of the box with React Native, and adding support for more platforms would require to add pre-compilers, polyfills and other tricks, which are completely out of the scope of this library. If you know what you're doing though, feel free to tweak your stack and use this library.

License

MIT

react-native-rest-client's People

Contributors

javorosas avatar mattsains avatar nicktoony avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-rest-client's Issues

How is this package a REST client?

After having checked this repo's README, I don't really see how this package is helping us to build apps calling REST APIs, so I would like to get your input @javorosas to explain me what this package does, and how this package helps developers to call REST APIs? (I want to be sure to not misunderstand what this package does).

In my eyes, as REST defines how REST APIs are working (using resources, HTTP verbs and so on), I was expecting this package to allow me to configure my React component (the inheritance of RestClient is perfect) by giving the API base URL, the resource I'd like to consume, and that's it.
(Of course, with some flexibilities for APIs not following 100% the REST standard)

An example of what I was expecting :

import RestClient from 'react-native-rest-client';

export default class UsersApi extends RestClient {
  constructor () {
    // Initialize with your base URL
    super('https://api.myawesomeservice.com', resource: 'users');
  }
}

Then calling it as the following :

const usersApi = new UsersApi();

// Get all users (GET '<api base URL>/users')
usersApi.all()
        .then(response => console.log(response.users)) // Array of User objects
        .catch(err => alert(err.message));

// Get user with ID 1 (GET '<api base URL>/users/1')
usersApi.get(1)
        .then(response => console.log(response.user)) // User with ID 1 object
        .catch(err => alert(err.message));

// Creating a new user (POST '<api base URL>/users')
usersApi.create({ name: 'John', ... })
        .then(response => console.log(response.user)) // Created user object
        .catch(err => alert(err.message));

// Updating the user with ID 1 (PUT/PATCH '<api base URL>/users/1')
usersApi.update(1, { name: 'John', ... })
        .then(response => console.log(response.user)) // Updated user object
        .catch(err => alert(err.message));

// Destroying the user with ID 1 (DELETE '<api base URL>/users/1')
usersApi.destroy(1)
        .then(response => console.log(response.user)) // Destroyed user object
        .catch(err => alert(err.message));

// Flexible way of calling (GET '<api base URL>/users/1/unlock')
usersApi.request(RestClient.GET, 1, '/unlock')
        .then(response => console.log(response.body)) // API Response body field
        .catch(err => alert(err.message));

Or, regarding the last example calling the user's unlock, we could then follow what is already shown in this repo's README, updating the UsersApi component :

import RestClient from 'react-native-rest-client';

export default class UsersApi extends RestClient {
  constructor () {
    // Initialize with your base URL
    super('https://api.myawesomeservice.com', resource: 'users');
  }

  unlock(id) {
    return this.GET(id, '/unlock');
  }
}

With this, it's very easy and fast to build apps consuming REST APIs.

Dynamic URL

Is there any way to pass base url dynamically from AsyncStorage in rest client constructor.
constructor () {
super(' dynamic URL);
}

Failed to minify code / react build

I am facing a problem in building a react app with this library.
Failed to minify the code from this file: ./node_modules/react-native-rest-client/index.js:1
Thanks for everything

Ability to return Promise for response before it is json parsed

I ran into an issue with react-native-rest-client when receiving a response from an api call that did not include JSON (simply an 202 response). How about adding a non-json response option to the api? It is has been very helpful for a project I'm working on. Thanks for sharing it!

How To Catch Promise

Hi, I use your libs, it's so light. But I still have problem to handle error :

Possible Unhandled Promise Rejection, where I should add catch..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.