React Native API Integration is one of the easiest way to fetch data from a remote urls. You can user the API integration to use not only GET request but we can also use any other HTTP requests like POST, PUT, DELETE easily on both Android and iOS using a single piece of code. In this tutorial, we will learn how to do a GET request with one example. Our application will fetch some dummy data and populate it in the application.
If you have not read previous articles in this series, we request you to do so-
Tutorial Index
- Tutorial #1 â React Native â Introduction
- Tutorial #2 â React Native Props and State
- Tutorial #3 â Styling React Native App
- Tutorial #4 â React Native UI Components
- Tutorial #5 â React Native API Integration
- Tutorial #6 â React Native Animation
- Tutorial #7 â Top 10 React Native libraries
Fetch API:
React native uses one API called Fetch API for handling HTTP requests. This is the same API used in web applications. If you have used âfetchâ before, this guide will be easier to understand. One global method called âfetch()â is used to fetch data. This is an asynchronous method. Its simplest form can take only one argument : the url of the data that we are fetching.We can use it to fetch data asynchronously and perform operations on that data once the fetch is completed. For example :
fetch('https://websiteurl.com/data.json');
Thatâs it.
Fetch deals with Request and Response objects. As you have seen above, fetch can be used minimum one argument. It returns one Promise object. It resolves to the response to that object. Once we get the Response, we can access other body params.
Other Arguments for Fetch API:
fetch also takes one second argument that can be used to customize the request. We can change the type of request like âPOSTâ, âGETâ , âPUTâ etc. and also we can customize the header and body of the request. For example :
fetch('https://api.mywebsite.url/v1/postdata', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ param1: 'value1', param2: 'value2', }), });
In this example, we are making one âPOSTâ request with a header and body values. The body is of type JSON.
Handling Response Data :
As explained above, we can handle the response using the Promise object returned by fetch. We can either use âthenâ to handle this promise or any âasync awaitâ function.
fetch('https://api.mywebsite.url/v1/postdata', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ param1: 'value1', param2: 'value2', }), });
In this example, we are fetching the data and converting the data to âjsonâ using its JSON. Async await example is at the end of the article.
Request Properties and Methods :
Request()
constructor is used to create a new Request object. If you are receiving the Request object access various properties of the object. You can its find below those properties and a brief details of each-
Properties (read only) :
- Request.cache: get the cache mode of the request.
- Request.context : get the context of the request
- Request.credentials: get the credentials of the request
- Request.destination : get the request destination
- Request.headers : get the header object
- Request.integrity : get the integrity value of the request
- Request.method: get the request method e.g. GET, POST, PUT etc.
- Request.redirect : get the mode how redirect is handled
- Request.referrer: get the referrer of the request
- Request.referrerPolicy : get the referrer policy of the request
- Request.url : get the url of the request
Methods:
Below are some methods of Request object that you can use readily.
- Request.clone() : this is used to clone the current request object.
- Body.arrayBuffer() : returns one promise, to resolve with an body object of type ArrayBuffer
- Body.blob() : returns one promise, to resolve with an body object of type Blob
- Body.formData() : returns one promise, to resolve with an body object of type FormData
- Body.json() : returns one promise, to resolve with an body object of type Json
- Body.text() : returns one promise to resolve with an body object of type Text
Response Properties and Methods :
Similar to Request, Response object also has some properties and methods, which you can check below-
Properties(read only) :
- Response.headers : get the headers object of the response
- Response.ok : Boolean value to define if the response is success or not. A response is called success if the response is in the range of 200 to 299
- Response.redirected : Defines if it is a redirected response
- Response.status : status code of the response
- Response.statusText : status message or text representation of the response value.
- Response.type : type of the response
- Response.url : the url of the response
- Response.useFinalURL : Boolean value that defines if it is the final URL of the response
- Body.body : A simple getter used to expose a ReadableStream of the body contents.
- Body.bodyUsed : Stores a Boolean that declares whether the body has been used in a response yet.
Methods :
- Response.clone() : creates the clone of the response object.
- Response.error() : returns one response object with a network error
- Response.redirect() : creates one response object with new url Response implements Body. So, it also contains the same Request Body methods we have defined above.
Running Example:
Letâs learn fetch with one simple example.
import * as React from 'react'; import { Text, View, StatusBar } from 'react-native'; export default class App extends React.Component { state = { jsonData: '', }; componentDidMount() { fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'GET', }) .then(response =x response.json()) .then(json =x { this.setState({ jsonData: json.body, }); }) .catch(error =x { console.error(error); }); } render() { return ( xView style={{ paddingTop: 30 }}x xTextx{this.state.jsonData}x/Textx x/Viewx ); } }
In this example, we are fetching dummy data from the âjsonplaceholderâ API. This is a open API and you can use it for testing.
- âAppâ is a react component that has one âstateâ with one key âjsonDataâ.
- In the ârenderâ method, it returns one âTextâ component that is showing the value defined by âjsonDataâ. This value is read from the âstateâ object. By default the value of âjsonDataâ is empty. Once the data is fetched, it will set the value to âjsonDataâ and reload the component.
- componentDidMount method is called once this component is loaded. Inside this method, we are using âfetchâ to make one GET request to the json API. It returns the response promise and we are using this promise object to get the âjsonâ value from that response.
- Finally, the body of that json value is set to the âjsonDataâ key. Once the value of state is changed, it will re-render the component UI and the json value will be shown in the UI like below :
As you can see in the above example that the json data is fetched and shown in the UI.
We can also use async-await while fetching like below :
async function getJsonData() { try { let res = await fetch( 'https://facebook.github.io/react-native/movies.json', ); let json = await res.json(); return json.data; } catch (error) { console.error(error); } }
You can use any one of the above function, totally depends on the architecture of the application.
Note:
For iOS applications, if a request is not SSL encrypted, it will be blocked or it will not work. This is the default behavior. You can avoid it by adding an ATS or app transport security exception.
Conclusion
The article has shown us how easy it is to integrate any third party API, Rest Services in React Native Application.
Please give it a try and let us know your comments.
Tutorial Index
- Tutorial #1 â React Native â Introduction
- Tutorial #2 â React Native Props and State
- Tutorial #3 â Styling React Native App
- Tutorial #4 â React Native UI Components
- Tutorial #5 â React Native API Integration
- Tutorial #6 â React Native Animation
- Tutorial #7 â Top 10 React Native libraries