FastAPI Guide for Building APIs
Table of Contents
1. FastAPI Basics
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
2. Endpoints
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.post("/items/")
def create_item(item: Item):
return item
3. Request/Response
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
4. Authentication
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
5. Deployment
# Run with uvicorn
uvicorn main:app --reload
# Deploy to Render
# 1. Create Dockerfile
# 2. Push to GitHub
# 3. Connect to Render
# 4. Deploy
Download FastAPI Guide PDF
Get the complete FastAPI Guide as a free PDF. Enter your email to receive the download link.
Start Learning with DSWallah
Join 300+ students who transformed their careers with DSWallah. IIT-certified mentor, 50+ real projects, placement support.
WhatsApp for Free Demo →