How to Handle API Data in React with a Python Backend
Building modern applications often involves:
React → Frontend UI
Python (FastAPI, Flask, or Django) → Backend API
The backend provides data via REST APIs, and React fetches and uses that data.
This guide explains how to send, fetch, display, and update API data using React + Python.
๐งฉ 1. Typical Architecture
React (Frontend)
|
HTTP / JSON
|
Python Backend (API)
|
Database
๐ 2. Example Python Backend (FastAPI)
FastAPI is modern and fast, but this works the same with Flask or Django.
Install:
pip install fastapi uvicorn
Create main.py:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
id: int
name: str
price: float
items = [
Item(id=1, name="Laptop", price=999.99),
Item(id=2, name="Phone", price=499.99),
]
@app.get("/items")
def get_items():
return items
@app.post("/items")
def add_item(item: Item):
items.append(item)
return {"message": "Item added", "item": item}
Run backend:
uvicorn main:app --reload
Your backend now serves:
GET /items → Fetch data
POST /items → Send data
⚛️ 3. Fetching API Data in React
Inside React, you typically fetch API data using:
fetch()
or axios
Example using fetch:
In Items.js:
import React, { useEffect, useState } from "react";
function Items() {
const [items, setItems] = useState([]);
useEffect(() => {
fetch("http://localhost:8000/items")
.then(res => res.json())
.then(data => setItems(data));
}, []);
return (
<div>
<h1>Items</h1>
{items.map(item => (
<p key={item.id}>
{item.name} - ${item.price}
</p>
))}
</div>
);
}
export default Items;
React will load the data from your Python backend and display it.
๐ค 4. Sending Data from React to Python
To submit data to an API, you send a POST request.
Example React form:
import React, { useState } from "react";
function AddItem() {
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
fetch("http://localhost:8000/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: Date.now(),
name,
price: parseFloat(price),
}),
})
.then(res => res.json())
.then(data => console.log(data));
};
return (
<form onSubmit={handleSubmit}>
<input
placeholder="Name"
onChange={(e) => setName(e.target.value)}
/>
<input
placeholder="Price"
type="number"
onChange={(e) => setPrice(e.target.value)}
/>
<button>Add Item</button>
</form>
);
}
export default AddItem;
๐ 5. Handling CORS
React and your API run on different ports, so you must enable CORS.
Install:
pip install fastapi[all]
Add to FastAPI:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # in production use specific domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Now React can safely communicate with Python.
๐ฆ 6. Using Axios Instead of fetch()
(Recommended for real apps)
Install:
npm install axios
Example:
import axios from "axios";
useEffect(() => {
axios.get("http://localhost:8000/items")
.then(res => setItems(res.data));
}, []);
๐ 7. Updating Data in React After API Calls
Common pattern:
Call API
Update React state
Rerender UI automatically
Example:
const addItem = async () => {
const res = await axios.post("http://localhost:8000/items", newItem);
setItems(prev => [...prev, res.data.item]);
};
๐ 8. Recommended Folder Structure
backend/
main.py
frontend/
src/
components/
pages/
App.js
๐ 9. Deployment Strategy
Backend:
Host on AWS EC2, DigitalOcean, or Azure
Use Uvicorn/Gunicorn
Add NGINX reverse proxy
Frontend:
Deploy React on Netlify, Vercel, or NGINX
Update API URL in React:
Use environment variables:
REACT_APP_API_URL=https://yourapi.com
Refer to it as:
fetch(process.env.REACT_APP_API_URL + "/items")
๐งพ 10. Summary
To handle API data in React with a Python backend:
Build a REST API using FastAPI, Flask, or Django
Enable CORS
Fetch data from React using fetch or axios
Display the data using React state
Send data to backend using POST
Update the UI automatically
Deploy backend + frontend separately or behind one server
Learn Fullstack Python Training in Hyderabad
Read More
Building Real-Time Web Applications with WebSockets in Python
How to Use AJAX with Python for Seamless User Interactions
Connecting Flask with React: Building a Full Stack App
Integrating React with Django: A Full Stack Tutorial
At Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments