Working with FastAPI

Splitting our API into files with APIRouter

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

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)