FastAPI Basics and Setup - Interview Questions
1. What is FastAPI and what are its main advantages?
FastAPI is a modern, fast web framework for building APIs with Python 3.7+ based on standard Python type hints. It’s built on top of Starlette and Pydantic.
Main Advantages:
- High Performance: One of the fastest Python frameworks available, comparable to NodeJS and Go
- Fast to Code: Reduces development time by ~200% to 300%
- Fewer Bugs: Automatic data validation reduces bugs by ~40%
- Intuitive: Great editor support with autocompletion everywhere
- Easy: Designed to be easy to use and learn
- Short: Minimizes code duplication
- Robust: Production-ready code with automatic interactive documentation
- Standards-based: Based on (and fully compatible with) OpenAPI and JSON Schema
2. How do you install and set up FastAPI?
# Install FastAPI and ASGI server
pip install fastapi uvicorn
# For development with auto-reload
pip install fastapi uvicorn[standard]
Basic setup:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
# Run with: uvicorn main:app --reload
3. What is the difference between FastAPI and Flask?
| Feature | FastAPI | Flask |
|---|---|---|
| Performance | High (async support) | Medium (synchronous) |
| Type Hints | Built-in support | Limited support |
| Data Validation | Automatic (Pydantic) | Manual or third-party |
| Documentation | Auto-generated (OpenAPI/Swagger) | Manual |
| Async Support | Native | Requires extensions |
| Learning Curve | Steeper (requires type hints) | Easier |
| Use Case | APIs and microservices | Web applications and APIs |
4. What is Uvicorn and why is it used with FastAPI?
Uvicorn is an ASGI (Asynchronous Server Gateway Interface) server implementation for Python. It’s used with FastAPI because:
- ASGI Support: FastAPI is built on ASGI, and Uvicorn is a high-performance ASGI server
- Async Capabilities: Supports async/await for better performance
- WebSocket Support: Built-in WebSocket support
- Production Ready: Can handle production workloads
- Hot Reload: Development server with auto-reload capability
# Basic usage
uvicorn main:app --reload
# Production usage
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
5. What are the main components of a FastAPI application?
The main components are:
- FastAPI Instance: The main application object
- Path Operations: Route handlers (GET, POST, PUT, DELETE)
- Request Models: Pydantic models for request validation
- Response Models: Pydantic models for response serialization
- Dependencies: Reusable components for common functionality
- Middleware: Request/response processing
- Exception Handlers: Custom error handling
from fastapi import FastAPI, Depends
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.get("/items/{item_id}")
def read_item(item_id: int, item: Item):
return {"item_id": item_id, "item": item}
6. What is the purpose of the @app.get(), @app.post() decorators?
These are path operation decorators that define HTTP endpoints:
@app.get(): Handles HTTP GET requests@app.post(): Handles HTTP POST requests@app.put(): Handles HTTP PUT requests@app.delete(): Handles HTTP DELETE requests@app.patch(): Handles HTTP PATCH requests
@app.get("/users")
def get_users():
return {"users": ["user1", "user2"]}
@app.post("/users")
def create_user(user: User):
return {"message": "User created", "user": user}
7. How does FastAPI handle automatic documentation?
FastAPI automatically generates interactive API documentation using:
- OpenAPI (Swagger): Available at
/docs - ReDoc: Available at
/redoc
The documentation is generated from:
- Type hints in function parameters
- Pydantic models
- Docstrings
- Path operation decorators
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(
title="My API",
description="A sample API",
version="1.0.0"
)
class User(BaseModel):
name: str
email: str
@app.post("/users", response_model=User)
def create_user(user: User):
"""
Create a new user with the following information:
- **name**: User's full name
- **email**: User's email address
"""
return user
8. What is the difference between path parameters and query parameters?
Path Parameters:
- Part of the URL path
- Required by default
- Defined in the path with curly braces
{}
Query Parameters:
- Added after
?in the URL - Optional by default
- Used for filtering, sorting, pagination
@app.get("/users/{user_id}") # user_id is a path parameter
def get_user(user_id: int, skip: int = 0, limit: int = 10):
# skip and limit are query parameters
return {"user_id": user_id, "skip": skip, "limit": limit}
9. How do you run a FastAPI application in production?
# Using uvicorn directly
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
# Using Gunicorn with uvicorn workers
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
# Using Docker
docker run -p 8000:8000 myapp
# Using systemd service
# Create a service file and use systemctl
Production considerations:
- Use multiple workers
- Set up reverse proxy (nginx)
- Configure logging
- Set up monitoring
- Use environment variables for configuration
- Enable HTTPS
10. What is the purpose of the app variable in FastAPI?
The app variable is the main FastAPI application instance that:
- Registers routes: All path operations are registered with this instance
- Configures middleware: Middleware is added to this instance
- Manages dependencies: Global dependencies are configured here
- Handles startup/shutdown events: Lifecycle events are managed
- Serves as ASGI application: Uvicorn uses this as the entry point
from fastapi import FastAPI
app = FastAPI(
title="My API",
description="API Description",
version="1.0.0"
)
# All routes are registered with 'app'
@app.get("/")
def root():
return {"message": "Hello World"}
Interview angle
- “How does FastAPI know how to parse a parameter?” - by where it appears and its type. Path parameters come from the URL template, scalars default to query parameters, and Pydantic models are read from the body.
Query,Path,BodyandDependsoverride the default inference. - “What does
response_modeldo beyond documentation?” - it filters the response. Fields not on the model are stripped, which is a real security control: addinghashed_passwordto your ORM model doesn’t leak it through an endpoint declared with a public response model. - “Why use
APIRouter?” - it splits routes into modules with shared prefixes, tags, dependencies and responses, so a large app stays navigable and cross-cutting dependencies apply per router rather than per endpoint. - “How do you structure a project?” - by feature rather than by layer once it grows: routers, schemas, services and repositories per domain area, with a composition root wiring them. See ../../13_architecture_design/02_feature_sliced_structure.md.