File tree
Expand file treeCollapse file tree2 files changed
+21
-3
lines changed Expand file treeCollapse file tree2 files changed
+21
-3
lines changed Original file line number | Diff line number | Diff line change |
---|
|
1 |
| -from fastapi import APIRouter |
2 |
| - |
| 1 | +from fastapi import APIRouter, Depends |
| 2 | +from sqlmodel import Session |
3 | 3 |
|
| 4 | +from api.db import get_session |
| 5 | +from .models import ChatMessagePayload, ChatMessage |
4 | 6 | router = APIRouter()
|
5 | 7 |
|
6 | 8 | # /api/chats/
|
7 | 9 | @router.get("/")
|
8 | 10 | 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 number | Diff line number | Diff line change |
---|
|
12 | 12 | engine = sqlmodel.create_engine(DATABASE_URL)
|
13 | 13 |
|
14 | 14 | # database models
|
| 15 | +# does not create db migrations |
15 | 16 | def init_db():
|
16 | 17 | print("creating database tables...")
|
17 | 18 | SQLModel.metadata.create_all(engine)
|
|
You can’t perform that action at this time.
0 commit comments