thewitchking

Untitled

Nov 21st, 2025
895
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. from fastapi import FastAPI, HTTPException
  2. from pydantic import BaseModel
  3. from sqlalchemy import create_engine, Column, Integer, String, select
  4. from sqlalchemy.orm import sessionmaker, declarative_base
  5.  
  6. app = FastAPI()
  7.  
  8. # ---------- DATABASE SETUP ----------
  9. DATABASE_URL = "sqlite:///./projects.db"
  10.  
  11. engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
  12. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  13. Base = declarative_base()
  14.  
  15.  
  16. class Project(Base):
  17.     __tablename__ = "projects"
  18.  
  19.     id = Column(Integer, primary_key=True, index=True)
  20.     name = Column(String)
  21.     description = Column(String)
  22.  
  23.  
  24. Base.metadata.create_all(bind=engine)
  25.  
  26.  
  27. # ---------- RESPONSE MODEL ----------
  28. class ProjectResponse(BaseModel):
  29.     id: int
  30.     name: str
  31.     description: str
  32.  
  33.  
  34. # ---------- API ENDPOINT ----------
  35. @app.get("/projects/{project_id}", response_model=ProjectResponse)
  36. def get_project(project_id: int):
  37.     db = SessionLocal()
  38.     project = db.execute(
  39.         select(Project).where(Project.id == project_id)
  40.     ).scalar_one_or_none()
  41.  
  42.     if not project:
  43.         raise HTTPException(status_code=404, detail="Project not found")
  44.  
  45.     return ProjectResponse(
  46.         id=project.id, name=project.name, description=project.description
  47.     )
  48.  
Advertisement
Add Comment
Please, Sign In to add comment