DEV Community

Brad
Brad

Posted on

Build a REST API in 10 Minutes with FastAPI and Python

Build a REST API in 10 Minutes with FastAPI and Python

FastAPI is the fastest way to build production-ready APIs in Python.

Setup

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

Your First API

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

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

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

@app.post("/items/")
def create_item(item: Item):
    return {"item": item, "status": "created"}
Enter fullscreen mode Exit fullscreen mode

Run It

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:8000/docs for automatic API documentation.

Add a Database

from fastapi import FastAPI
import sqlite3

app = FastAPI()

def get_db():
    conn = sqlite3.connect("data.db")
    conn.row_factory = sqlite3.Row
    return conn

@app.get("/products")
def list_products():
    db = get_db()
    rows = db.execute("SELECT * FROM products").fetchall()
    return [dict(r) for r in rows]

@app.post("/products")
def create_product(name: str, price: float):
    db = get_db()
    db.execute("INSERT INTO products (name, price) VALUES (?, ?)", (name, price))
    db.commit()
    return {"status": "created"}
Enter fullscreen mode Exit fullscreen mode

Authentication

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

security = HTTPBearer()

@app.get("/protected")
def protected(credentials: HTTPAuthorizationCredentials = Security(security)):
    if credentials.credentials != "my-secret":
        raise HTTPException(status_code=401)
    return {"ok": True}
Enter fullscreen mode Exit fullscreen mode

FastAPI gives you automatic docs, validation, and async support out of the box. It is the right choice for any Python API project.


Want 50+ ready-to-use Python automation scripts? Get the complete toolkit for just $9: https://lukassbrad.gumroad.com/l/ugeka

Top comments (0)