Working with FastAPI

Our social media API: adding posts

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/models/post.py
from pydantic import BaseModel


class UserPostIn(BaseModel):
    body: str


class UserPost(UserPostIn):
    id: int

Modified files

storeapi/main.py
--- 
+++ 
@@ -1,8 +1,20 @@
 from fastapi import FastAPI
+from storeapi.models.post import UserPost, UserPostIn

 app = FastAPI()

+post_table = {}

-@app.get("/")
-async def root():
-    return {"message": "Hello World"}
+
+@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())