File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,26 @@
1-
from fastapi import APIRouter
2-
1+
from fastapi import APIRouter, Depends
2+
from sqlmodel import Session
33

4+
from api.db import get_session
5+
from .models import ChatMessagePayload, ChatMessage
46
router = APIRouter()
57

68
# /api/chats/
79
@router.get("/")
810
def chat_health():
9-
return {"status": "ok"}
11+
return {"status": "ok"}
12+
13+
14+
# HTTP POST -> payload = {"message": "Hello world"} -> {"message": "hello world", "id": 1}
15+
@router.post("/", response_model=ChatMessage)
16+
def chat_create_message(
17+
payload:ChatMessagePayload,
18+
session: Session = Depends(get_session)
19+
):
20+
data = payload.model_dump() # pydantic -> dict
21+
obj = ChatMessage.model_validate(data)
22+
session.add(obj)
23+
session.commit()
24+
session.refresh(obj) # ensure id/primary key added to the obj instance
25+
# ready to store in the database
26+
return obj
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
engine = sqlmodel.create_engine(DATABASE_URL)
1313

1414
# database models
15+
# does not create db migrations
1516
def init_db():
1617
print("creating database tables...")
1718
SQLModel.metadata.create_all(engine)

0 commit comments

Comments
 (0)