NashTech Blog

Building a Full-Stack App with React and FastAPI: How to Quickly Build and Document APIs with Python

Table of Contents

In modern web development, developers are increasingly choosing React for building dynamic, responsive frontends — and FastAPI for creating high-performance, Python-based backends with automatic API documentation.

The combination of these two technologies provides the perfect balance between speed, scalability, and developer experience, making it easier than ever to prototype, test, and deploy production-ready applications.

In this article, we’ll walk through how to build a full-stack project using React for the frontend and FastAPI (Python) for the backend — complete with Swagger auto-documentation and clean API design.


1. Why React + FastAPI?

Before diving into the setup, let’s understand why this combination works so well.

FeatureReactFastAPI
PurposeFrontend UI frameworkBackend web framework
LanguageJavaScript / TypeScriptPython
Key StrengthComponent-based, interactive UIHigh performance, auto-generated docs
Ideal UseSPAs, dashboards, real-time interfacesREST APIs, data processing, ML serving

FastAPI stands out among Python frameworks for its:

  • 🚀 Speed — built on ASGI and Starlette, it’s faster than Flask and Django REST.
  • 🧠 Automatic validation with Pydantic models.
  • 🧩 Swagger UI integration — automatic API documentation out of the box.
  • ⚙️ Async support for concurrency and scalability.

When paired with React, you can build a complete web system: React handles the front-end logic, while FastAPI serves structured data and performs business operations.


2. Project Structure

Let’s create a simple project structure for clarity:

fullstack-app/
│
├── backend/
│   ├── main.py
│   ├── requirements.txt
│
└── frontend/
    ├── package.json
    ├── src/
        ├── App.js
        ├── components/

3. Step 1: Set Up the FastAPI Backend

a. Install FastAPI and Uvicorn

mkdir backend && cd backend
python -m venv venv
source venv/bin/activate
pip install fastapi uvicorn

b. Create a Simple API in main.py

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(
    title="React + FastAPI App",
    description="A simple demo API built with Python and FastAPI",
    version="1.0.0"
)

# Define a data model
class Item(BaseModel):
    name: str
    price: float
    description: str | None = None

@app.get("/")
def read_root():
    return {"message": "Welcome to FastAPI backend!"}

@app.post("/items/")
def create_item(item: Item):
    return {"data": item}

c. Run the server

uvicorn main:app --reload

By default, your backend will be available at:

👉 You now have a fully documented REST API with just a few lines of Python!


4. Step 2: Set Up the React Frontend

a. Initialize React

npx create-react-app frontend
cd frontend
npm install axios

b. Create App.js

import React, { useState } from "react";
import axios from "axios";

function App() {
  const [item, setItem] = useState({ name: "", price: "", description: "" });
  const [response, setResponse] = useState(null);

  const handleChange = (e) => {
    setItem({ ...item, [e.target.name]: e.target.value });
  };

  const handleSubmit = async () => {
    try {
      const res = await axios.post("http://127.0.0.1:8000/items/", item);
      setResponse(res.data.data);
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <div style={{ textAlign: "center", marginTop: "5rem" }}>
      <h2>React + FastAPI Demo</h2>
      <input
        name="name"
        placeholder="Item name"
        onChange={handleChange}
      /><br/>
      <input
        name="price"
        type="number"
        placeholder="Item price"
        onChange={handleChange}
      /><br/>
      <input
        name="description"
        placeholder="Item description"
        onChange={handleChange}
      /><br/>
      <button onClick={handleSubmit}>Send to API</button>

      {response && (
        <div style={{ marginTop: "2rem" }}>
          <h3>API Response:</h3>
          <pre>{JSON.stringify(response, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}

export default App;

5. Step 3: Handle CORS in FastAPI

To allow your React app to communicate with FastAPI, add CORS middleware.

In main.py:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Or specify your React domain
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Now you can safely send requests from the React frontend to the Python backend.


6. Step 4: Test the Full-Stack Setup

Run both:

# Terminal 1
cd backend
uvicorn main:app --reload

# Terminal 2
cd frontend
npm start

Visit http://localhost:3000, input a few test values, and you’ll see your React frontend send POST requests to the FastAPI endpoint — and receive structured responses instantly.


7. Step 5: Automatic Swagger API

One of FastAPI’s biggest advantages is that your API automatically generates documentation.

Visit:

Every endpoint, model, and parameter is described clearly — no manual setup needed.


8. Step 6: Optional – Containerize with Docker

To streamline deployment, you can containerize both frontend and backend:

# backend/Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install fastapi uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# frontend/Dockerfile
FROM node:20
WORKDIR /app
COPY . .
RUN npm install && npm run build
CMD ["npm", "start"]

Then run both services with Docker Compose for local orchestration.


9. Conclusion

Combining React and FastAPI provides developers with one of the cleanest, fastest, and most flexible full-stack workflows available today.

  • React handles interactive, real-time UIs.
  • FastAPI powers efficient, async-ready, Python-based APIs.
  • Swagger docs come built-in, saving hours of manual work.

Whether you’re prototyping a dashboard, building a SaaS product, or integrating ML models into your backend, this stack gives you everything you need — clarity, speed, and simplicity.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top