Skip to content
tezvyn:

FastAPI: Set a Response's HTTP Status Code

Source: fastapi.tiangolo.comMediumHow cards are made

FastAPI: Set a Response's HTTP Status Code

In FastAPI, set the success status code in the decorator, not the function. Use status_code=201 in @app.post() to signal resource creation. The common footgun is placing status_code in the function signature instead of the decorator itself.

Why it exists

APIs use HTTP status codes to communicate the result of an operation. While a 200 OK is a fine default for successful GET requests, other operations have more specific success codes. For example, creating a resource should ideally return 201 Created. FastAPI provides a declarative way to set the correct success code for an endpoint.

The mental model

Think of the success status code as part of the endpoint's contract, not the function's result. You declare it alongside the path and HTTP method in the decorator because it defines how the API behaves on success, independent of the specific data being returned by your function.

How it works

In any path operation decorator (@app.get, @app.post, etc.), add the status_code argument. FastAPI will use this code for all successful responses from that endpoint, overriding the default 200 OK. You can provide a raw integer like 201 or use Python's http.HTTPStatus enum for better readability (e.g., status_code=status.HTTP_201_CREATED after an import).

When to use it

Use this parameter whenever the default 200 OK is not the most semantically correct status for a successful operation. The most common use case is setting status_code=201 for POST requests that create a new resource. Another might be 204 No Content for a DELETE operation that succeeds but returns no body.

When not to use it

The status_code parameter is only for the default success response. For error conditions, you should raise an HTTPException. For instance, to return a 404 Not Found, you would raise HTTPException(status_code=404, detail="Item not found") from within your function logic. Do not try to set error codes in the decorator.

One canonical example

from fastapi import FastAPI, status
app = FastAPI()

@app.post("/items/", status_code=status.HTTP_201_CREATED)

async def create_item(name: str):

Logic to create the item in a database...

return {"name": name}

A successful POST to /items/ will now return a 201 status code.

Interview question

Which is the correct way to set a 201 Created status for a new resource created via a FastAPI POST endpoint?

  • a.@app.post("/items/") async def create_item(name: str, status_code: int = 201):
  • b.@app.post("/items/") async def create_item(name: str): return Response(status_code=201)
  • c.@app.post("/items/", status_code=201)Correct
  • d.@app.post("/items/") async def create_item(name: str): raise HTTPException(status_code=201, detail="Resource created")
Why?

The card explicitly states that the success status code should be set in the path operation decorator, as shown in option C, because it's part of the endpoint's contract. Option A is identified as a 'common footgun' for placing it in the function signature, and option D incorrectly uses HTTPException for a success code.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.

See open roles