← Back to Chapters

REST API Basics

? REST API Basics

? Quick Overview

REST APIs allow React Native applications to communicate with servers using HTTP. They are commonly used to fetch data, send user input, authenticate users, and synchronize mobile apps with backend services.

? Key Concepts

  • Client–Server communication
  • HTTP methods (GET, POST, PUT, DELETE)
  • JSON as data exchange format
  • Status codes (200, 201, 400, 401, 404, 500)

? Syntax / Theory

In React Native, REST APIs are usually consumed using the built-in fetch() function or third-party libraries like Axios. The API endpoint returns JSON data that can be converted into JavaScript objects.

? Code Example(s)

? View Code Example
// Fetching data from a REST API using fetch()
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});

? Live Output / Explanation

What Happens?

The API returns a list of posts in JSON format. The response.json() method parses the response, and the resulting JavaScript object is logged to the console.

? Interactive Example

You can connect this API call to a button or useEffect hook in React Native to fetch data when the screen loads or when the user taps a button.

Below is the React Native code logic, followed by a Live Simulation:

? View React Native Code Logic
// Example using useEffect to call API on screen load
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(users => {
console.log(users);
});
}, []);
 

? Live Simulation

Click the button below to perform a real fetch request to a public API.

// Response data will appear here...

? Use Cases

  • Fetching product lists
  • User authentication and login
  • Submitting forms and feedback
  • Real-time data synchronization

✅ Tips & Best Practices

  • Always handle errors using catch()
  • Use environment variables for API URLs
  • Show loaders while data is fetching
  • Validate API responses before using them

? Try It Yourself

  • Fetch data from a public API and display it in a list
  • Implement error handling with a custom message
  • Try a POST request to send data to an API