New files
storeapi/routers/posts.py
from fastapi import APIRouter
from storeapi.models.post import UserPost, UserPostIn
router = APIRouter()
post_table = {}
@router.post("/post", response_model=UserPost, status_code=201)
async def create_post(post: UserPostIn):
data = post.model_dump() # previously .dict()
last_record_id = len(post_table)
new_post = {**data, "id": last_record_id}
post_table[last_record_id] = new_post
return new_post
@router.get("/post", response_model=list[UserPost])
async def get_all_posts():
return list(post_table.values())
Modified files
storeapi/main.py
---
+++
@@ -1,20 +1,5 @@
from fastapi import FastAPI
-from storeapi.models.post import UserPost, UserPostIn
+from storeapi.routers.posts import router as posts_router
app = FastAPI()
-
-post_table = {}
-
-
-@app.post("/post", response_model=UserPost)
-async def create_post(post: UserPostIn):
- data = post.model_dump() # previously .dict()
- last_record_id = len(post_table)
- new_post = {**data, "id": last_record_id}
- post_table[last_record_id] = new_post
- return new_post
-
-
-@app.get("/post", response_model=list[UserPost])
-async def get_all_posts():
- return list(post_table.values())
+app.include_router(posts_router)