Courses Curriculum Cities Blog Enroll Now
Database Integration and User History · Day 4 of 5 ~45 minutes

Day 4: Database Integration and User History

Add persistent storage so users can see their previous analyses. Every analysis gets saved to PostgreSQL and retrieved on demand.

1
Day 1
2
Day 2
3
Day 3
4
Day 4
5
Day 5
What You'll Build

A full database-backed history feature: every analysis is saved with timestamp and type, a GET /history endpoint returns recent analyses, and the React frontend shows a history panel.

1
Section 1 · 15 min

Database Setup with SQLAlchemy

Set up PostgreSQL locally (or use SQLite for development) and add database models:

pythonbackend/database.py
from sqlalchemy import create_engine, Column, String, Text, DateTime, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

DATABASE_URL = "sqlite:///./ai_analyzer.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class Analysis(Base):
    __tablename__ = "analyses"
    id = Column(Integer, primary_key=True)
    input_text = Column(Text)
    analysis_type = Column(String)
    result = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)

Base.metadata.create_all(bind=engine)
2
Section 2 · 15 min

Save and Retrieve Analyses

Update the analyze endpoint to save results, and add a history endpoint:

pythonbackend/main.py (update)
from fastapi import Depends
from sqlalchemy.orm import Session
from .database import SessionLocal, Analysis

def get_db():
    db = SessionLocal()
    try: yield db
    finally: db.close()

@app.get("/history")
def get_history(db: Session = Depends(get_db)):
    records = db.query(Analysis)         .order_by(Analysis.created_at.desc())         .limit(20).all()
    return [{
        "id": r.id,
        "type": r.analysis_type,
        "preview": r.input_text[:100],
        "created_at": r.created_at.isoformat()
    } for r in records]
3
Section 3 · 15 min

History Panel in React

javascriptsrc/HistoryPanel.js
import { useEffect, useState } from 'react';
import axios from 'axios';

function HistoryPanel() {
  const [history, setHistory] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:8000/history')
      .then(res => setHistory(res.data));
  }, []);

  return (
    <div>
      <h3>Recent Analyses</h3>
      {history.map(item => (
        <div key={item.id}>
          <strong>{item.type}</strong>{item.preview}...
          <small> {new Date(item.created_at).toLocaleString()}</small>
        </div>
      ))}
    </div>
  );
}
export default HistoryPanel;

What You Learned Today

  • How to save analysis results to SQLite with SQLAlchemy from a FastAPI endpoint
  • How to build a history endpoint that returns the last 20 analyses ordered by time
  • How useEffect + axios fetches data when a React component first loads
  • How to extract the first 100 characters as a text preview for the history list
Your Challenge

Go Further on Your Own

  • Add pagination to the history endpoint: support ?page=1&limit=10 query parameters
  • Add a 'reload history' button in the React frontend that re-fetches the history without refreshing the page
  • Add a DELETE /history/{id} endpoint and a delete button per history item in the React UI
Day 4 Complete

Nice work. Keep going.

Day 5 is ready when you are.

Continue to Day 5
Course Progress
80%

Want live instruction and hands-on projects? Join the AI bootcamp — 3 days, 5 cities.

Finished this lesson?