Skip to content

Commit d4b5e05

Browse files
author
sathya
committed
Initial working FastAPI app with PostGreSQL
1 parent 3a6a049 commit d4b5e05

File tree

6 files changed

+147
-0
lines changed

6 files changed

+147
-0
lines changed

.gitignore

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Python
2+
__pycache__/
3+
*.py[cod]
4+
*.pyo
5+
6+
# Environments
7+
env/
8+
venv/
9+
.venv/
10+
11+
# dotenv
12+
.env
13+
.env.*
14+
15+
# IDE
16+
.idea/
17+
.vscode/
18+
19+
# macOS
20+
.DS_Store
21+
22+
# DB backups / misc
23+
*.sqlite3
24+
*.log

crud.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from models import Item
2+
from sqlalchemy.orm import Session
3+
from schemas import ItemCreate
4+
5+
# CREATE
6+
def create_item(db: Session, item: ItemCreate):
7+
db_item = Item(**item.model_dump())
8+
db.add(db_item)
9+
db.commit()
10+
db.refresh(db_item)
11+
return db_item
12+
13+
# READ
14+
def get_items(db: Session):
15+
return db.query(Item).all()
16+
17+
# READ ONLY ONE
18+
def get_item(db: Session, item_id: int):
19+
return db.query(Item).filter(Item.id == item_id).first()
20+
21+
def update_item(db: Session, item_id: int, updated_data: ItemCreate):
22+
item = db.query(Item).filter(Item.id == item_id).first()
23+
if item:
24+
item.name = updated_data.name
25+
item.description = updated_data.description
26+
db.commit()
27+
db.refresh(item)
28+
29+
return item
30+
return None
31+
32+
def delete_item(db: Session, item_id: int):
33+
item = db.query(Item).filter(Item.id == item_id).first()
34+
if item:
35+
db.delete(item)
36+
db.commit()
37+
return item
38+
return None

database.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from sqlalchemy import create_engine
2+
from sqlalchemy.orm import sessionmaker, declarative_base
3+
from dotenv import load_dotenv
4+
import os
5+
6+
load_dotenv()
7+
8+
DATABASE_URL= os.getenv("DATABASE_URL")
9+
10+
engine = create_engine(DATABASE_URL)
11+
12+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
13+
14+
Base = declarative_base()

main.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from database import SessionLocal, engine, Base
2+
import models, schemas, crud
3+
from fastapi import FastAPI, Depends, HTTPException
4+
from sqlalchemy.orm import Session
5+
6+
models.Base.metadata.create_all(bind=engine)
7+
print("Table is created")
8+
9+
def get_db():
10+
db = SessionLocal()
11+
try:
12+
yield db
13+
finally:
14+
db.close()
15+
16+
# Creating Routes
17+
app = FastAPI()
18+
19+
@app.post("/items/", response_model= schemas.Item)
20+
def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)):
21+
return crud.create_item(db, item)
22+
23+
@app.get("/items/", response_model=list[schemas.Item])
24+
def read_items(db: Session = Depends(get_db)):
25+
return crud.get_items(db)
26+
27+
@app.get("/items/{item_id}", response_model=schemas.Item)
28+
def read_item(item_id: int, db: Session = Depends(get_db)):
29+
item= crud.get_item(db, item_id)
30+
if not item:
31+
raise HTTPException(status_code=404, detail="Item NOT FOUND")
32+
return item
33+
34+
@app.put("/items/{item_id}", response_model= schemas.Item)
35+
def update_item(item_id: int, item: schemas.ItemCreate, db: Session= Depends(get_db)):
36+
updated_item = crud.update_item(db, item_id, item)
37+
if not updated_item:
38+
raise HTTPException(status_code=404, detail="Item NOT FOUND")
39+
return updated_item
40+
41+
@app.delete("/items/{item_id}")
42+
def delete_item(item_id: int, db: Session= Depends(get_db)):
43+
deleted_item = crud.delete_item(db, item_id)
44+
if not deleted_item:
45+
raise HTTPException(status_code=404, detail="Item NOT FOUND")
46+
return {"details": "Deleted"}
47+

models.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from database import Base
2+
from sqlalchemy import Column, Integer, String
3+
4+
class Item(Base):
5+
__tablename__ = "items"
6+
7+
id = Column(Integer, primary_key=True, index=True)
8+
name = Column(String, index=True)
9+
description = Column(String)

schemas.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from pydantic import BaseModel
2+
# For data validation while performing CRUD operations
3+
4+
class ItemBase(BaseModel):
5+
name: str
6+
description: str
7+
8+
class ItemCreate(ItemBase):
9+
pass
10+
11+
class Item(ItemBase):
12+
id: int
13+
model_config = {
14+
"from_attributes": True
15+
}

0 commit comments

Comments
 (0)