0% found this document useful (0 votes)
85 views16 pages

FastAPI Interview Preparation Guide

FastAPI is a modern web framework for building APIs in Python, known for its high performance, automatic documentation, and built-in data validation. It supports asynchronous programming and dependency injection, making it efficient for API development. The guide covers various aspects of FastAPI, including request handling, middleware, authentication, deployment, and best practices for development and testing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views16 pages

FastAPI Interview Preparation Guide

FastAPI is a modern web framework for building APIs in Python, known for its high performance, automatic documentation, and built-in data validation. It supports asynchronous programming and dependency injection, making it efficient for API development. The guide covers various aspects of FastAPI, including request handling, middleware, authentication, deployment, and best practices for development and testing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

FAST API INTERVIEW GUIDE

1. What is FastAPI, and how does it differ from other web frameworks?
FastAPI is a modern, fast web framework for building APIs with Python 3.7+ based on
standard Python type hints. It was created by Sebastian Ramirez in 2018.

Key Differences from Other Frameworks:


vs Flask:

FastAPI has automatic API documentation (OpenAPI/Swagger)


Built-in data validation using Pydantic
Async support by default
Type hints for better IDE support and validation
vs Django REST Framework:

FastAPI is lighter and more focused on APIs


Better performance (one of the fastest Python frameworks)
Simpler setup for API-only applications
Built-in async support
vs [Link] ([Link]):

Comparable performance
Automatic data validation and serialization
Built-in documentation generation

2. Benefits of Using FastAPI


High Performance: Comparable to [Link] and Go
Fast Development: Reduces development time by 200–300%
Fewer Bugs: Reduces human-induced errors by ~40%
Intuitive: Great editor support with autocompletion
Easy: Designed to be easy to learn and use
Short: Minimize code duplication
Robust: Production-ready code with automatic documentation
Standards-based: Based on OpenAPI and JSON Schema
Async Support: Native async/await support

3. How FastAPI Handles Requests and Responses


FastAPI uses ASGI (Asynchronous Server Gateway Interface) to handle requests
asynchronously:

Request Processing: Incoming requests are parsed and validated against type hints
Path Operation: Routes requests to appropriate path operation functions
Dependency Injection: Resolves dependencies before executing the handler
Data Validation: Automatically validates request data using Pydantic models
Response Generation: Serializes response data and generates appropriate HTTP responses

4. Route Definition Syntax


from fastapi import FastAPI
app = FastAPI()
# Basic GET route
@[Link]("/")
def read_root():
return {"Hello": "World"}
# Route with path parameter
@[Link]("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
# POST route with request body
@[Link]("/items/")
def create_item(item: Item):
return item

5. Types of Request Parameters


Path Parameters
@[Link]("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
Query Parameters
@[Link]("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
Request Body
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@[Link]("/items/")
def create_item(item: Item):
return item
Headers
from fastapi import Header
@[Link]("/items/")
def read_items(user_agent: str = Header(None)):
return {"User-Agent": user_agent}
Cookies
from fastapi import Cookie
@[Link]("/items/")
def read_items(session_id: str = Cookie(None)):
return {"session_id": session_id}
6. Dependency Injection in FastAPI
Dependency Injection is a design pattern where components receive their dependencies
from external sources rather than creating them internally. FastAPI has a powerful
dependency injection system.

Benefits:

Code reusability
Easy testing
Separation of concerns
Automatic validation

7. Defining and Using Dependencies


from fastapi import Depends
# Simple dependency
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@[Link]("/items/")
def read_items(commons: dict = Depends(common_parameters)):
return commons
# Class-based dependency
class CommonQueryParams:
def __init__(self, q: str = None, skip: int = 0, limit: int = 100):
self.q = q
[Link] = skip
[Link] = limit
@[Link]("/users/")
def read_users(commons: CommonQueryParams = Depends(CommonQueryParams)):
return commons
8. Middleware in FastAPI
Middleware is a function that works with every request before it’s processed by specific path
operations and with every response before returning it.

Common Use Cases:

Authentication
Logging
CORS handling
Request/Response modification
Performance monitoring

9. Adding Middleware
from fastapi import FastAPI, Request
import time
app = FastAPI()
@[Link]("http")
async def add_process_time_header(request: Request, call_next):
start_time = [Link]()
response = await call_next(request)
process_time = [Link]() - start_time
[Link]["X-Process-Time"] = str(process_time)
return response
# Using third-party middleware
from [Link] import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

10. Path Parameters vs Query Parameters


Path Parameters
Part of the URL path
Required by default
Declared in the path string with {parameter_name}
Example: /users/{user_id} → user_id is a path parameter
Query Parameters
Come after ? in the URL
Optional by default (can be made required)
Declared as function parameters
Example: /users?skip=0&limit=10 → skip and limit are query parameters

11. Exception and Error Handling


from fastapi import HTTPException
@[Link]("/items/{item_id}")
def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}
# Custom exception handler
from [Link] import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
[Link] = name
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {[Link]} did something."}
)

12. Handling CORS


from [Link] import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["[Link] "[Link]
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)

13. Pydantic in FastAPI


Pydantic is a Python library that provides data validation and settings management using
Python type annotations.

Usage in FastAPI:

Request body validation


Response model definition
Configuration management
Data serialization/deserialization
from pydantic import BaseModel, validator
from typing import Optional
class User(BaseModel):
name: str
email: str
age: Optional[int] = None

@validator('email')
def email_must_contain_at(cls, v):
if '@' not in v:
raise ValueError('Invalid email')
return v

14. Response Model Syntax


from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
class ItemResponse(BaseModel):
name: str
price: float
@[Link]("/items/", response_model=ItemResponse)
def create_item(item: Item):
return item
# Response model with list
from typing import List
@[Link]("/items/", response_model=List[ItemResponse])
def read_items():
return items

15. Background Tasks


Background tasks allow you to run functions after returning a response, useful for operations
that don’t need to complete before returning the response.
Use Cases:

Sending emails
Processing files
Logging
Cache warming

16. Using Background Tasks


from fastapi import BackgroundTasks
def write_log(message: str):
with open("[Link]", "a") as log:
[Link](message)
@[Link]("/send-notification/")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, f"Notification sent to {email}")
return {"message": "Notification sent in the background"}
# Multiple background tasks
@[Link]("/process-items/")
async def process_items(background_tasks: BackgroundTasks):
background_tasks.add_task(task_one, "arg1")
background_tasks.add_task(task_two, "arg2", keyword="value")
return {"message": "Tasks started"}

17. WebSocket Purpose in FastAPI


WebSockets enable bidirectional, real-time communication between client and server.

Use Cases:

Chat applications
Live notifications
Real-time dashboards
Gaming applications
Live data feeds

18. Implementing WebSockets


from fastapi import WebSocket, WebSocketDisconnect
@[Link]("/ws")
async def websocket_endpoint(websocket: WebSocket):
await [Link]()
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
except WebSocketDisconnect:
print("Client disconnected")
# WebSocket with path parameters
@[Link]("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
await [Link]()
# Handle client-specific logic

19. OAuth2 and JWT Authentication Support


FastAPI provides built-in support for OAuth2 with JWT tokens:

from fastapi import Depends, HTTPException, status


from [Link] import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from [Link] import CryptContext
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
def create_access_token(data: dict):
return [Link](data, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = [Link](token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = [Link]("sub")
if username is None:
raise HTTPException(status_code=401, detail="Invalid token")
return username
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
@[Link]("/protected")
async def protected_route(current_user: str = Depends(get_current_user)):
return {"user": current_user}

20. Securing FastAPI Applications


Authentication Methods:
JWT tokens
OAuth2
API keys
Basic authentication
Security Best Practices:
from [Link] import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import Depends, HTTPException
security = HTTPBearer()
async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
if not verify_jwt_token([Link]):
raise HTTPException(status_code=401, detail="Invalid token")
return [Link]
# Rate limiting
from slowapi import Limiter, _rate_limit_exceeded_handler
from [Link] import get_remote_address
limiter = Limiter(key_func=get_remote_address)
[Link] = limiter
app.add_exception_handler(429, _rate_limit_exceeded_handler)
@[Link]("/limited")
@[Link]("5/minute")
async def limited_endpoint(request: Request):
return {"message": "This endpoint is rate limited"}

21. Benefits of Using FastAPI with Docker


Consistent Environment: Same environment across development, testing, and production
Easy Deployment: Containerized applications are easier to deploy
Scalability: Easy horizontal scaling with container orchestration
Isolation: Dependencies are isolated within containers
Portability: Runs anywhere Docker is supported
FROM python:3.9
WORKDIR /app
COPY [Link] .
RUN pip install -r [Link]
COPY . .
CMD ["uvicorn", "main:app", "--host", "[Link]", "--port", "8000"]

22. Deploying to Cloud Platforms


AWS Deployment Options:
AWS Lambda (serverless)
AWS ECS/EKS (containerized)
AWS Elastic Beanstalk (platform-as-a-service)
AWS EC2 (virtual machines)
Heroku Deployment:
# Procfile
web: uvicorn main:app --host=[Link] --port=${PORT:-5000}
# Deploy commands
heroku create myapp
git push heroku main
Key Considerations:
Environment variables for configuration
Database connections
Static file serving
HTTPS/SSL certificates
Load balancing

23. Testing Support


FastAPI provides excellent testing support with TestClient:

from [Link] import TestClient


from main import app
client = TestClient(app)
def test_read_main():
response = [Link]("/")
assert response.status_code == 200
assert [Link]() == {"Hello": "World"}
def test_create_item():
response = [Link](
"/items/",
json={"name": "Foo", "price": 50.5}
)
assert response.status_code == 200
assert [Link]()["name"] == "Foo"
# Testing with authentication
def test_protected_endpoint():
headers = {"Authorization": "Bearer valid-token"}
response = [Link]("/protected", headers=headers)
assert response.status_code == 200
24. Best Practices for Development and Deployment
Development Best Practices:
Use type hints consistently
Implement proper error handling
Use Pydantic models for data validation
Organize code with routers
Write comprehensive tests
Use environment variables for configuration
Implement logging
Use dependency injection for reusable components
Deployment Best Practices:
Use HTTPS in production
Set up proper monitoring and logging
Implement health checks
Use environment-specific configurations
Set up CI/CD pipelines
Use secrets management
Implement rate limiting
Regular security updates
Code Organization:
app/
├── [Link]
├── models/
│ ├── __init__.py
│ └── [Link]
├── routers/
│ ├── __init__.py
│ ├── [Link]
│ └── [Link]
├── dependencies/
│ ├── __init__.py
│ └── [Link]
└── tests/
├── __init__.py
└── test_main.py

25. Scalability and Performance


Performance Features:
Async/Await Support: Non-blocking I/O operations
High Performance: One of the fastest Python frameworks
Automatic Validation: Reduces overhead of manual validation
Efficient Serialization: Pydantic’s optimized serialization
Scalability Strategies:
Horizontal Scaling: Multiple instances behind a load balancer
Database Optimization: Connection pooling, query optimization
Caching: Redis, Memcached for frequently accessed data
CDN: Content delivery networks for static assets
Monitoring: Application performance monitoring (APM)
Performance Tips:
# Use async for I/O operations
@[Link]("/async-endpoint")
async def async_endpoint():
data = await fetch_data_from_database()
return data
# Use background tasks for non-critical operations
@[Link]("/process-data")
async def process_data(background_tasks: BackgroundTasks):
background_tasks.add_task(heavy_processing_task)
return {"status": "processing started"}
# Implement caching
from functools import lru_cache
@lru_cache()
def get_settings():
return Settings()

Interview Tips
Practice Code Examples: Be ready to write basic FastAPI code on a whiteboard or computer
Understand Async: Be prepared to explain when and why to use async/await
Know the Ecosystem: Understand how FastAPI fits with other Python tools (SQLAlchemy,
Alembic, etc.)
Real-world Experience: Prepare examples of how you’ve used or would use FastAPI in real
projects
Compare with Other Frameworks: Be ready to discuss trade-offs between FastAPI and other
frameworks
Security Awareness: Understand common web security concerns and how FastAPI addresses
them

You might also like