DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

CORS & API Contracts: Preparing Your Backend for Frontend Collaboration

What is CORS?

When a React frontend on localhost:3000 tries to
call an API on localhost:8000, the browser blocks it.
That's CORS protection and it's a good thing.

But your own frontend should be allowed through.
That's what CORS configuration does.

Enabling CORS in FastAPI

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

Enter fullscreen mode Exit fullscreen mode

One middleware call, every response now includes
the correct CORS headers automatically.

API Contract : camelCase for Frontend

Backend Python uses snake_case by default.
But JavaScript frontends expect camelCase.

Instead of:

  • created_at -> use createdAt
  • category_id -> use categoryId
  • access_token -> use accessToken

Small change, big impact on frontend collaboration.

The Consistent Response Shape

Every endpoint follows the same contract:

GET /items returns:

{
  "data": [...],
  "count": 2
}
Enter fullscreen mode Exit fullscreen mode

POST /auth/login returns:

{
  "accessToken": "...",
  "tokenType": "bearer",
  "email": "user@example.com"
}
Enter fullscreen mode Exit fullscreen mode

Frontend developers can rely on these shapes
without reading your source code.

The OpenAPI Contract

FastAPI auto generates an OpenAPI spec at /openapi.json
This is your official API contract
frontend teams can import it into Postman
and know exactly what every endpoint expects and returns.

Postman Tests

Home endpoint showing CORS enabled

home endpoint

Items with camelCase fields

camelCase fields

Lessons

CORS and consistent field naming aren't
afterthoughts, they're part of being a
good backend developer who works well with
frontend teams. Your API is only as good
as how easy it is to integrate with.

Day 23 done. 7 more to go.

GDGoCBowen30dayChallenge

Top comments (0)