When It Isn't There: HTTPException and 404
A FastAPI route answers 404 for an item that isn't there by raising HTTPException with a status code and a detail message, which stops the function at once and sends {"detail": ...}, and a route that creates something sets status_code=201 on its decorator.
Apprentice · FastAPI · REST API · Updated
After this lesson you can
- Answer 404 for an item that isn't there by raising HTTPException with a detail message, and explain why it's raised and not returned
- Choose a route's success status code with status_code= on its decorator, such as 201 for a route that creates something
Key takeaways
- A route that finds nothing must still say so with its status code. An answer of 200 with null or an error message tells the app that everything went fine.
- raise HTTPException(status_code=404, detail="...") stops the function at once and answers 404 with the body {"detail": "..."}.
- HTTPException has to be raised, not returned. Returned, it's sent as an ordinary 200 answer that happens to contain the words 404.
- Because raising stops everything, a helper function such as find_game can raise the 404 for every route that uses it.
- A route answers 200 unless you choose otherwise. status_code=201 on the decorator says that the route created something.
Ask an API for something that doesn't exist, an order that was never placed or a user who deleted their account, and the app on the other end needs to know, so it can show "not found" instead of a blank screen. The status code is how an API says it, and Status Codes and Headers read them as sentences: 404 means "there's nothing at that address". This lesson shows how a FastAPI route sends one.
The example is the Rolling Dice café's API from Path Parameters and Their Types, where /games/9 still answers 200 with null.
A 200 that isn't fine
The café's shelf has three games, so there's no game 9. The route's loop finds nothing, and the function ends without returning a game. The staff app gets status 200, which says "here it is", and a body of null, and shows an empty card.
A first try is to return a message instead:
@app.get("/games/{game_id}")
def get_game(game_id: int):
for game in GAMES:
if game["id"] == game_id:
return game
return {"error": f"There's no game {game_id}."}
/games/9 now answers 200 with this body:
{"error":"There's no game 9."}
A person can read it, but the app checks the status code first, and 200 still says "here it is". The app would try to show a game whose title is missing. The message is right; the status code is wrong.
raise HTTPException
FastAPI's HTTPException carries a status code and a message. You raise it, the way Python raises a ValueError (Handling Errors with try and except shows raising and catching): the function stops on that line, and FastAPI sends an answer with that status code.
from fastapi import FastAPI, HTTPException
app = FastAPI()
GAMES = [
{"id": 1, "title": "Harbor Lights", "min_players": 2, "max_players": 4, "minutes": 45, "available": True},
{"id": 2, "title": "Moon Mice", "min_players": 3, "max_players": 6, "minutes": 20, "available": False},
{"id": 3, "title": "Tile Town", "min_players": 1, "max_players": 2, "minutes": 30, "available": True},
]
@app.get("/games/{game_id}")
def get_game(game_id: int):
for game in GAMES:
if game["id"] == game_id:
return game
raise HTTPException(status_code=404, detail=f"There's no game {game_id}.")
/games/9 answers 404 Not Found, and detail becomes the body:
{"detail":"There's no game 9."}
/games/2 still answers 200 with Moon Mice: the raise line runs only when the loop finishes without returning. A request for an address the app has no route for at all, such as /snacks, gets FastAPI's own 404, with the body {"detail":"Not Found"}.
Raised, not returned
HTTPException is an object like any other, so a route can return it by mistake:
return HTTPException(status_code=404, detail=f"There's no game {game_id}.")
FastAPI then treats it as data to send. /games/9 answers 200 OK with this body:
{"status_code":404,"detail":"There's no game 9.","headers":null}
The number 404 is in there, but only as text in the body; the real status code is 200. Only a raised HTTPException changes the status code.
Raising has a second advantage: it stops everything, even from inside another function. The café's routes all need "find the game, or answer 404", so one helper can do it for all of them:
def find_game(game_id):
for game in GAMES:
if game["id"] == game_id:
return game
raise HTTPException(status_code=404, detail=f"There's no game {game_id}.")
@app.get("/games/{game_id}")
def get_game(game_id: int):
return find_game(game_id)
When find_game raises, get_game stops too, and the 404 goes out. Each route that uses the helper stays one line long.
201: choosing the success code
Every route answers 200 OK when it succeeds, unless you choose another code. The café counts how often each game is played: POST /games/2/plays records a play of Moon Mice. That request creates something new, and 201 Created says so. Set it with status_code= on the decorator:
PLAYS = []
@app.post("/games/{game_id}/plays", status_code=201)
def record_play(game_id: int):
game = find_game(game_id)
play = {"id": len(PLAYS) + 1, "game_id": game_id, "title": game["title"]}
PLAYS.append(play)
return play
@app.post (read "at app dot post") ties the function to POST requests. The first POST /games/2/plays answers 201 Created:
{"id":1,"game_id":2,"title":"Moon Mice"}
POST /games/9/plays answers 404 with {"detail":"There's no game 9."}: find_game raised before anything was recorded, and the 404 replaced the 201. You'll try POST routes on the docs page in the next lesson, Taking JSON In: Your First Request Body.
Check yourself
2 questions to try on the lesson page.
So what
The status code is the first thing an app reads, so a route that raises a 404 when something's missing and sends 201 when it creates something tells the app the truth before it reads a word of the body.