Monday, 22 December 2025

FastAPI Microservices Setup

 Below is a real-world FastAPI microservices setup, explained step by step, and mapped to how companies actually do it in production. I’ll also relate it to Spring Boot microservices, so it’s easy to grasp.


FastAPI Microservices Setup (Production-Ready Guide)

1️⃣ What Is a FastAPI Microservices Architecture?

Instead of one large backend, you create multiple small FastAPI services, each responsible for one business capability.

Example services:

  • Auth Service

  • User Service

  • Notification Service

  • Event / Integration Service

  • Reporting Service

Each service:

  • Has its own codebase

  • Has its own database (recommended)

  • Can be deployed and scaled independently


2️⃣ High-Level Architecture

Frontend (Angular / React / Mobile) ↓ API Gateway ↓ ┌────────┬─────────┬──────────┐ | Auth | Users | Events | FastAPI services |Service | Service | Service | └────────┴─────────┴──────────┘ ↓ Databases / Queues / Caches

3️⃣ Example Microservices Folder Structure

microservices/ │ ├── api-gateway/ │ └── app/ │ └── main.py │ ├── auth-service/ │ └── app/ │ ├── main.py │ └── api/ │ ├── user-service/ │ └── app/ │ ├── main.py │ └── api/ │ ├── event-service/ │ └── app/ │ ├── main.py │ └── api/ │ ├── docker-compose.yml └── README.md

👉 Each service is a separate FastAPI app.


4️⃣ Service-to-Service Communication

Option 1: REST (Most Common)

  • HTTP calls between services

  • Use async HTTP clients (httpx)

User Service → Auth Service

Option 2: Message Queue (Recommended for scale)

  • Kafka / RabbitMQ / AWS SQS

  • Event-driven communication

Event Service → Queue → Notification Service

5️⃣ API Gateway (Very Important)

Companies use:

  • Nginx

  • Kong

  • FastAPI Gateway

Responsibilities:

  • Routing

  • Authentication

  • Rate limiting

  • Logging

Simple FastAPI Gateway Example

@app.api_route("/{path:path}", methods=["GET", "POST"]) async def proxy(path: str, request: Request): async with httpx.AsyncClient() as client: response = await client.request( request.method, f"http://user-service/{path}", headers=request.headers.raw, content=await request.body() ) return Response(response.content)

6️⃣ Authentication Strategy

Central Auth Service (Recommended)

Flow:

  1. User logs in → Auth Service

  2. JWT token issued

  3. Other services validate JWT

Each service:

  • Validates token

  • Does not store auth logic

📌 Same idea as Spring Security + JWT.


7️⃣ Database Strategy

Best practice:

  • One database per service

Examples:

  • Auth Service → PostgreSQL

  • User Service → MongoDB

  • Event Service → NoSQL / Kafka

❌ Avoid shared databases between services.


8️⃣ Async & Performance Setup

Run services using:

Gunicorn + Uvicorn workers

Example:

gunicorn app.main:app -k uvicorn.workers.UvicornWorker -w 4

9️⃣ Docker Setup (Per Service)

Dockerfile (Common for all services)

FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY app app CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

🔟 docker-compose (Local Development)

version: "3.8" services: auth-service: build: ./auth-service ports: - "8001:8000" user-service: build: ./user-service ports: - "8002:8000" event-service: build: ./event-service ports: - "8003:8000"

1️⃣1️⃣ Configuration Management

Use:

  • .env files

  • Environment variables

  • Secrets manager (in prod)

Example:

AUTH_SERVICE_URL=http://auth-service:8000

1️⃣2️⃣ Logging & Monitoring

Production services include:

  • Structured logging

  • Request tracing (request ID)

  • Metrics (Prometheus)

  • Central log aggregation


1️⃣3️⃣ Scaling Strategy

  • Stateless services

  • Horizontal scaling

  • Kubernetes HPA

  • Load balancing via ingress


1️⃣4️⃣ FastAPI vs Spring Boot Microservices

AspectFastAPISpring Boot
Startup timeVery fastSlower
Resource usageLowHigher
AsyncSimpleComplex
Enterprise toolingModerateExcellent

Many companies use:

Spring Boot → Core services FastAPI → Integration & API services

1️⃣5️⃣ Common Mistakes to Avoid

❌ Sharing databases
❌ Tight coupling between services
❌ Missing API gateway
❌ Blocking calls in async routes
❌ No centralized auth


Final Thoughts

FastAPI microservices are:

  • Lightweight

  • Fast

  • Easy to scale

  • Perfect for integration-heavy systems

For someone with your background:

  • Spring Boot → Core business logic

  • FastAPI → Microservices, integrations, ML APIs

This combo is very powerful in modern architectures.

FastAPI Project Structure

 

Production Best Practices

1️⃣ Recommended Folder Structure

fastapi-app/ │ ├── app/ │ ├── main.py # Entry point (like SpringBootApplication) │ │ │ ├── core/ # Core configs (security, settings) │ │ ├── config.py # App settings (env based) │ │ ├── security.py # Auth, JWT, OAuth2 │ │ └── logging.py │ │ │ ├── api/ # API layer (Controllers) │ │ ├── v1/ │ │ │ ├── router.py # API router aggregation │ │ │ └── endpoints/ │ │ │ ├── users.py │ │ │ ├── auth.py │ │ │ └── health.py │ │ │ ├── models/ # DB models (Entities) │ │ ├── user.py │ │ └── base.py │ │ │ ├── schemas/ # Pydantic schemas (DTOs) │ │ ├── user.py │ │ └── auth.py │ │ │ ├── services/ # Business logic (Service layer) │ │ ├── user_service.py │ │ └── auth_service.py │ │ │ ├── repositories/ # DB access layer │ │ └── user_repo.py │ │ │ ├── db/ # Database setup │ │ ├── session.py │ │ └── init_db.py │ │ │ ├── middlewares/ # Custom middleware │ │ └── request_log.py │ │ │ ├── utils/ # Utilities/helpers │ │ └── date_utils.py │ │ │ └── tests/ # Unit & integration tests │ └── test_users.py │ ├── requirements.txt ├── Dockerfile ├── docker-compose.yml ├── .env └── README.md

2️⃣ Mapping to Spring Boot (So It Feels Familiar)

Spring BootFastAPI
@SpringBootApplicationmain.py
Controllerapi/endpoints
Serviceservices
Repositoryrepositories
Entitymodels
DTOschemas
application.ymlconfig.py / .env
Filtersmiddlewares

3️⃣ main.py – Application Entry Point

from fastapi import FastAPI from app.api.v1.router import api_router app = FastAPI(title="FastAPI App") app.include_router(api_router, prefix="/api/v1")

➡ Similar to:

@SpringBootApplication public class App { }

4️⃣ Router Aggregation (Like Controller Scanning)

api/v1/router.py

from fastapi import APIRouter from app.api.v1.endpoints import users, auth, health api_router = APIRouter() api_router.include_router(users.router, prefix="/users", tags=["Users"]) api_router.include_router(auth.router, prefix="/auth", tags=["Auth"]) api_router.include_router(health.router, prefix="/health", tags=["Health"])

5️⃣ Controller Layer (Endpoints)

api/v1/endpoints/users.py

from fastapi import APIRouter from app.schemas.user import UserCreate router = APIRouter() @router.post("/") def create_user(user: UserCreate): return {"message": "User created"}

6️⃣ Schema (DTO)

schemas/user.py

from pydantic import BaseModel class UserCreate(BaseModel): name: str email: str

7️⃣ Service Layer (Business Logic)

services/user_service.py

def create_user(user): # business rules here return user

8️⃣ Repository Layer (DB Access)

repositories/user_repo.py

def save(user): pass

9️⃣ Dependency Injection (FastAPI Style)

from fastapi import Depends def get_user_service(): return UserService() @router.get("/{id}") def get_user(id: int, service=Depends(get_user_service)): return service.find(id)

➡ Similar concept to @Autowired.


🔟 Environment Configuration

.env

DB_URL=mongodb://localhost:27017/app JWT_SECRET=secret

config.py

from pydantic import BaseSettings class Settings(BaseSettings): DB_URL: str JWT_SECRET: str settings = Settings()

1️⃣1️⃣ Testing Structure

tests/ ├── test_users.py └── conftest.py

Uses:

  • pytest

  • TestClient


1️⃣2️⃣ Production-Grade Tips

✅ Keep business logic out of controllers
✅ Use async DB drivers
✅ Version your APIs (/v1)
✅ Use dependency injection properly
✅ Add middleware for logging
✅ Use Docker for consistency


1️⃣3️⃣ Minimal Structure (For Small Services)

app/ ├── main.py ├── routes.py ├── schemas.py └── services.py

Use this only for small microservices.


Final Thoughts

FastAPI doesn’t force structure like Spring Boot, but teams must enforce discipline.

If you follow the above structure:

  • Code stays clean

  • Team collaboration improves

  • Scaling becomes easy

FastAPI Interview Questions and Answers (Beginner to Advanced)

FastAPI has quickly become one of the most popular Python frameworks for building high-performance APIs. As a result, FastAPI interview questions are now common in backend, microservices, and AI/ML roles.

This post covers commonly asked FastAPI interview questions with simple and clear answers, from basic concepts to advanced topics.


1️⃣ What is FastAPI?

FastAPI is a modern, high-performance Python web framework used to build REST APIs quickly.
It is built on Starlette for web handling and Pydantic for data validation.

Key features:

  • Fast performance

  • Automatic API documentation

  • Built-in request validation

  • Async support


2️⃣ Why is FastAPI faster than Flask or Django?

FastAPI is faster because:

  • It uses ASGI instead of WSGI

  • Supports async/await

  • Uses Uvicorn (high-performance server)

  • Minimizes blocking IO

This makes FastAPI ideal for high-concurrency APIs.


3️⃣ What is ASGI and how is it different from WSGI?

WSGIASGI
SynchronousAsynchronous
One request per threadEvent-loop based
Used by Flask, DjangoUsed by FastAPI

FastAPI uses ASGI, enabling better scalability.


4️⃣ What are Pydantic models?

Pydantic models are used for:

  • Request body validation

  • Response validation

  • Type enforcement

Example:

class User(BaseModel): name: str age: int

FastAPI automatically validates incoming JSON against this model.


5️⃣ How does FastAPI generate Swagger documentation?

FastAPI automatically generates OpenAPI (Swagger) documentation using:

  • Python type hints

  • Route definitions

  • Pydantic models

Available at:

  • /docs (Swagger UI)

  • /redoc (ReDoc)


6️⃣ What is dependency injection in FastAPI?

Dependency Injection (DI) allows reusable components like:

  • Database sessions

  • Authentication logic

  • Common validations

Example:

Depends(get_db)

It improves code reusability and testability.


7️⃣ How do you handle authentication in FastAPI?

FastAPI supports:

  • OAuth2

  • JWT

  • API Keys

  • Basic Auth

It provides built-in security utilities like:

OAuth2PasswordBearer

8️⃣ What is the difference between def and async def in FastAPI?

defasync def
BlockingNon-blocking
CPU-bound tasksIO-bound tasks
SimplerHigh concurrency

Use async def when calling:

  • Databases

  • External APIs

  • Message queues


9️⃣ How does FastAPI handle request validation errors?

FastAPI:

  • Automatically validates requests

  • Returns HTTP 422 (Unprocessable Entity)

  • Provides clear error messages

No manual validation code is required.


🔟 How do you connect FastAPI to a database?

FastAPI supports:

  • SQLAlchemy (SQL)

  • Motor (MongoDB)

  • Async ORMs

Typically:

  • Create a DB session dependency

  • Inject it using Depends()


1️⃣1️⃣ How do you write unit tests in FastAPI?

FastAPI uses:

  • pytest

  • TestClient

Example:

def test_health(): response = client.get("/health") assert response.status_code == 200

1️⃣2️⃣ How is FastAPI deployed in production?

Typical production setup:

Nginx ↓ Gunicorn + Uvicorn workers ↓ FastAPI app

Often containerized using Docker and orchestrated with Kubernetes.


1️⃣3️⃣ How does FastAPI compare to Spring Boot?

FastAPISpring Boot
PythonJava
Async-firstThread-based
Minimal configHeavy config
Fast developmentEnterprise stability

Many companies use both together.


1️⃣4️⃣ What are background tasks in FastAPI?

Background tasks allow execution after response is sent.

Used for:

  • Sending emails

  • Logging

  • Notifications

Example:

BackgroundTasks

1️⃣5️⃣ What are common FastAPI interview mistakes?

❌ Using def instead of async def
❌ Blocking calls inside async routes
❌ Ignoring dependency injection
❌ Not handling exceptions properly
❌ Poor project structure


Advanced FastAPI Interview Questions (For Experienced Devs)

  • How does FastAPI handle concurrency internally?

  • How do you implement rate limiting?

  • How do you use middleware in FastAPI?

  • How do you secure APIs using OAuth2 + JWT?

  • How do you scale FastAPI horizontally?

  • How do you integrate FastAPI with Kafka / RabbitMQ?


Final Thoughts

FastAPI is not just a framework, it’s a modern API philosophy:

  • Clean code

  • High performance

  • Strong typing

  • Developer-friendly

FastAPI vs Spring Boot

 

FastAPI vs Spring Boot: Which One Should You Choose?

In the world of backend development, Spring Boot has been the gold standard for years—especially in enterprise Java applications.
But recently, FastAPI has gained massive popularity in the Python ecosystem for building modern APIs.

So the big question is:

👉 FastAPI vs Spring Boot — which one is better?
👉 Should Java developers care about FastAPI?

Let’s compare them from a real-world, production perspective.


What is Spring Boot?

Spring Boot is a Java-based framework that simplifies building enterprise-grade applications.

It provides:

  • Dependency Injection

  • Security

  • Transaction management

  • Database integration

  • Production-ready tooling

Spring Boot is widely used in:

  • Banking

  • Insurance

  • Government systems

  • Large enterprises


What is FastAPI?

FastAPI is a modern Python framework designed specifically for building high-performance APIs.

It focuses on:

  • Speed

  • Simplicity

  • Automatic validation

  • Automatic documentation

FastAPI is widely used in:

  • Microservices

  • Startups

  • AI / ML platforms

  • Integration-heavy systems


Core Comparison: FastAPI vs Spring Boot

1️⃣ Language & Ecosystem

AspectFastAPISpring Boot
LanguagePythonJava
EcosystemLightweight, fastEnterprise-grade
VerbosityVery lowHigh

Verdict:
Spring Boot is structured and strict. FastAPI is flexible and fast to develop.


2️⃣ Development Speed

FastAPISpring Boot
BoilerplateMinimalHeavy
API setup timeMinutes30–60 minutes
ConfigurationVery lessExtensive

FastAPI allows teams to ship APIs much faster.


3️⃣ Performance & Concurrency

FastAPISpring Boot
Concurrency modelAsync (event loop)Thread-based
Best forIO-heavy APIsCPU-heavy logic
LatencyLowerSlightly higher

FastAPI shines in:

  • Webhooks

  • Event ingestion

  • High-concurrency APIs


4️⃣ Validation & API Contracts

FastAPISpring Boot
Request validationAutomaticAnnotations
OpenAPI specAuto-generatedManual setup
Error messagesClearVerbose

FastAPI’s validation feels like:

DTO + Validation + Swagger — without extra configuration


5️⃣ API Documentation (Major Difference)

FastAPI provides:

  • Swagger UI at /docs

  • ReDoc at /redoc

No extra setup needed.

In Spring Boot:

  • Swagger/OpenAPI requires manual configuration

  • Docs often go out of sync

📌 Frontend teams love FastAPI for this reason alone.


6️⃣ Async Support

FastAPISpring Boot
Async supportNativeWebFlux
ComplexitySimpleHigh
Learning curveEasySteep

Many Java teams avoid WebFlux due to complexity, while FastAPI makes async natural.


7️⃣ Enterprise Features

FeatureFastAPISpring Boot
SecurityGoodExcellent
TransactionsManualStrong
AOP
Dependency InjectionBasicAdvanced

Spring Boot clearly wins in enterprise governance and safety.


8️⃣ Database & ORM Support

FastAPISpring Boot
ORMSQLAlchemyHibernate
MongoDBMotorSpring Data Mongo
MaturityMediumVery High

Spring Data is more mature for large teams and long-term projects.


When to Use FastAPI?

Choose FastAPI if you are building:

  • Microservices

  • API gateways

  • Integration platforms

  • Event-driven systems

  • AI / ML APIs

  • Backend for React / Angular apps


When to Use Spring Boot?

Choose Spring Boot if you are building:

  • Enterprise systems

  • Banking or finance apps

  • Complex transactional workflows

  • Long-term systems (10–15 years lifespan)

  • Large, regulated platforms


Real-World Architecture (Very Common)

Many companies use both together:

Spring Boot → Core business logic FastAPI → API layer, integrations, ML services

This hybrid approach offers stability + speed.


Final Verdict

FastAPI is not a replacement for Spring Boot.
It is a complement.

  • Spring Boot = Enterprise backbone

  • FastAPI = Fast, modern API layer

For experienced Java developers, learning FastAPI adds a powerful new skill and opens doors to modern architectures and AI-driven systems.


Conclusion

If you want:

  • Faster development

  • Cleaner APIs

  • Better API documentation

  • Modern async architecture

👉 FastAPI is worth learning.

If you want:

  • Enterprise reliability

  • Strong governance

  • Long-term maintainability

👉 Spring Boot remains unbeatable.

Sunday, 21 December 2025

What is FastAPI

 

What is FastAPI? A Beginner-Friendly Guide

In today’s world of web and mobile applications, APIs are the backbone of modern software. If you’re a Python developer—or planning to become one—you’ve probably heard about FastAPI.

But what exactly is FastAPI, and why are companies adopting it so fast?
Let’s break it down in simple terms.


What is FastAPI?

FastAPI is a modern Python web framework used to build REST APIs quickly and efficiently.

It is:

  • 🚀 Fast (high performance)

  • 🧠 Smart (automatic validation & documentation)

  • Easy to use (less boilerplate code)

FastAPI was created to solve common problems developers face with older frameworks like Flask and Django when building APIs at scale.


Why is it called FastAPI?

FastAPI is fast because it is built on top of:

  • Starlette → for web handling

  • Pydantic → for data validation

This combination makes FastAPI one of the fastest Python frameworks, with performance comparable to Node.js and Go for API workloads.


A Simple FastAPI Example

Here’s how easy it is to create an API:

from fastapi import FastAPI app = FastAPI() @app.get("/hello") def hello(): return {"message": "Hello World"}

Run it, and your API is live!


Automatic API Documentation (Big Advantage)

One of FastAPI’s biggest strengths is automatic documentation.

Without writing any extra code, you get:

  • Swagger UI/docs

  • ReDoc UI/redoc

This is extremely useful for:

  • Frontend developers

  • QA teams

  • API consumers

Your API docs are always up-to-date.


Built-in Data Validation

FastAPI automatically validates incoming requests using Python type hints.

Example:

from pydantic import BaseModel class User(BaseModel): name: str age: int

If incorrect data is sent, FastAPI returns a clear error message—no manual checks needed.


Async Support (High Concurrency)

FastAPI supports async / await natively.

This makes it ideal for:

  • Webhooks

  • Event ingestion

  • API integrations

  • High traffic systems

Example:

@app.get("/items") async def get_items(): return ["item1", "item2"]

Where is FastAPI Used in Real Life?

Companies use FastAPI in production for:

  • 🔹 Microservices

  • 🔹 Backend for React / Angular apps

  • 🔹 CRM integrations (Salesforce, Marketo, etc.)

  • 🔹 Event processing systems

  • 🔹 AI / ML model serving

  • 🔹 API gateways

Many startups and even large companies use FastAPI alongside Java Spring Boot systems.


FastAPI vs Flask vs Django

FeatureFastAPIFlaskDjango
Performance⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Auto Docs
Validation⚠️
Async⚠️
Best forAPIsSmall appsFull web apps

When Should You Use FastAPI?

Use FastAPI if you:

  • Need to build APIs quickly

  • Want high performance

  • Work on microservices

  • Are building AI/ML APIs

  • Want clean and maintainable code


When Not to Use FastAPI?

Avoid FastAPI if:

  • You need a full server-side HTML framework

  • You want heavy built-in admin panels (Django is better here)


Final Thoughts

FastAPI has become a game-changer in the Python ecosystem.

It combines:

  • ⚡ Speed

  • 🧩 Simplicity

  • 📄 Excellent documentation

  • 🛡️ Strong validation

If you are a backend developer or want to build scalable APIs in Python, FastAPI is absolutely worth learning.