CS NOTES
0 Likes
21 Views
14 Pages
Free
0 Ratings
Below is a preview of the PDF. To download the full document, please click the download button.
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed for ease of use, automatic data validation, and excellent performance (comparable to Node and Go frameworks). These handwritten notes summarize essential FastAPI concepts in a concise, exam- and interview-friendly format.
Install FastAPI and an ASGI server (Uvicorn) using pip:
pip install fastapi uvicorn
Run the app with Uvicorn:
uvicorn app:app --reload
FastAPI uses path operation decorators to define routes. Example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello FastAPI"}
Supported methods: @app.get, @app.post, @app.put, @app.delete, @app.patch.
FastAPI uses Pydantic for data validation and settings management. Define request bodies using Pydantic models:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool | None = None
Pydantic automatically validates and converts data types from JSON requests.
Examples of different parameter types:
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
@app.post("/items/")
async def create_item(item: Item):
return item
Use type hints for automatic parsing and validation. Default values make query params optional.
FastAPI provides a simple and powerful dependency injection system for reusing logic (e.g., DB sessions, authentication):
from fastapi import Depends
def get_db():
db = connect_db()
try:
yield db
finally:
db.close()
@app.get("/users/")
async def list_users(db = Depends(get_db)):
return db.query_users()
Run non-blocking background work using BackgroundTasks or startup/shutdown events:
from fastapi import BackgroundTasks
def write_log(message: str):
with open("log.txt", "a") as f:
f.write(message)
@app.post("/send/")
async def send_message(background_tasks: BackgroundTasks, msg: str):
background_tasks.add_task(write_log, msg)
return {"status": "queued"}
Use middleware for request/response processing and configure CORS for cross-origin requests:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
FastAPI supports OAuth2, JWT, API keys, and HTTP Basic auth. Example using OAuth2PasswordBearer:
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
Always validate tokens, use HTTPS in production, and follow security best practices.
Use TestClient from starlette.testclient (or FastAPI's built-in wrapper) with pytest:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello FastAPI"}
gunicorn -k uvicorn.workers.UvicornWorker app:appfrom fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Dict
app = FastAPI()
db: Dict[int, dict] = {}
next_id = 1
class Item(BaseModel):
name: str
description: str | None = None
@app.post("/items/", status_code=201)
async def create_item(item: Item):
global next_id
item_data = item.dict()
db[next_id] = item_data
next_id += 1
return {"id": next_id - 1, **item_data}
@app.get("/items/{item_id}")
async def get_item(item_id: int):
if item_id not in db:
raise HTTPException(status_code=404, detail="Item not found")
return db[item_id]
These notes are for Python developers, backend learners, and anyone preparing for API development interviews.
Yes - replace the download link above with your hosted PDF URL to offer a free download.
Yes - the PDF includes explanations and examples of asynchronous endpoints, concurrency, and background tasks.
FastAPI Python Backend Development API Pydantic Async Handwritten Notes FastAPI PDF Web Development APIs
To leave a comment, please log in.
Log in to CommentDBMS Handwritten Notes - Basics Made Easy
Data Structure and Algorithm Notes
UP Police Computer Operator 2018 Question Paper PDF
Handwritten Notes on the Indian Constitution in Hindi (PDF)
SPI Protocol Complete Interview Guide PDF
Master Recursion and Backtracking in DSA - Complete Notes & Concepts Explained
Handwritten Linux Notes PDF | Simplified Linux Commands & Concepts for Beginners
Kubernetes for Beginners | Handwritten Notes & Easy Tutorials
DBMS Handwritten Notes - Basics Made Easy
Data Structure and Algorithm Notes
Master Recursion and Backtracking in DSA - Complete Notes & Concepts Explained
Handwritten Linux Notes PDF | Simplified Linux Commands & Concepts for Beginners
Kubernetes for Beginners | Handwritten Notes & Easy Tutorials
Mastering Git & GitHub: A Complete Beginner's Guide
Angular Handwritten Notes: A Complete Guide for Beginners
C Programming Handwritten Notes: A Complete Guide
CSS Handwritten Notes: A Complete Guide for Beginners and Developers
Java Handwritten Notes PDF Download | Complete Core & Advanced Java Notes
JavaScript Handwritten Notes PDF Download | Learn JS Basics to Advanced Concepts
HTML Handwritten Notes PDF Download | Complete HTML Notes for Beginners
PHP Handwritten Notes PDF Download | Complete PHP Notes for Beginners
Docker Handwritten Notes PDF Download | Complete Docker Notes for Beginners
Next.js Handwritten Notes PDF Download | Complete Next.js Notes for Beginners
Operating System Handwritten Notes PDF Download | Complete OS Notes for Students
SQL Handwritten Notes PDF Download | Complete SQL Notes for Beginners