APIs in React Native
Last update: 2025-04-24In React Native, you have multiple options to make API calls. The two most common approaches are using the built-in fetch
API or the popular axios
library. Let’s look at both approaches.
Using Fetch API
The Fetch API is built into React Native and requires no additional dependencies. Here’s how to make a GET request:
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const json = await response.json();
console.log(json);
} catch (error) {
console.error('Error fetching data:', error);
}
};
For POST requests with data, you need to specify additional options:
const postData = async () => {
try {
const response = await fetch('https://api.example.com/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer YOUR_TOKEN'
},
body: JSON.stringify({
title: 'New Item',
body: 'Content'
})
});
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error posting data:', error);
}
};
Using Axios
Axios provides a more feature-rich API client with built-in request/response transformations. First, install axios:
npm install axios
# or
yarn add axios
Here’s how to make requests with axios:
import axios from 'axios';
// GET request
const fetchDataWithAxios = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
// POST request
const postDataWithAxios = async () => {
try {
const response = await axios.post(
'https://api.example.com/create',
{
title: 'New Item',
body: 'Content'
},
{
headers: {
Authorization: 'Bearer YOUR_TOKEN'
}
}
);
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
You can also create an axios instance with default configuration:
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer YOUR_TOKEN'
}
});
// Now use the configured instance
const getData = async () => {
try {
const response = await api.get('/data');
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
Both fetch
and axios are great options for making API calls in React Native. Choose fetch
if you want to keep dependencies minimal, or axios if you need more advanced features like request/response interceptors, automatic JSON transformation, or better error handling.