0% found this document useful (0 votes)
4 views

FastAPI_Interview_Guide

The FastAPI Complete Interview Guide covers essential features and benefits of FastAPI, including high performance, interactive API documentation, and support for asynchronous programming. It provides examples of routing, data validation with Pydantic, dependency injection, and middleware, along with testing, deployment, and security features like OAuth2. Additionally, it discusses handling static files, background tasks, WebSockets, CORS, environment variables, custom responses, and file uploads.

Uploaded by

Sathish Smart
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

FastAPI_Interview_Guide

The FastAPI Complete Interview Guide covers essential features and benefits of FastAPI, including high performance, interactive API documentation, and support for asynchronous programming. It provides examples of routing, data validation with Pydantic, dependency injection, and middleware, along with testing, deployment, and security features like OAuth2. Additionally, it discusses handling static files, background tasks, WebSockets, CORS, environment variables, custom responses, and file uploads.

Uploaded by

Sathish Smart
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

FastAPI Complete Interview Guide

1. Core Features and Benefits

FastAPI is designed for performance and usability. Key features:

- High Performance: Built on Starlette and Pydantic

- Interactive API Docs: Swagger UI and ReDoc auto-generated

- Standards: Built on OpenAPI and JSON Schema

from fastapi import FastAPI

app = FastAPI(title="My FastAPI App", description="A simple API", version="1.0.0")

@app.get("/")
def read_root():
return {"message": "Welcome to FastAPI!"}

# Run with: uvicorn main:app --reload

2. Asynchronous Programming

FastAPI supports async request handling for I/O-bound tasks.

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

Use Depends to inject shared logic.

from fastapi import Depends, FastAPI

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

4. Data Validation and Serialization

Use Pydantic models for input validation and output formatting.

from fastapi import FastAPI


from pydantic import BaseModel

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

Use decorators to define clean routes.

from fastapi import FastAPI

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

Swagger UI and ReDoc available at /docs and /redoc.


FastAPI Complete Interview Guide

from fastapi import FastAPI

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

Process requests and responses globally.

from fastapi import FastAPI, Request

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

Use HTTPException for custom error responses.

from fastapi import FastAPI, HTTPException

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

Use TestClient to test endpoints.

from fastapi.testclient import TestClient


from main import app

client = TestClient(app)

def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Welcome to FastAPI!"}

10. Deployment

Deploy with Uvicorn or Gunicorn.

# Basic Uvicorn command:


uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

# Gunicorn with Uvicorn workers:


gunicorn -k uvicorn.workers.UvicornWorker main:app -w 4 -b 0.0.0.0:8000

11. Security - OAuth2

Built-in support for OAuth2 and JWT.

from fastapi import FastAPI, Depends


from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}

12. HTML Templating


FastAPI Complete Interview Guide

Use Jinja2 to render HTML templates.

from fastapi import FastAPI, Request


from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse

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"})

13. Static Files

Serve static content like CSS/JS.

from fastapi.staticfiles import StaticFiles

app.mount("/static", StaticFiles(directory="static"), name="static")

14. Background Tasks

Run non-blocking background operations.

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(message: str):


with open("log.txt", "a") as file:
file.write(message + "\n")

@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

Add real-time communication.

from fastapi import FastAPI, WebSocket

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}")

16. CORS Middleware

Allow cross-origin requests.

from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

17. Environment Variables

Use Pydantic BaseSettings for config.

from pydantic import BaseSettings

class Settings(BaseSettings):
database_url: str
secret_key: str

class Config:
FastAPI Complete Interview Guide

env_file = ".env"

settings = Settings()

18. Custom Response Classes

Return HTML, text, or file responses.

from fastapi.responses import PlainTextResponse

@app.get("/ping", response_class=PlainTextResponse)
def ping():
return "pong"

19. File Uploads

Support for file uploads.

from fastapi import File, UploadFile

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
content = await file.read()
return {"filename": file.filename}

You might also like