FastAPI_Interview_Guide
FastAPI_Interview_Guide
@app.get("/")
def read_root():
return {"message": "Welcome to FastAPI!"}
2. Asynchronous Programming
import asyncio
from fastapi import FastAPI
app = FastAPI()
@app.get("/async")
async def async_route():
await asyncio.sleep(1)
return {"message": "Handled asynchronously!"}
3. Dependency Injection
app = FastAPI()
FastAPI Complete Interview Guide
def common_dependency():
return {"dependency_data": "Shared logic"}
@app.get("/use-dependency")
def use_dependency(data = Depends(common_dependency)):
return data
app = FastAPI()
class Item(BaseModel):
name: str
price: float
description: str | None = None
@app.post("/items")
def create_item(item: Item):
return {"item": item}
5. Routing
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "query": q}
6. Interactive Documentation
app = FastAPI(
title="Custom API",
description="This is a custom description.",
version="1.0.0"
)
@app.get("/")
def read_root():
return {"message": "Custom API documentation!"}
7. Middleware
app = FastAPI()
@app.middleware("http")
async def log_requests(request: Request, call_next):
print(f"Request: {request.method} {request.url}")
response = await call_next(request)
print(f"Response: {response.status_code}")
return response
8. Error Handling
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id > 10:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
FastAPI Complete Interview Guide
9. Testing
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Welcome to FastAPI!"}
10. Deployment
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/welcome", response_class=HTMLResponse)
def get_html(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "name":
"Esakiraj"})
app = FastAPI()
@app.post("/notify/")
async def notify(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, "User notified!")
return {"message": "Notification scheduled"}
15. WebSockets
FastAPI Complete Interview Guide
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class Settings(BaseSettings):
database_url: str
secret_key: str
class Config:
FastAPI Complete Interview Guide
env_file = ".env"
settings = Settings()
@app.get("/ping", response_class=PlainTextResponse)
def ping():
return "pong"
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
content = await file.read()
return {"filename": file.filename}