This video is available to students only

Making API calls

The very reliable "fetch". Learn the best practices for structuring the app's services and APIs to make them resilient to change.

Prerequisites#

It is highly recommended that you go through the lessons of Module 1 - Getting Started before proceeding with any other module. They build up to the type of learning we are trying to achieve here and lay the foundation for the whole course.


Making API calls#

Making API calls in React Native is quite similar to how one would do it in a React app, or in fact any web application, using fetch.

A simple setup that makes calls from the business logic layer of the app works pretty well. We will be using thunk and can see more of it in the middlewares lesson in the State Management module.

Setup#

The structure I like to follow for making API calls is as follows:

This setup helps abstract out the actual implementation and keeps it simple for the rest of the application trying to fetch data or consume any low-level service. It also promotes the single responsibility principle. Let's understand this in more detail below.

Core#

The core folder is where we will do the low-level implementation of APIs we need to define. This will have the abstraction over primitive APIs that blackbox the actual implementation and expose simple methods to the app for consumption. Examples can be, an implementation over fetch for making API calls, or over AsyncStorage for storing persistent data locally, or a request/response logger, and exposing an API class or a Storage class.

The idea is that if tomorrow we wanted to move from fetch to Axios, or say from AsyncStorage to a SQLite database, then the rest of the application could remain oblivious of the change and not be impacted by it.

Base API#

The baseAPI abstracts out the nuts and bolts of API implementation, ie. how to make network calls. It can be a wrapper over fetch or Axios or Apisauce. baseAPI will expose the standard get, post, delete, or other methods, as required.

Apart from abstracting out low-level API implementation, we can also plug in any common requirements for making such calls. An example might be that for REST APIs we can add the common headers that are required to make the call.

Start a new discussion. All notification go to the author.