In the last post, Extra Models, we tidied up our family of Blog models. We have the body fully under control. Now the small but important number that rides next to it: the HTTP status code. When you create a blog, returning a plain 200 OK is a little off. The right answer is 201 Created. Let's set it. 🤔
Setting the status code
Add status_code to the decorator, just like response_model from earlier.
from fastapi import FastAPIfrom pydantic import BaseModelapp = FastAPI()class Blog(BaseModel): title: str content: str@app.post("/blog", status_code=201)async def create_blog(blog: Blog): return blogLet's review:
status_code=201lives on the decorator, not in the function signature.FastAPI returns that code on success and documents it in
/docs.201means "Created", the right fit for a POST that makes something new.
Using the status shortcut
Nobody wants to memorize code numbers. FastAPI ships named constants in fastapi.status so your editor can autocomplete them.
from fastapi import FastAPI, statusfrom pydantic import BaseModelapp = FastAPI()class Blog(BaseModel): title: str content: str@app.post("/blog", status_code=status.HTTP_201_CREATED)async def create_blog(blog: Blog): return blogstatus.HTTP_201_CREATED is just 201 with a readable name. Same result, clearer code.
A few you will reach for: 200 OK (the default), 201 Created (after a POST), 204 No Content (deletes with nothing to return), and 404 Not Found (the resource is missing).
