Web APIs (FastAPI)

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

1. Why FastAPI?

  • Fast: On par with NodeJS and Go.
  • Auto Docs: Automatically generates Swagger (OpenAPI) docs.
  • Type-Safe: Catch editor bugs before they happen using Type Hints.
  • Async Support: Built-in support for async and await.

2. Basic App

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

# To run: uvicorn main:app --reload

3. Path & Query Parameters

FastAPI uses Python type hints for automatic validation.

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}
Interactive Docs: Once your server is running, go to/docs to see a fully interactive API playground generated for you!