Simple API with FastAPI
This guide demonstrates how to build a high-performance API using FastAPI. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
Modules Used:
fastapi: The web framework.uvicorn: An ASGI web server implementation for Python.pydantic: For data validation and settings management using Python type annotations.
Installation
pip install fastapi uvicorn
The Code
Save this as main.py.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
# --- Data Model ---
class Item(BaseModel):
id: int
name: str
price: float
is_offer: Optional[bool] = None
# --- In-Memory Database ---
items_db = []
# --- Endpoints ---
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/", response_model=List[Item])
def read_items():
return items_db
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
for item in items_db:
if item.id == item_id:
return item
raise HTTPException(status_code=404, detail="Item not found")
@app.post("/items/", response_model=Item)
def create_item(item: Item):
# Check if ID already exists
for existing_item in items_db:
if existing_item.id == item.id:
raise HTTPException(status_code=400, detail="Item ID already exists")
items_db.append(item)
return item
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, item: Item):
for index, existing_item in enumerate(items_db):
if existing_item.id == item_id:
# Update the item
items_db[index] = item
return item
raise HTTPException(status_code=404, detail="Item not found")
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
for index, item in enumerate(items_db):
if item.id == item_id:
del items_db[index]
return {"message": "Item deleted"}
raise HTTPException(status_code=404, detail="Item not found")
# To run programmatically (optional, usually run via CLI)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
Usage
-
Run the server: You can run it using the
uvicorncommand line tool (recommended for development with auto-reload):uvicorn main:app --reload -
Interactive Documentation (Swagger UI): FastAPI automatically generates interactive API documentation. Go to
http://127.0.0.1:8000/docs. Here you can test all your endpoints (GET, POST, PUT, DELETE) directly from the browser.