Add persistent storage so users can see their previous analyses. Every analysis gets saved to PostgreSQL and retrieved on demand.
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.
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)
Update the analyze endpoint to save results, and add a history endpoint:
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]
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;
Want live instruction and hands-on projects? Join the AI bootcamp — 3 days, 5 cities.
Before moving on, confirm understanding of these key concepts: