In this section, we’ll understand the process of building a feature to allow users to create posts in our social media API. We’ll utilize FastAPI’s powerful data validation and request body handling capabilities to ensure that posts are created correctly.
Setting Up the Data Model
First, we’ll define a data model for our posts using Pydantic:
Python
from pydantic import BaseModel
class Post(BaseModel):
content: str
user_id: int
This model ensures that posts have a content
field and a user_id
field.
Creating a POST Endpoint
Now, we’ll create a POST endpoint to handle the creation of new posts:
Python
from fastapi import APIRouter, HTTPException
router = APIRouter()
@router.post("/posts")
async def create_post(post: Post, db: Session = Depends(get_db)):
new_post = PostModel(content=post.content, user_id=post.user_id)
db.add(new_post)
db.commit()
db.refresh(new_post)
return new_post
Explanation:
- The
@router.post("/posts")
decorator defines a POST endpoint for the/posts
path. - The
post: Post
argument indicates that the request body should be parsed as aPost
object. - The
db: Session = Depends(get_db)
argument injects a database session into the function. - A new
PostModel
instance is created using the data from the request body. - The new post is added to the database session.
- The changes are committed to the database.
- The new post is refreshed to get its assigned ID.
- The created post is returned as a response.
Handling Errors
You might want to add error handling to catch exceptions like database errors or validation errors:
Python
try:
db.add(new_post)
db.commit()
db.refresh(new_post)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error creating post: {e}")