← Back to Home

Store API + Local Database

Storing Data

So far your API forgets everything when you restart it. Let's use a local NoSQL database to store products for a simple shop.

We'll use TinyDB—a tiny, file-based JSON database perfect for learning.

Set up the project

Create a new folder and install dependencies:

mkdir -p python-tutorials/store-api
cd python-tutorials/store-api

uv venv
uv pip install fastapi uvicorn tinydb

Build the Store API

Create main.py:

from fastapi import FastAPI, HTTPException
from tinydb import TinyDB, Query
from pydantic import BaseModel

app = FastAPI()
db = TinyDB("store.json")
products_table = db.table("products")

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

@app.get("/")
def read_root():
    return {"message": "Welcome to the Store API"}

@app.get("/products")
def get_products():
    return products_table.all()

@app.post("/products")
def add_product(product: Product):
    product_id = products_table.insert(product.dict())
    return {"id": product_id, **product.dict()}

@app.get("/products/{product_id}")
def get_product(product_id: int):
    product = products_table.get(doc_id=product_id)
    if not product:
        raise HTTPException(status_code=404, detail="Product not found")
    return {"id": product_id, **product}

Run and Test

Start the server:

uv run uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs to:

  • Add products with POST /products (name and price)
  • View all products with GET /products
  • Get a single product with GET /products/1

Your data is saved in store.json — it persists even when you restart!

What's Next?

In the final tutorial, you'll build a simple web UI that talks to this API so users can search and "buy" products.

← Previous Next: Storefront UI →