Changing response Status Codes
from fastapi import FastAPI
from typing import Optional
from pydantic import BaseModel
from random import randrange
app = FastAPI()
class Post(BaseModel):
title: str
content: str
published: bool = True
rating: Optional[int] = None
# Global variable to save the post in memory
my_posts = [
{
"title": "title of post 1",
"content": "content of post 1",
"id": 1
},
{
"title": "favorite foods",
"content": "Pizza",
"id": 2
}
]
@app.get("/posts/{id}")
def get_post(id: int):
post = find_post(id)
return {"post_details": post}

There is a better way of doing things

The above method is fine but a little sloppy, there is a even better way of raising this sort of exceptions so that you don't have to hardcode values
Returning a HTTP code inside the decorator

Last updated