How to learn fetch
Data from APIs
Have the necessary skills for any developer. Whether you are creating a simple portfolio site or working on real -world applications, you will often need to connect with external data sources. The relief from API calls shows that you are ready to contribute to real projects and work well in the team.
It is designed to show the initial friendly tutorial junior developers and any new reaction. You will learn how fetch data
From an API, then store
And display
This is in your reaction app. No modern knowledge is needed – we will break everything step by step, so you can build confidence and trust.
We will use React
For, for, for,. Vite
For, for, for,. Axios
And Tailwind CSS
To create a simple app that shows and displays data from the public API. First, we will bring data using a built -in recovery method. Then we will reflect this using Acosis, a famous library that makes it easy HTTP requests
.
Provisions
You should do this article as well, you should:
Be aware of the basic reaction concepts such as components and
useState
Know what
API
Is and that it returns the data (usually in JSON)JavaScript promises and experience something with that
.then()
Method (if you have seen or used.then()
Before that, it’s enough – we will build on it).Stay comfortably by using
map()
Submitting lists from Rows (which data we get from API)Be able to run a react project using tools such as making a white or react app
The table of content
What is an API and why do we need it?
An API, or application programming interface, is a way to communicate for different systems. Think about it like a waiter in a restaurant. You tell the waiter what you want from the menu (request), they take this order to the kitchen (server), and then bring your food back to the table.
In web development, APIS let your Front and Application talk to the back and service. Most of the time, this communication is done through HTTP applications. You request a specific URL (called the closing point), and you usually get the answer JSON (JavaScript Object Notation)
The shape json is lightweight, easy to read, and works well with Javascript.
Here is an example of a basic gate application:
GET https:
This application asks the server for a list of users. Answer will look like something like this:
(
{
"id": 1,
"name": "John Doe",
"email": "JohnDOe@email.com",
},
{
"id": 2,
"name": "Jane Doe",
"email": "JaneDoe@email.com",
},
)
Your react app can catch this JSON, keep it in the state, and display it in the browser. This is the basic API cycle you will see in real -world applications repeatedly:
Request
Wait for the answer
Analyze JSON
Use data in your UI
Understanding APIs
And JSON
Essential. You will use them to bring user profiles, submit form, update dashboards, search database and more.
Types of APIS will have to face you
Not all APIs are the same. Understanding the types of APIs coming to you will help you know what tools or measures you will need to work with them.
1. Public apis (no key required)
These are open access APIs that anyone can use. They do not need verification or API key. They are great to test, learn and build demo apps.
Example:
GET
2. Public APIS (with API key)
Some APIs are public, but still requires an API key. This helps track the use of the provider and avoid abuse. You will usually sign up to get a free key.
Example:
GET
– the original API closing point
country=us
– an inquiry parameter you want “US headlines”apiKey=YOUR_API_KEY
– This is your personal API key that gets you after signing up NewsP.P
You will need to use these APIs, you will need:
Sign up to the provider’s site
Store your key (securely) in your app (we’ll find it later)
Pass it as an inquiry parameter or header
3. Private apis
They are commonly used internally in companies. They often need more sophisticated forms of verification, such as oat tokens or sessions cookies. You will usually not use them unless you are working at a backdrop or team project.
4. Use of bearer token for API verification
When working with modern APIS, it is common to face APIS that requires verification using A Bearer token
Instead of a simple API key in the URL. The only difference here is that you pass in a object
It only contains a bearer token instead of the API key variable (for example, the movie database (TMDB) API).
This approach is more secure because it keeps the token away from the history of the URL and the browser. It also aligns with token -based verification standards such as Outh 2.0.
Note: When working with the third party’s APIS, the documents always look at how the confirmation should be handled. Verification methods vary – some APIs need to pass the key in the URL, others expect it in the header.
Reacts: Our JavaScript UI Library of Selection
Tel Wind CSS: For a quick style
Recovery: Local browser method to make http applications
Axios: Optional library that makes applications more convenient
How to use these tools and methods will make it easier to adopt different production methods and environments.
How to bring data with reaction
Now you need to understand the infrastructure and tools you need so that you can bring data with a reaction and use this data in your components. You will need to understand some basic tools and concepts to do it correctly:
USESESTATE HOCK: It allows you to build and manage the local state within your component. You will use it to hold your data, and track things like you are still loading or having a mistake.
Useefect Hook: Allows you to carry out operations that need to run after components, such as bringing data, subscribing events, or updating the domestation.
Http requests: You talk to APIS. You can use a local recovery () method or third -party tools such as Axios from the browser.
A basic data bringing flow looks like:
Set the State when your data arrives
Use Useeffect () hook to call API
Handle loading and error conditions
Store and display data once
Now that you’ve got the basic principles, let’s go through two ways to bring data: using first fetch()
Then use Axios
.
How to bring data fetch()
fetch()
Method is a local browser feature that allows you to send HTTP
Application directly from Front End. It is useful for making basic API calls without any additional libraries.
Reacting Recovery () to use () you will usually follow this style:
To ensure this, use the Useeffect () hook when the component increases, the recovery call only runs once.
Call Recover (‘URL’) to send a HTTP request.
Use .Json () to analyze the JSON response.
Store the reaction in the state using the USestate ().
Let’s see an example:
Import the necessary hooks and call the recovery within Useeffect.js:
import { useEffect, useState } from 'react';
function App() {
const (users, setUsers) = useState(());
useEffect(() => {
fetch('')
.then(res => res.json())
.then(data => setUsers(data));
}, ());
return (
<div className="p-6 max-w-4xl mx-auto">
<h1 className="text-2xl font-bold mb-4">User List (using fetch)h1>
<ul className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{users.map(user => (
<li key={user.id} className="bg-white shadow p-4 rounded-xl">
<h2 className="text-lg font-semibold">{user.name}h2>
<p className="text-sm text-gray-600">{user.email}p>
<p className="text-sm text-gray-600">{user.company.name}p>
li>
))}
ul>
div>
);
}
export default App;
Refects with acneus
Axis is a third -party library that makes HTTP requests easier and more reliable. While the recovery () is made in the browser, acne makes many things easier, such as automatically dealing with JSON parsing and cleaner error.
Why use more axis than recovery:
Acnees automatically changes the JSON response – you don’t have to manually call .json ().
Its application and response are built -in support for interceptors.
It makes it easier to send a header, handle errors, and work with non -obtained requests (post, deletion, and so on).
First, install the axis in your project via terminal:
npm install axios
Import the necessary hooks and axes and insert the API call inside it.
import { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const (users, setUsers) = useState(());
useEffect(() => {
axios.get('')
.then(response => setUsers(response.data);
}, ());
return (
<div className="p-6 max-w-4xl mx-auto">
<h1 className="text-2xl font-bold mb-4">User List (using Axios)
h1>
<ul className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{users.map(user => (
<li key={user.id} className="bg-white shadow p-4 rounded-xl">
<h2 className="text-lg font-semibold">{user.name}h2>
<p className="text-sm text-gray-600">{user.email}p>
<p className="text-sm text-gray-600">{user.company.name}p>
li>
))}
ul>
div>
);
}
export default App;
How to handle loading and error conditions
When you work with the reaction, things are not always right. Sometimes it takes time to reach the data and the application fails for the second time. Loading and error states are useful because they give you feedback and make it friendly to both the user and the developer.
What is the loading state?
A loading state is used to show that data is being brought. Without it, consumers may not know what is happening and seems to be the application is not passing or the app is not working. You usually use Bowen to track it.
What is the state of error?
An error condition tells you that something has gone wrong – maybe the API is below, or the URL was wrong. Catching and displaying these mistakes helps you to weaken faster and give users clear feedback.
Code’s piece:
Here’s how you can add loading and error to the primary recovery () request:
const (users, setUsers) = useState(());
const (loading, setLoading) = useState(true);
const (error, setError) = useState(null);
useEffect(() => {
fetch('')
.then(res => {
if (!res.ok) throw new Error('Network response was not ok');
return res.json();
})
.then(data => {
setUsers(data);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, ());
if (loading) return <p>Loading...p>;
if (error) return <p>Error: {error}p>;
This gives you the user’s smooth experience and makes your app more reliable.
How to secure your API Keys
If you are using an API that requires a key, this key must be preserved. Never direct your API keys directly to your reaction components or push them to public reservoirs. Instead, store them in one .env
File in the root of your project (the same directory that is like your package. In you .env
File it:
VITE_API_KEY=your_actual_key_here
To access this in your app, use:
const apiKey = import.meta.env.VITE_API_KEY;
You can then use this key in your API applications. Here you will add it to the axes.
axios.get(`https://api.example.com/data?apikey=${apiKey}`)
.then(response => {
setUsers(response.data);
setLoading(false);
})
.catch(error => {
setError(error.message);
setLoading(false);
});
Note: In order to be accessible to the browser, environmental variables have to start with VITE_. Make sure .env add your .gitignore file so that it does not push the gut hub.
Hiding your key helps to avoid exposing you to the public, especially if your project is shared on the gut hub or is deployed online.
Why is it necessary:
Exposed keys can be abused, which causes overseas or bans by the API provider
You may lose access in terms of service or eliminate charges
In safe apps, exposed keys may be a major risk of security
Always treat your keys like passwords. If a key is exposed, cancel it and create a new API provider’s dashboard.
Public APIS to practice
Here are some entertainment and free APIs you can use to make practice projects.
1. Json Place Holder: Fake data for testing: users, posts, comments, Todos. No key is needed.
2. Dog API: Find random images, generation information, and search through generation. Need a free API key.
3. Cat API: Just like dog API, but for cats. Image is great for heavy apps. Free API Key.
4. Recover detailed Pokémon’s detailed data. Great for cards, search filters, or sports. No key is needed.
5. TMDB API: Get movie data, trending shows, cast details, posters and more. Need a free API key from TMDB (you can clone famous streaming sites with it).
6. The rest of the countries API: Recover the names of the country, capital, region, flags and populations. No API key is needed.
7. Boring API: Get random activity tips when you are bored. No key is needed.
8. Recover jokes in terms of category or type (safe for work, programming, dark humor). No key is needed.
9. Rick and Morte API: Discover letters, places and episodes. Perfect for fans. No key is needed.
10. NASA APIS: Discover images, astronomical data, and space facts. NASA needs a free API key.
Play with different data formats, add filters or search, and connect multiple APIS into a project. This is a great process for the development of the real world app.
Conclusion
What you just made is the basis of countless real -world applications. Web development requires the ability to bring data, manage and display data from APIS.
From here, you can extend this app:
When you continue to develop as a developer, the sample you have taken here will appear again and again. Mastering them now prepares you for success later.