Basic FastAPI Interview Questions (Freshers & 1-3 Years Experience)
1. What is FastAPI?
FastAPI is a modern, fast web framework for building APIs with Python 3.7+ based on standard Python type hints. It leverages Starlette for the web parts and Pydantic for data validation, providing high performance and automatic documentation.[1][6]
2. What are the main features of FastAPI?
Key features include high performance due to async support, automatic interactive API documentation, data validation using Pydantic, dependency injection, and type safety through Python type hints.[1][2]
3. How do you create a basic FastAPI application?
Create a basic app using the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}[5]
4. What is automatic API documentation in FastAPI?
FastAPI automatically generates interactive API documentation at /docs (Swagger UI) and /redoc using OpenAPI schema based on your route definitions and type hints.[1][2]
5. How does FastAPI achieve high performance?
FastAPI uses Starlette’s ASGI support and async/await capabilities with Python’s asyncio, making it one of the fastest Python frameworks for API development.[1][2]
6. What role does Pydantic play in FastAPI?
Pydantic provides data validation and serialization using Python type annotations. FastAPI uses Pydantic models to validate request bodies, query parameters, and generate responses.[2][6]
7. How do you define path parameters in FastAPI?
Path parameters are defined in the path using curly braces:
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
8. What are query parameters in FastAPI?
Query parameters appear after the ? in the URL. FastAPI automatically extracts and validates them using type hints:
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
Intermediate FastAPI Interview Questions (1-3 & 3-6 Years Experience)
9. What is dependency injection in FastAPI?
Dependency injection allows you to declare dependencies that FastAPI will execute and provide to your endpoints. It’s declared using the Depends() function.[2][3]
10. How do you implement dependency injection? (Zoho scenario)
In a Zoho-like SaaS application handling multiple tenants:
from fastapi import Depends
async def get_current_user(token: str):
return {"user": "john"}
@app.get("/profile")
async def profile(user = Depends(get_current_user)):
return user
11. How do you handle request body validation?
Use Pydantic models for request body validation:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return item
12. What are response models in FastAPI?
Response models define the structure of your API responses using Pydantic models, ensuring consistent output format and automatic documentation.[1]
13. How do you implement HTTPException in FastAPI?
Raise HTTPException for proper error responses:
from fastapi import HTTPException
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
14. What is the difference between sync and async endpoints?
Async endpoints (async def) handle concurrent I/O operations efficiently using asyncio, while sync endpoints (def) are blocking and better for CPU-bound tasks.[3]
15. How do you create async endpoints? (Paytm scenario)
For Paytm-like high-throughput payment APIs:
@app.get("/payments/{payment_id}")
async def get_payment(payment_id: str):
payment = await fetch_payment(payment_id)
return payment
16. What are FastAPI middleware?
Middleware processes requests before they reach your endpoints or responses before they’re sent back. Common uses include CORS, authentication, logging.[2][7]
17. How do you add middleware? (Swiggy scenario)
For Swiggy-like food delivery logging:
@app.middleware("http")
async def log_requests(request, call_next):
print(f"Request: {request.url}")
response = await call_next(request)
return response
Advanced FastAPI Interview Questions (3-6+ Years Experience)
18. How do you implement global exception handlers?
Use ExceptionHandler for centralized error handling:
@app.exception_handler(ValidationError)
async def validation_exception_handler(request, exc):
return JSONResponse(status_code=422, content={"detail": exc.errors()})
19. What is APIRouter in FastAPI?
APIRouter allows you to organize your code into modules, creating reusable router instances for different resource groups or microservices.[1]
20. How do you use APIRouter? (Atlassian scenario)
For Atlassian-like modular APIs:
router = APIRouter()
@router.get("/users/")
def get_users():
return users
app.include_router(router, prefix="/api/v1")
21. How do you implement authentication in FastAPI? (Adobe scenario)
For Adobe-like enterprise authentication:
from fastapi.security import HTTPBearer
security = HTTPBearer()
@app.get("/secure")
async def secure_endpoint(token: str = Depends(security)):
return {"message": "Secure endpoint"}
22. What are background tasks in FastAPI?
Background tasks run after sending the response to the client, useful for sending emails, logging, or cleanup operations.[1]
23. How do you implement rate limiting? (Flipkart scenario)
For Flipkart-like e-commerce APIs:
from slowapi import Limiter
limiter = Limiter(key_func=get_remote_address)
@app.get("/products")
@limiter.limit("5/minute")
async def get_products(request: Request):
return products
24. How do you handle file uploads?
Use UploadFile for handling file uploads:
@app.post("/upload")
async def upload_file(file: UploadFile):
contents = await file.read()
return {"filename": file.filename}
25. What are FastAPI tags and summaries?
Tags organize endpoints in documentation, summaries provide brief descriptions:
@app.get("/users/", tags=["users"], summary="Get all users")
def get_users():
26. How do you implement WebSockets in FastAPI?
FastAPI provides full WebSocket support:
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Hello WebSocket")
27. How do you test FastAPI applications?
Use TestClient from FastAPI.testclient and pytest:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
28. What is the lifespan event in FastAPI?
Lifespan events manage startup and shutdown procedures for your application:
@app.on_event("startup")
async def startup():
create_db_connection()
@app.on_event("shutdown")
async def shutdown():
close_db_connection()
29. How do you handle database sessions with dependencies?
Create database session dependencies:
async def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/")
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
return create_user_db(db, user)
30. How do you optimize FastAPI performance? (Salesforce scenario)
For Salesforce-like enterprise scale: use async endpoints for I/O operations, connection pooling, caching with Redis, efficient middleware, and proper load balancing.[3]