📖 Scenario: You are building a simple web API using FastAPI. Your API will respond to client requests with different HTTP status codes depending on the situation.This is like a restaurant where the waiter tells you if your order is accepted, delayed, or not available by using different signals.
🎯 Goal: Create a FastAPI app with one endpoint that returns a JSON message and controls the HTTP status code explicitly.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a GET endpoint at path /items/{item_id}
Use a variable item_id as a path parameter
Return a JSON response with a message and a status code
Return status code 200 if item_id is 1
Return status code 404 if item_id is not 1
💡 Why This Matters
🌍 Real World
APIs often need to tell clients if a request was successful or if something went wrong. Controlling status codes helps clients understand the result and handle it properly.
💼 Career
Knowing how to set HTTP status codes in FastAPI is essential for backend developers building reliable and clear APIs.
Progress0 / 4 steps
1
Create FastAPI app and define endpoint
Import FastAPI from fastapi and create an app instance called app. Then define a GET endpoint function called read_item with a path parameter item_id of type int at path /items/{item_id}.
FastAPI
Hint
Start by importing FastAPI and creating an app instance. Then use the @app.get decorator with the path /items/{item_id}. Define an async function read_item that takes item_id as an integer parameter.
2
Add a status code variable
Inside the read_item function, create a variable called status_code and set it to 200.
FastAPI
Hint
Inside the function, write status_code = 200 to start with a default success code.
3
Change status code for missing item
Add an if statement inside read_item to check if item_id is not equal to 1. If so, set status_code to 404.
FastAPI
Hint
Use an if statement to check if item_id is not 1, then assign status_code = 404.
4
Return JSON response with status code
Set a message to "Item found" if status_code == 200 else "Item not found". Return JSONResponse(content={"message": message}, status_code=status_code).
FastAPI
Hint
Import JSONResponse from fastapi.responses. Use a conditional expression to set the message. Return JSONResponse with content as a dictionary and status_code as the HTTP status.
Practice
(1/5)
1. What is the purpose of setting a status_code in a FastAPI route?
easy
A. To define the data type of the response
B. To change the URL path of the route
C. To tell the client if the request was successful or if there was an error
D. To set the server's port number
Solution
Step 1: Understand HTTP status codes
Status codes communicate the result of a request, like success (200) or error (404).
Step 2: Role of status_code in FastAPI
Setting status_code in a route tells the client what happened with their request.
Final Answer:
To tell the client if the request was successful or if there was an error -> Option C
Quick Check:
Status code = success or error info [OK]
Hint: Status codes show request success or failure [OK]
Common Mistakes:
Confusing status_code with URL path
Thinking status_code sets response data type
Mixing status_code with server settings
2. Which of the following is the correct way to set a 201 status code for a POST route in FastAPI?
easy
A. @app.post('/items')
def create_item():
status_code = 201
return {'message': 'Created'}
B. @app.post('/items')
def create_item():
return JSONResponse({'message': 'Created'}, status=201)
C. @app.post('/items')
def create_item():
return {'message': 'Created'}, 201
D. @app.post('/items', status_code=201)
def create_item():
return {'message': 'Created'}
Solution
Step 1: Check FastAPI decorator usage
FastAPI allows setting status_code directly in the route decorator.
Step 2: Analyze each option
@app.post('/items', status_code=201)
def create_item():
return {'message': 'Created'} correctly sets status_code=201 in the decorator. @app.post('/items')
def create_item():
status_code = 201
return {'message': 'Created'} wrongly assigns inside function without effect. @app.post('/items')
def create_item():
return {'message': 'Created'}, 201 returns a tuple which FastAPI does not accept. @app.post('/items')
def create_item():
return JSONResponse({'message': 'Created'}, status=201) uses JSONResponse but with wrong parameter name (status instead of status_code).
Final Answer:
@app.post('/items', status_code=201)
def create_item():
return {'message': 'Created'} -> Option D
Quick Check:
Set status_code in decorator = @app.post('/items', status_code=201)
def create_item():
return {'message': 'Created'} [OK]
Hint: Use status_code in decorator for simple status setting [OK]
Common Mistakes:
Trying to set status_code inside function without response object
Returning tuple with status code (not supported)
Using wrong parameter name in JSONResponse
3. What status code will this FastAPI route return when called?
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get('/data')
async def get_data():
return JSONResponse(content={'info': 'ok'}, status_code=202)
medium
A. 202 Accepted
B. 201 Created
C. 200 OK
D. 404 Not Found
Solution
Step 1: Identify the response type and status code
The route returns a JSONResponse with status_code=202.
Step 2: Understand HTTP status code 202
Status code 202 means "Accepted" indicating the request is accepted but not completed yet.
Final Answer:
202 Accepted -> Option A
Quick Check:
JSONResponse with status_code=202 = 202 Accepted [OK]
Hint: Check status_code in JSONResponse for actual returned code [OK]
Common Mistakes:
Assuming default 200 OK without checking status_code
Confusing 201 Created with 202 Accepted
Ignoring status_code parameter in JSONResponse
4. Identify the error in this FastAPI route that tries to return a 404 status code:
Hint: Decorator status_code sets fixed code, use exceptions for errors [OK]
Common Mistakes:
Using status_code=404 in decorator to signal missing item
Not raising HTTPException for 404 errors
Assuming status_code in decorator is dynamic
5. You want to create a FastAPI route that returns 201 when a new user is created, but 400 if the username is missing. Which is the best way to control the status codes?
hard
A. Use status_code=201 in decorator and raise HTTPException(status_code=400) if username missing
B. Set status_code=201 in decorator and return JSONResponse with status_code=400 inside function
C. Return a tuple with data and status code 201 or 400
D. Set status_code=400 in decorator and return 201 in response body
Solution
Step 1: Understand status code control methods
Setting status_code=201 in decorator sets default success code. Raising HTTPException sends error with desired status.
Step 2: Evaluate options
Use status_code=201 in decorator and raise HTTPException(status_code=400) if username missing uses decorator for success and exception for error, which is correct. Set status_code=201 in decorator and return JSONResponse with status_code=400 inside function mixes decorator and response status codes causing confusion. Return a tuple with data and status code 201 or 400 returning tuple is invalid in FastAPI. Set status_code=400 in decorator and return 201 in response body sets wrong default status code and misuses response body.
Final Answer:
Use status_code=201 in decorator and raise HTTPException(status_code=400) if username missing -> Option A
Quick Check:
Decorator for success, exceptions for errors [OK]
Hint: Use decorator for success, raise HTTPException for errors [OK]
Common Mistakes:
Returning tuples with status codes (not supported)
Setting error status_code in decorator instead of raising exception
Mixing response status codes inconsistently
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.