Tech With Galvan
Back to Articles
DevelopmentMay 24, 2026 • 6 min read

FastAPI + Streamlit: Full-Stack Python App (Backend + UI)

Build a full-stack Python app with FastAPI as the backend and Streamlit as the UI — REST API, auth, database, and a clean separation of concerns.

Galvan
Galvan

Founder & Creator

Introduction

Streamlit is amazing for UIs — but putting DB queries, auth, and business logic directly in your Streamlit app gets messy fast. The fix: FastAPI backend + Streamlit frontend. Clean separation, testable API, and you can swap the UI later (React, mobile, etc.) without touching the backend.

This post builds a full-stack Python app: FastAPI REST API + Streamlit UI + SQLite.

Architecture

┌─────────────┐     HTTP/JSON     ┌──────────────┐
│  Streamlit  │  ──────────────►  │   FastAPI    │
│   (UI)      │  ◄──────────────  │  (backend)   │
└─────────────┘                   └──────┬───────┘
                                        │
                                        ▼
                                  ┌──────────┐
                                  │  SQLite  │
                                  └──────────┘

Both run as separate processes. Streamlit calls the API via requests.

Setup

mkdir fullstack && cd fullstack
python -m venv .venv && source .venv/bin/activate
pip install fastapi uvicorn streamlit requests sqlalchemy pydantic

Step 1: FastAPI backend (api.py)

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, declarative_base

app = FastAPI(title="Notes API")
engine = create_engine("sqlite:///notes.db", connect_args={"check_same_thread": False})
Base = declarative_base()
Session = sessionmaker(bind=engine)

class Note(Base):
    __tablename__ = "notes"
    id = Column(Integer, primary_key=True)
    title = Column(String)
    body = Column(String)

Base.metadata.create_all(engine)

class NoteIn(BaseModel):
    title: str
    body: str

@app.get("/notes")
def list_notes():
    db = Session()
    return [{"id": n.id, "title": n.title, "body": n.body} for n in db.query(Note).all()]

@app.post("/notes", status_code=201)
def create_note(note: NoteIn):
    db = Session()
    n = Note(title=note.title, body=note.body)
    db.add(n); db.commit(); db.refresh(n)
    return {"id": n.id, "title": n.title, "body": n.body}

@app.delete("/notes/{note_id}", status_code=204)
def delete_note(note_id: int):
    db = Session()
    n = db.query(Note).filter(Note.id == note_id).first()
    if not n:
        raise HTTPException(404, "Not found")
    db.delete(n); db.commit()

Run it:

uvicorn api:app --reload --port 8000

Visit http://localhost:8000/docs — you get auto-generated Swagger docs for free.

Step 2: Streamlit frontend (app.py)

import streamlit as st
import requests

API = "http://localhost:8000"

st.title("📝 Notes App")
st.caption("FastAPI backend + Streamlit frontend")

# Create
with st.form("new"):
    title = st.text_input("Title")
    body = st.text_area("Body")
    if st.form_submit_button("Add") and title and body:
        requests.post(f"{API}/notes", json={"title": title, "body": body})
        st.rerun()

# List
notes = requests.get(f"{API}/notes").json()
for n in notes:
    with st.container(border=True):
        st.subheader(n["title"])
        st.write(n["body"])
        if st.button("Delete", key=f"del-{n['id']}"):
            requests.delete(f"{API}/notes/{n['id']}")
            st.rerun()

Run it (in another terminal):

streamlit run app.py

Step 3: Add auth (JWT)

FastAPI makes auth trivial with OAuth2PasswordBearer:

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import Depends

oauth2 = OAuth2PasswordBearer(tokenUrl="token")

@app.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends()):
    # verify credentials (simplified)
    if form.username != "admin" or form.password != "secret":
        raise HTTPException(401, "Bad credentials")
    return {"access_token": form.username, "token_type": "bearer"}

@app.get("/notes")
def list_notes(token: str = Depends(oauth2)):
    # verify token here
    ...

In Streamlit, store the token in st.session_state and pass it as a header:

headers = {"Authorization": f"Bearer {st.session_state.token}"}
requests.get(f"{API}/notes", headers=headers)

Why separate backend from UI?

  1. Testability — test the API with pytest + TestClient, independent of Streamlit.
  2. Reusability — the same API serves a web app, mobile app, or CLI.
  3. Security — DB credentials and secrets stay server-side; Streamlit only sees JSON.
  4. Scaling — scale the API horizontally without touching the UI.
  5. Team split — backend devs and frontend devs work in parallel.

Common mistakes

  • Calling the DB from Streamlit — defeats the purpose; always go through the API.
  • Hardcoding localhost:8000 — use env vars (API_URL) for deployment.
  • No error handling — requests.get can fail; wrap in try/except and show st.error.
  • CORS issues — if Streamlit and FastAPI are on different origins, add CORSMiddleware to FastAPI.
  • Sharing SQLite across processes — SQLite handles concurrent reads fine but writes need care; use Postgres for production.

Key Concepts

  • FastAPI = modern Python API framework with auto docs
  • Pydantic models = request/response validation
  • SQLAlchemy = ORM for the database
  • Streamlit = UI layer, calls the API via requests
  • Separation of concerns = backend = logic, frontend = display

What to Try Next

  • Add pagination to /notes (?skip=0&limit=10).
  • Add search with query params (?q=keyword).
  • Deploy both to a single server with Docker Compose.
  • Replace Streamlit with React — the API doesn’t change.
  • Add WebSocket support for real-time updates.

FAQ

FastAPI vs Flask in 2026?

FastAPI is the modern default: async by default, auto-generated docs, Pydantic validation, type hints. Flask is simpler and has a bigger ecosystem but lacks async and auto-docs. For new projects, FastAPI.

Can I deploy both on one server?

Yes — run FastAPI with uvicorn and Streamlit on different ports, put Nginx in front as a reverse proxy. Or containerize both with Docker Compose.

Streamlit vs React for the frontend?

Streamlit = 10x faster to build, great for data apps and internal tools. React = more control, better for consumer-facing products. Start with Streamlit; migrate to React when you hit its limits.