API Development

Python APIFree Lesson

Advertisement

API Development

REST API design, authentication, rate limiting, and API patterns.

Overview

Build production-ready APIs.

RESTful API Design

from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import List

app = FastAPI()

# Data models
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

# In-memory database
items_db = {}

# Endpoints
@app.get("/items/", response_model=List[Item])
def read_items():
    return list(items_db.values())

@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: str):
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return items_db[item_id]

@app.post("/items/", response_model=Item, status_code=201)
def create_item(item: Item):
    items_db[item.name] = item
    return item

@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: str, item: Item):
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    items_db[item_id] = item
    return item

@app.delete("/items/{item_id}")
def delete_item(item_id: str):
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    del items_db[item_id]
    return {"message": "Item deleted"}

Authentication

from fastapi import Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt

security = HTTPBearer()

def create_token(user_id: int):
    payload = {"user_id": user_id}
    return jwt.encode(payload, "secret", algorithm="HS256")

def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)):
    try:
        payload = jwt.decode(credentials.credentials, "secret", algorithms=["HS256"])
        return payload["user_id"]
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")

@app.get("/protected/")
def protected_route(user_id: int = Depends(verify_token)):
    return {"message": f"Hello user {user_id}"}

Practice

Add JWT authentication to a REST API.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement