issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1
section: Interview Questions / interview questions
08 Jun 2026
placement brief / Interview Questions / interview questions / 08 Jun 2026

Top 40 FastAPI Interview Questions 2026

FastAPI is the fastest-growing Python web framework, favored for its performance, automatic OpenAPI documentation, and type safety. Candidates report that...

Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

Last Updated: June 2026 | Level: Freshers to 3 Years Experience | Read Time: ~18 min

FastAPI is the fastest-growing Python web framework, favored for its performance, automatic OpenAPI documentation, and type safety. Candidates report that Pydantic models, dependency injection, async/await patterns, and JWT authentication are the most frequently tested FastAPI interview topics.

Pair with Flask Interview Questions 2026 and Python Interview Questions 2026. Confirm current interview requirements on the official careers portal of your target company.


Table of Contents

  1. FastAPI Basics (Q1-Q12)
  2. Pydantic and Validation (Q13-Q20)
  3. Dependency Injection and Auth (Q21-Q28)
  4. Async, Background Tasks, and WebSockets (Q29-Q35)
  5. Database, Middleware, and Deployment (Q36-Q40)
  6. Mock Interview: 5 Questions
  7. FAQ

FastAPI Basics

Q1. What is FastAPI and what are its key features? Easy

FeatureDescription
PerformanceComparable to Go and Node.js (async I/O)
Type hintsFull Python type hints support
Auto-validationPydantic validates request/response models
Auto-docsOpenAPI (Swagger UI) + ReDoc generated automatically
Dependency injectionBuilt-in DI system
StandardsOpenAPI, JSON Schema, OAuth2

Q2. What is a minimal FastAPI application? Easy

from fastapi import FastAPI

app = FastAPI(title="My API", version="1.0.0")

@app.get("/")
def root():
    return {"message": "Hello, World!"}

@app.get("/health")
async def health():
    return {"status": "ok"}

# Run: uvicorn main:app --reload
# Docs: http://localhost:8000/docs
# ReDoc: http://localhost:8000/redoc
# OpenAPI JSON: http://localhost:8000/openapi.json

Q3. What are path parameters and query parameters? Easy

from fastapi import FastAPI, Query, Path

app = FastAPI()

# Path parameter
@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id}

# Path parameter with validation
@app.get("/items/{item_id}")
def get_item(
    item_id: int = Path(title="Item ID", ge=1, le=1000)
):
    return {"item_id": item_id}

# Query parameters
@app.get("/search")
def search(
    q: str,
    limit: int = Query(default=10, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
    active: bool = True
):
    return {"q": q, "limit": limit, "offset": offset, "active": active}
# GET /search?q=python&limit=20

Q4. What are HTTP methods in FastAPI? Easy

@app.get("/items/{id}")      # READ
@app.post("/items")          # CREATE
@app.put("/items/{id}")      # REPLACE
@app.patch("/items/{id}")    # PARTIAL UPDATE
@app.delete("/items/{id}")   # DELETE
@app.options("/items")       # OPTIONS
@app.head("/items/{id}")     # HEAD

# With multiple methods
@app.api_route("/flexible", methods=["GET", "POST"])
def flexible(request: Request):
    pass

Q5. What are response models? Medium

from pydantic import BaseModel

class UserOut(BaseModel):
    id: int
    name: str
    email: str
    # No password field!

class UserIn(BaseModel):
    name: str
    email: str
    password: str  # input only

@app.post("/users", response_model=UserOut, status_code=201)
def create_user(user: UserIn):
    # save to DB
    return UserOut(id=1, name=user.name, email=user.email)
    # password is automatically excluded from response

Q6. What are status codes in FastAPI? Easy

from fastapi import status

@app.post("/users", status_code=status.HTTP_201_CREATED)
@app.delete("/users/{id}", status_code=status.HTTP_204_NO_CONTENT)

# Dynamic status codes with JSONResponse
from fastapi.responses import JSONResponse

@app.get("/conditional")
def conditional(exists: bool):
    if not exists:
        return JSONResponse(
            status_code=status.HTTP_404_NOT_FOUND,
            content={"error": "Not found"}
        )
    return {"data": "found"}

Q7. How do you handle errors in FastAPI? Medium

from fastapi import HTTPException

@app.get("/users/{user_id}")
def get_user(user_id: int):
    user = find_user(user_id)
    if not user:
        raise HTTPException(
            status_code=404,
            detail="User not found",
            headers={"X-Error": "user_not_found"}
        )
    return user

# Custom exception handler
from fastapi import Request
from fastapi.responses import JSONResponse

class DatabaseError(Exception):
    def __init__(self, message: str):
        self.message = message

@app.exception_handler(DatabaseError)
async def database_error_handler(request: Request, exc: DatabaseError):
    return JSONResponse(
        status_code=503,
        content={"error": "Database unavailable", "detail": exc.message}
    )

Q8. What is path operation ordering? Medium

# ORDER MATTERS: more specific routes first
@app.get("/users/me")        # MUST be before /{user_id}
def get_current_user():
    return {"user": "current"}

@app.get("/users/{user_id}")  # catches everything else
def get_user(user_id: str):
    return {"user_id": user_id}

# If reversed, "me" would be captured as user_id

Q9. What are tags and routers? Medium

from fastapi import APIRouter

users_router = APIRouter(prefix="/users", tags=["users"])

@users_router.get("/")
def list_users(): pass

@users_router.get("/{id}")
def get_user(id: int): pass

# Include in main app
app.include_router(users_router)
app.include_router(
    admin_router,
    prefix="/admin",
    tags=["admin"],
    dependencies=[Depends(verify_admin)]
)

Q10. What are custom headers and cookies? Medium

from fastapi import Header, Cookie, Response

@app.get("/items")
def get_items(
    x_token: str = Header(...),           # X-Token header (auto-converts)
    session_id: str = Cookie(None)        # session_id cookie
):
    return {"token": x_token, "session": session_id}

# Set response headers/cookies
@app.get("/set-cookie")
def set_cookie(response: Response):
    response.set_cookie(key="session_id", value="abc123", httponly=True)
    response.headers["X-Custom"] = "value"
    return {"status": "cookie set"}

Q11. What is Request in FastAPI? Medium

from fastapi import Request

@app.get("/info")
async def request_info(request: Request):
    return {
        "method": request.method,
        "url": str(request.url),
        "client": request.client.host,
        "headers": dict(request.headers),
        "path_params": request.path_params,
        "query_params": dict(request.query_params),
    }

# Get raw body
@app.post("/raw")
async def raw_body(request: Request):
    body = await request.body()
    return {"length": len(body)}

Q12. Predict the output: Easy

from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/greet/{name}")
def greet(name: str, title: str = "Mr"):
    return {"message": f"Hello, {title} {name}"}

client = TestClient(app)
response = client.get("/greet/Aditya?title=Dr")
print(response.status_code)
print(response.json())

Output:

200
{'message': 'Hello, Dr Aditya'}

Pydantic and Validation

Q13. What is Pydantic? Easy

from pydantic import BaseModel, EmailStr, validator, field_validator
from typing import Optional
from datetime import date

class User(BaseModel):
    name: str
    email: EmailStr
    age: int
    birth_date: Optional[date] = None
    tags: list[str] = []
    
    @field_validator('age')
    @classmethod
    def age_must_be_valid(cls, v):
        if not (18 <= v <= 120):
            raise ValueError('Age must be between 18 and 120')
        return v

user = User(name="Aditya", email="[email protected]", age=25)
print(user.model_dump())
# {'name': 'Aditya', 'email': '[email protected]', 'age': 25, 'birth_date': None, 'tags': []}

Q14. What is Pydantic model configuration? Medium

from pydantic import BaseModel, ConfigDict

class UserResponse(BaseModel):
    model_config = ConfigDict(
        from_attributes=True,     # read from ORM objects (was orm_mode)
        populate_by_name=True,    # allow both field name and alias
        str_strip_whitespace=True
    )
    
    id: int
    full_name: str = Field(alias="name")  # accept "name" in input
    email_address: str = Field(alias="email")

# Works with ORM object
user = UserResponse.model_validate(orm_user)

Q15. What are nested models? Medium

class Address(BaseModel):
    street: str
    city: str
    pincode: str = Field(pattern=r'^\d{6}$')

class CreateUserRequest(BaseModel):
    name: str
    email: EmailStr
    address: Address
    shipping_addresses: list[Address] = []

# JSON body:
# {
#   "name": "Aditya",
#   "email": "[email protected]",
#   "address": {"street": "123 Main St", "city": "Delhi", "pincode": "110001"},
#   "shipping_addresses": []
# }

Q16. What are computed fields and validators? Advanced

from pydantic import BaseModel, computed_field, model_validator

class OrderItem(BaseModel):
    name: str
    price: float
    quantity: int
    discount: float = 0.0
    
    @computed_field
    @property
    def total(self) -> float:
        return self.price * self.quantity * (1 - self.discount)

class Order(BaseModel):
    items: list[OrderItem]
    
    @model_validator(mode='after')
    def check_total(self) -> 'Order':
        if not self.items:
            raise ValueError('Order must have at least one item')
        return self

Q17. What is the difference between BaseModel and dataclasses in FastAPI? Medium

FeaturePydantic BaseModelPython dataclass
ValidationAlways validatesNo validation
PerformancePydantic V2 (Rust core)Faster to create
JSON serializationBuilt-in .model_dump_json()Requires extra work
FastAPI supportFull (request/response)Limited (no nested validation)

For FastAPI API models, always use Pydantic BaseModel.


Q18. What are discriminated unions? Advanced

from typing import Annotated, Union, Literal
from pydantic import BaseModel, Field

class Cat(BaseModel):
    type: Literal['cat'] = 'cat'
    meows: bool

class Dog(BaseModel):
    type: Literal['dog'] = 'dog'
    barks: bool

Pet = Annotated[Union[Cat, Dog], Field(discriminator='type')]

@app.post("/pets")
def create_pet(pet: Pet):
    if isinstance(pet, Cat):
        return {"animal": "cat", "meows": pet.meows}
    return {"animal": "dog", "barks": pet.barks}

Q19. What are Form and File in FastAPI? Medium

from fastapi import Form, File, UploadFile

@app.post("/login")
async def login(username: str = Form(), password: str = Form()):
    return authenticate(username, password)

@app.post("/upload")
async def upload(
    file: UploadFile = File(),
    description: str = Form("")
):
    content = await file.read()
    return {
        "filename": file.filename,
        "size": len(content),
        "content_type": file.content_type
    }

# Multiple files
@app.post("/upload-multiple")
async def upload_multiple(files: list[UploadFile] = File()):
    return [{"filename": f.filename} for f in files]

Q20. Predict the output: Pydantic validation. Medium

from pydantic import BaseModel, ValidationError

class Item(BaseModel):
    name: str
    price: float
    quantity: int = 1

try:
    item = Item(name="Laptop", price="not-a-number")
except ValidationError as e:
    print(len(e.errors()))
    print(e.errors()[0]['type'])

Output:

1
float_parsing

Explanation: price="not-a-number" cannot be coerced to float. Pydantic V2 raises a ValidationError with one error of type float_parsing.


Dependency Injection and Auth

Q21. What is dependency injection in FastAPI? Medium

from fastapi import Depends

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    user = verify_token(token, db)
    if not user:
        raise HTTPException(status_code=401, detail="Not authenticated")
    return user

@app.get("/profile")
def profile(current_user: User = Depends(get_current_user)):
    return {"id": current_user.id, "name": current_user.name}

Q22. What are class-based dependencies? Advanced

class PaginationParams:
    def __init__(
        self,
        page: int = Query(default=1, ge=1),
        per_page: int = Query(default=20, ge=1, le=100)
    ):
        self.page = page
        self.per_page = per_page
        self.offset = (page - 1) * per_page

@app.get("/items")
def list_items(pagination: PaginationParams = Depends()):
    return db.items.offset(pagination.offset).limit(pagination.per_page).all()

Q23. What are sub-dependencies? Advanced

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_settings():
    return Settings()

def get_cache(settings: Settings = Depends(get_settings)):
    return RedisCache(settings.redis_url)

def get_current_user(
    db: Session = Depends(get_db),
    cache: Cache = Depends(get_cache),
    token: str = Depends(oauth2_scheme)
):
    # FastAPI builds the full dependency tree automatically
    return verify_token(token, db, cache)

Q24. How do you implement OAuth2 with JWT? Medium

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"

@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    
    token = jwt.encode(
        {"sub": user.email, "exp": datetime.utcnow() + timedelta(hours=1)},
        SECRET_KEY, algorithm=ALGORITHM
    )
    return {"access_token": token, "token_type": "bearer"}

async def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        email = payload.get("sub")
        user = get_user_by_email(email)
        if not user:
            raise HTTPException(status_code=401)
        return user
    except JWTError:
        raise HTTPException(status_code=401, detail="Invalid token")

Q25. What are security scopes? Advanced

from fastapi.security import OAuth2PasswordBearer, SecurityScopes

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"read": "Read items", "write": "Create items", "admin": "Full access"}
)

def get_current_user(
    security_scopes: SecurityScopes,
    token: str = Depends(oauth2_scheme)
):
    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    token_scopes = payload.get("scopes", [])
    
    for scope in security_scopes.scopes:
        if scope not in token_scopes:
            raise HTTPException(
                status_code=403,
                detail=f"Insufficient scope: requires {scope}"
            )
    return get_user(payload["sub"])

@app.get("/admin", dependencies=[Depends(Security(get_current_user, scopes=["admin"]))])
def admin_panel():
    return {"access": "admin"}

Q26. What is API key authentication? Medium

from fastapi import Security
from fastapi.security import APIKeyHeader

API_KEY_HEADER = APIKeyHeader(name="X-API-Key")
VALID_KEYS = {"key1": "read_only", "key2": "read_write"}

def validate_api_key(api_key: str = Security(API_KEY_HEADER)):
    if api_key not in VALID_KEYS:
        raise HTTPException(status_code=403, detail="Invalid API key")
    return {"key": api_key, "permissions": VALID_KEYS[api_key]}

@app.get("/data", dependencies=[Depends(validate_api_key)])
def get_data():
    return {"data": "protected"}

Q27. What is middleware in FastAPI? Medium

from starlette.middleware.base import BaseHTTPMiddleware
import time

class TimingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        start = time.time()
        response = await call_next(request)
        duration = time.time() - start
        response.headers["X-Process-Time"] = f"{duration:.3f}s"
        return response

app.add_middleware(TimingMiddleware)

# Built-in middleware
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://yourfrontend.com"],
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Authorization"],
)

Q28. What is lifespan management? Advanced

from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: runs before app starts serving
    print("Starting up...")
    await database.connect()
    yield  # app runs here
    # Shutdown: runs after last request
    print("Shutting down...")
    await database.disconnect()

app = FastAPI(lifespan=lifespan)

lifespan replaced the deprecated @app.on_event("startup") / @app.on_event("shutdown").


Async, Background Tasks, and WebSockets

Q29. What is the difference between async def and def in FastAPI? Medium

# def: runs in a thread pool (good for CPU-bound or blocking I/O)
@app.get("/sync")
def sync_endpoint():
    result = blocking_db_call()  # FastAPI runs in thread pool
    return result

# async def: runs on event loop (good for non-blocking I/O)
@app.get("/async")
async def async_endpoint():
    result = await async_db_call()  # truly non-blocking
    return result

# WRONG: blocking code in async endpoint
@app.get("/bad")
async def bad_endpoint():
    time.sleep(1)  # BLOCKS the event loop! Use asyncio.sleep instead
    return {}

Q30. What are background tasks? Medium

from fastapi import BackgroundTasks

def send_email_task(email: str, message: str):
    # Runs after response is sent
    send_email(email, message)

def write_audit_log(user_id: int, action: str):
    db.audit_logs.insert({'user_id': user_id, 'action': action})

@app.post("/register")
async def register(
    user: UserCreate,
    background_tasks: BackgroundTasks
):
    new_user = create_user(user)
    background_tasks.add_task(send_email_task, user.email, "Welcome!")
    background_tasks.add_task(write_audit_log, new_user.id, "registered")
    return {"id": new_user.id}  # response sent immediately

Q31. How do WebSockets work in FastAPI? Advanced

from fastapi import WebSocket, WebSocketDisconnect

class ConnectionManager:
    def __init__(self):
        self.active: list[WebSocket] = []
    
    async def connect(self, ws: WebSocket):
        await ws.accept()
        self.active.append(ws)
    
    async def disconnect(self, ws: WebSocket):
        self.active.remove(ws)
    
    async def broadcast(self, message: str):
        for ws in self.active:
            await ws.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(ws: WebSocket, client_id: int):
    await manager.connect(ws)
    try:
        while True:
            data = await ws.receive_text()
            await manager.broadcast(f"Client {client_id}: {data}")
    except WebSocketDisconnect:
        await manager.disconnect(ws)

Q32. What is asyncio.gather in FastAPI? Advanced

import asyncio

@app.get("/dashboard/{user_id}")
async def dashboard(user_id: int):
    # Run multiple async calls concurrently
    user, orders, stats = await asyncio.gather(
        get_user(user_id),
        get_orders(user_id),
        get_stats(user_id)
    )
    return {"user": user, "orders": orders, "stats": stats}

# vs sequential (slower)
user = await get_user(user_id)
orders = await get_orders(user_id)
stats = await get_stats(user_id)

Q33. What are Server-Sent Events (SSE) in FastAPI? Advanced

from fastapi.responses import StreamingResponse
import asyncio

async def event_generator(user_id: int):
    while True:
        notification = await get_notifications(user_id)
        if notification:
            yield f"data: {notification.json()}\n\n"
        await asyncio.sleep(1)

@app.get("/events/{user_id}")
async def sse_endpoint(user_id: int):
    return StreamingResponse(
        event_generator(user_id),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
    )

Q34. What is HTTPException vs raising a regular exception? Medium

# HTTPException: translates directly to HTTP response
raise HTTPException(status_code=404, detail="Not found")

# Custom exception with handler (for structured errors)
class AppException(Exception):
    def __init__(self, code: str, message: str, status_code: int = 400):
        self.code = code
        self.message = message
        self.status_code = status_code

@app.exception_handler(AppException)
async def app_exception_handler(request, exc: AppException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"code": exc.code, "message": exc.message}
    )

raise AppException("USER_NOT_FOUND", "User not found", 404)

Q35. Predict the output: dependency caching. Advanced

from fastapi import FastAPI, Depends

call_count = 0

def get_db():
    global call_count
    call_count += 1
    return {"connection": call_count}

@app.get("/test")
def test(
    db1: dict = Depends(get_db),
    db2: dict = Depends(get_db)
):
    return {"db1": db1, "db2": db2, "count": call_count}

Output: {"db1": {"connection": 1}, "db2": {"connection": 1}, "count": 1}

Explanation: FastAPI caches dependency results within a single request. Both db1 and db2 use the same get_db() call result. call_count is incremented only once.


Database, Middleware, and Deployment

Q36. How do you use SQLAlchemy with FastAPI? Medium

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase

engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)

class Base(DeclarativeBase): pass

class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))

async def get_db():
    async with AsyncSessionLocal() as session:
        yield session

@app.get("/users")
async def list_users(db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(User))
    return result.scalars().all()

Q37. What is Alembic with FastAPI? Medium

pip install alembic
alembic init alembic         # initialize
# Edit alembic.ini and env.py to point to your database URL

alembic revision --autogenerate -m "add users table"  # generate migration
alembic upgrade head          # apply all
alembic downgrade -1          # revert one

Q38. How do you test FastAPI applications? Medium

import pytest
from fastapi.testclient import TestClient
from httpx import AsyncClient, ASGITransport

client = TestClient(app)

def test_create_user():
    response = client.post("/users", json={
        "name": "Test", "email": "[email protected]"
    })
    assert response.status_code == 201
    assert response.json()["name"] == "Test"

# Async testing
@pytest.mark.anyio
async def test_async_endpoint():
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        response = await ac.get("/async-endpoint")
    assert response.status_code == 200

Q39. How do you deploy FastAPI? Medium

# Uvicorn (single process, development)
uvicorn main:app --reload

# Gunicorn with Uvicorn workers (production, multi-process)
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

# Docker (Dockerfile)
# FROM tiangolo/uvicorn-gunicorn-fastapi:python3.11
# COPY . /app

# Environment variables
# WORKERS_PER_CORE=2
# MAX_WORKERS=8

Q40. What is the difference between ASGI and WSGI? Medium

FeatureWSGIASGI
Async supportNoYes
WebSocketsNoYes
FrameworksFlask, DjangoFastAPI, Starlette, Django 4+
ServersGunicorn, uWSGIUvicorn, Hypercorn, Daphne
ConcurrencyThread-per-requestEvent loop (many requests)

FastAPI is ASGI-native. Running it behind a WSGI server (Gunicorn without uvicorn workers) loses async benefits.


Mock Interview: 5 Questions

  1. Explain FastAPI's dependency injection system. How does it handle cleanup (like closing database connections)?
  2. What happens if you use def (not async def) in a FastAPI route that calls a slow blocking operation?
  3. Implement a rate limiter as a FastAPI dependency that limits a user to 100 requests per hour.
  4. What is the difference between response_model and returning a Pydantic model directly?
  5. How would you implement field-level authorization (user can only see their own data) using FastAPI dependencies?

FAQ

Q: How fast is FastAPI compared to Flask? A: Under async I/O conditions, FastAPI can handle significantly more concurrent requests than Flask on the same hardware. Both are fast enough for most applications. The performance difference matters for high-concurrency APIs.

Q: Does FastAPI work with Django ORM? A: Not recommended. Use SQLAlchemy (async with asyncpg driver), Tortoise ORM, or databases library with FastAPI. Django ORM is designed for Django's sync request model and does not integrate cleanly with async FastAPI.

Q: What is the biggest advantage of FastAPI over other frameworks? A: Automatic interactive documentation (Swagger UI + ReDoc) generated from your code, combined with type-safe validation via Pydantic and built-in dependency injection. These three together make it uniquely developer-friendly for API development.


Related reading: Flask Interview Questions 2026 | Python Interview Questions 2026 | Django Interview Questions 2026 | Docker Interview Questions 2026

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

topic cluster

More resources in Interview Questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Open Interview Questions hubBrowse all articles

paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story with byline.

Submit your story →

ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start free mock test →
related guides
more from PapersAdda
Company Placement PapersAmazon Placement Papers 2026: SDE-1 OA, Loop and Bar Raiser Guide
19 min read
Company Placement PapersFlipkart Placement Papers 2026, Complete Guide with Solutions
14 min read
Company Placement PapersGoogle Placement Papers 2026, Complete Guide with Solutions
16 min read
Exam PatternsMicrosoft Interview Pattern Bank 2026: LRU Cache, OneDrive & AA Round
13 min read

Share this guide