FastAPI with Django: Build a Separate API for React
Prepare a Django-backed FastAPI API for a separate React frontend with ASGI composition, CORS, schemas, database boundaries, and token authentication.
A React frontend on a separate domain needs a clear API boundary. FastAPI can provide that boundary while Django continues to own the existing website, administration, users, migrations, and database models.
This article explains a practical architecture for adding FastAPI to an existing Django project. It uses the current Coding Bowl repository as context, but the examples are design guidance only. FastAPI has not been added to this repository yet.
If you need the FastAPI fundamentals first, read FastAPI Basics: Build Your First Typed Python API.
The target architecture
There are three separate concerns:
React app FastAPI API Django site
app.example.com ─────▶ api.example.com and www.example.com
public and private admin and server pages
React should not connect directly to Django’s database. It calls documented API endpoints. FastAPI validates the request, applies authentication and authorization rules, calls the application layer, and returns a response model.
Django remains the system of record for the first version:
- Django owns the
Postmodel, migrations, admin, and existing server-rendered pages. - FastAPI exposes a deliberate API contract instead of returning Django model objects directly.
- React consumes JSON from FastAPI.
- A later architecture decision can split FastAPI into its own service if independent scaling becomes necessary.
Public and protected endpoints
Start with a small contract:
GET /api/posts/
GET /api/posts/{slug}/
GET /api/me/
The first two endpoints are public. They return published posts only and should expose a stable response shape rather than every internal database field.
GET /api/me/ is protected. It returns basic information about the currently authenticated user and demonstrates the authentication boundary without inventing a saved-posts feature that does not exist yet.
Compose Django and FastAPI at the ASGI boundary
The existing Django project already has an ASGI application at config.asgi:application. A future composition layer could mount FastAPI under /api and keep Django responsible for all other paths:
import os
import django
from fastapi import FastAPI
from django.core.asgi import get_asgi_application
from starlette.applications import Starlette
from starlette.routing import Mount
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
django_asgi_app = get_asgi_application()
fastapi_app = FastAPI(title='Blog API')
application = Starlette(
routes=[
Mount('/api', app=fastapi_app),
Mount('/', app=django_asgi_app),
]
)
This is an illustrative composition example, not a change already made to the repository. The exact implementation should be tested against Django’s URL handling, static/media behavior, health checks, and deployment server before it replaces the current config.asgi:application entry point.
The order matters: /api must be matched before the catch-all Django mount. A production implementation should also confirm how the reverse proxy sets the forwarded protocol and host headers.
Initialize Django before importing models
FastAPI route modules that use Django models must initialize Django before importing those models:
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from blog.models import Post # noqa: E402
Importing a model too early can produce AppRegistryNotReady errors because Django’s application registry has not finished loading. In a real project, keep this initialization in one application entry point and make the import order obvious.
Return API schemas, not model objects
The API should define the fields React is allowed to depend on:
from datetime import datetime
from pydantic import BaseModel, ConfigDict
class PostResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
title: str
slug: str
excerpt: str
published_at: datetime
from_attributes=True allows Pydantic to build the response from an object with attributes, such as a Django model instance. The response model is still an API boundary: adding a private model field does not automatically expose it to React.
Read published posts safely
For a synchronous FastAPI route, a small service function can use Django’s synchronous ORM. The exact import and dependency wiring will depend on how the final ASGI application is composed:
from fastapi import APIRouter
from blog.models import Post
router = APIRouter(prefix='/posts', tags=['posts'])
@router.get('/', response_model=list[PostResponse])
def list_posts() -> list[PostResponse]:
posts = (
Post.objects.published()
.select_related('author', 'category')
.order_by('-published_at')[:20]
)
return [PostResponse.model_validate(post) for post in posts]
Do not return every row without a limit. Add pagination before the public API becomes a high-volume client dependency.
If the route is declared with async def, do not call blocking synchronous ORM work directly in the event loop. Use Django’s supported async ORM methods where appropriate, or move synchronous work through a carefully configured sync_to_async boundary. Keep database access in a service layer so this choice is testable and consistent.
Find one post and handle missing data
The detail route should return 404 when the slug does not identify a published post:
from fastapi import HTTPException
@router.get('/{slug}', response_model=PostResponse)
def get_post(slug: str) -> PostResponse:
post = Post.objects.published().filter(slug=slug).first()
if post is None:
raise HTTPException(status_code=404, detail='Post not found')
return PostResponse.model_validate(post)
The API should not reveal whether a draft exists. Filtering through the published queryset before checking the result keeps draft content private.
CORS for a separate React domain
Browsers enforce the same-origin policy. If React runs at https://app.example.com and FastAPI runs at https://api.example.com, FastAPI must explicitly allow the React origin:
from fastapi.middleware.cors import CORSMiddleware
fastapi_app.add_middleware(
CORSMiddleware,
allow_origins=['https://app.example.com'],
allow_credentials=False,
allow_methods=['GET', 'POST', 'PUT', 'DELETE'],
allow_headers=['Authorization', 'Content-Type'],
)
Do not use allow_origins=['*'] for a production authenticated API. Keep the approved frontend origin in an environment variable and validate the deployed value. CORS is a browser permission mechanism; it is not authentication and it does not protect the API from non-browser clients.
Token authentication for private endpoints
Django session cookies do not automatically become FastAPI authentication. For a separate React domain, use an explicit token contract:
- The user signs in through the chosen identity flow.
- The client receives a short-lived access token and, if needed, a refresh token.
- React sends the access token in the
Authorizationheader. - FastAPI validates the token signature, issuer, audience, expiry, and relevant claims.
- The API maps the subject claim to the Django user and checks permissions.
Authorization: Bearer <access-token>
The project should choose one authority for issuing tokens. That may be Django with a reviewed token library or a dedicated identity provider. Do not invent a home-grown signing scheme or place a signing secret in React. Token validation belongs on the server, and protected endpoints should return 401 for missing or invalid credentials and 403 when an authenticated user lacks permission.
The first protected example is deliberately small:
@fastapi_app.get('/api/me/', response_model=UserResponse)
def current_user(user: AuthenticatedUser = Depends(get_current_user)) -> UserResponse:
return UserResponse.model_validate(user)
AuthenticatedUser, get_current_user, and UserResponse are placeholders for the project’s reviewed authentication design. They are not implemented in the current Django repository.
Docker and deployment boundaries
Adding FastAPI changes more than Python imports. Before deployment, decide whether the API and Django site share one container or run as separate services.
Sharing one container is a reasonable first step when:
- Django and FastAPI use the same database and release cycle.
- One ASGI process can serve both applications reliably.
- The API does not need independent scaling yet.
Separate services become more attractive when the API needs independent scaling, a different release cadence, or isolated resource limits. Either way, keep database migrations owned by Django and keep secrets in the platform secret store.
Test the contract before building React
Before connecting the frontend, test the API boundary independently:
- Public list returns only published posts.
- Public detail returns
404for an unknown or draft slug. - Response fields match the documented Pydantic schema.
- CORS allows the approved React origin and rejects unapproved origins.
- Missing, expired, or invalid tokens return
401. - Authenticated users can access
/api/me/without exposing another user’s data. - Database failures produce a controlled error without leaking credentials or connection strings.
Use FastAPI’s test client or an HTTP client in a focused test suite. These tests should run before React depends on the endpoint shape.
What is not implemented yet
This article describes the preparation path. The current repository still serves its public pages through Django, and it does not yet contain FastAPI routes, CORS configuration, token issuance, or a React application.
The safe implementation order is:
- Agree on the API response contract.
- Add a minimal FastAPI application without changing existing Django routes.
- Add one public read-only post endpoint.
- Test ASGI composition and database access.
- Add authentication and
/api/me/. - Configure the React origin and CORS in each environment.
- Connect React only after the API contract and tests are stable.
That sequence keeps the existing site working while creating a clear API boundary for the frontend.