React.js Frontend & FastAPI Backend Communication via JSON
1. How React.js and FastAPI Connect
- React.js (Frontend): Runs in the browser, makes HTTP requests using
fetchoraxios, receives JSON, updates the UI. - FastAPI (Backend): Exposes endpoints (REST API), returns JSON responses, accepts JSON requests.
2. Example Flow
(a) React.js sends a request:
// Using fetch in React
fetch("http://localhost:8000/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Example", quantity: 3 })
})
.then(response => response.json())
.then(data => console.log(data));
(b) FastAPI receives the request:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
quantity: int
@app.post("/items")
def create_item(item: Item):
return {"message": f"Received {item.quantity} of {item.name}"}
(c) FastAPI responds with JSON:
{
"message": "Received 3 of Example"
}
(d) React updates the UI:
The data received in React is parsed from JSON and can be displayed or used in components.
- JSON is the standard for frontend-backend communication in REST APIs.
- React cannot directly access Python objects; only JSON data is sent over HTTP.
- FastAPI automatically serializes Python objects to JSON and deserializes JSON to Python objects.
- Query parameters and form data can also be used, but JSON is preferred for structured data.
3. Summary
React.js and FastAPI communicate via HTTP requests with JSON payloads, enabling a powerful and modern web application architecture.