Day 04 Advanced Patterns

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 hour Hands-on Precision AI Academy

Today's Objective

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.


  
code
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)
01
Section 2 · 15 min

Save and Retrieve Analyses

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

backend/main.py (update)
python
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]
01
Section 3 · 15 min

History Panel in React

src/HistoryPanel.js
javascript
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;
80%

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

Supporting References & Reading

Go deeper with these external resources.

Docs
Database Integration and User History Official documentation for fullstack ai.
GitHub
Database Integration and User History Open source examples and projects for Database Integration and User History
MDN
MDN Web Docs Comprehensive web technology reference

Day 4 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 5
Day 5 of the Full-Stack AI course