๐Ÿ Python Examples - Comprehensive Code Library
โ† Back to PranavKulkarni.org
Lesson 3 ยท Web Development

REST API Development & FastAPI

Create high-performance APIs with FastAPI and understand RESTful principles.

FastAPI: Modern & High Performance

FastAPI is a modern web framework for building APIs with Python 3.7+ based on standard Python type hints.

Key Features

  • Fast: Very high performance, on par with NodeJS and Go.
  • Fast to code: Increase speed to develop features by about 200% to 300%.
  • Fewer bugs: Reduce about 40% of human induced errors.
  • Automatic Docs: Interactive API documentation (Swagger UI / ReDoc) out of the box.

Hello FastAPI

from fastapi import FastAPI

app = FastAPI()

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

Path and Query Parameters

FastAPI uses Python type hints for validation and documentation.

@app.get("/items/<item_id>")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

Pydantic Models

Define request bodies using Pydantic classes for automatic validation.

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
def create_item(item: Item):
    return item

โœ… Practice (30 minutes)

  • Install FastAPI and Uvicorn: pip install fastapi uvicorn.
  • Run your app: uvicorn main:app --reload.
  • Visit /docs to see the automatic Swagger UI.
  • Create an endpoint that accepts a list of IDs and returns their sum.