Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from fastapi import FastAPI, HTTPException
- from pydantic import BaseModel
- from sqlalchemy import create_engine, Column, Integer, String, select
- from sqlalchemy.orm import sessionmaker, declarative_base
- app = FastAPI()
- # ---------- DATABASE SETUP ----------
- DATABASE_URL = "sqlite:///./projects.db"
- engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
- SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
- Base = declarative_base()
- class Project(Base):
- __tablename__ = "projects"
- id = Column(Integer, primary_key=True, index=True)
- name = Column(String)
- description = Column(String)
- Base.metadata.create_all(bind=engine)
- # ---------- RESPONSE MODEL ----------
- class ProjectResponse(BaseModel):
- id: int
- name: str
- description: str
- # ---------- API ENDPOINT ----------
- @app.get("/projects/{project_id}", response_model=ProjectResponse)
- def get_project(project_id: int):
- db = SessionLocal()
- project = db.execute(
- select(Project).where(Project.id == project_id)
- ).scalar_one_or_none()
- if not project:
- raise HTTPException(status_code=404, detail="Project not found")
- return ProjectResponse(
- id=project.id, name=project.name, description=project.description
- )
Advertisement
Add Comment
Please, Sign In to add comment