Bird
Raised Fist0
FastAPIframework~20 mins

Status code control in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Status Code Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What status code does this FastAPI endpoint return?
Consider this FastAPI endpoint code. What HTTP status code will the client receive when calling /items/42?
FastAPI
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    if item_id == 42:
        return JSONResponse(content={'item_id': item_id}, status_code=202)
    return {'item_id': item_id}
A200
B500
C404
D202
Attempts:
2 left
💡 Hint
Look at the status_code parameter in JSONResponse for item_id 42.
📝 Syntax
intermediate
2:00remaining
Which option correctly sets a 201 status code for a POST endpoint?
You want to create a FastAPI POST endpoint that returns status code 201 when a new item is created. Which code snippet correctly sets this status code?
A
@app.post('/items')
async def create_item(item: dict):
    return Response(content=item, status_code=201)
B
@app.post('/items')
async def create_item(item: dict):
    return JSONResponse(content=item, status_code=201)
C
@app.post('/items', status_code=201)
async def create_item(item: dict):
    return item
D
@app.post('/items')
async def create_item(item: dict):
    return {'item': item, 'status': 201}
Attempts:
2 left
💡 Hint
Check how FastAPI allows setting status codes directly in the decorator.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI endpoint always return status 200 instead of 404?
Examine the code below. The intention is to return 404 if the item is not found. Why does it always return 200?
FastAPI
from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {1: 'apple', 2: 'banana'}

@app.get('/items/{item_id}')
async def get_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail='Item not found')
    return {'item': items[item_id]}
AHTTPException must be raised, not returned, to trigger the error response.
BThe status_code 404 is invalid and defaults to 200.
CThe items dictionary is empty, so the condition never triggers.
DFastAPI does not support HTTPException for status control.
Attempts:
2 left
💡 Hint
Think about how exceptions work in Python and FastAPI.
❓ state_output
advanced
2:00remaining
What is the status code and response body when this FastAPI endpoint is called with /users/0?
Analyze the following FastAPI endpoint. What status code and JSON response will the client receive when requesting /users/0?
FastAPI
from fastapi import FastAPI, Response

app = FastAPI()

@app.get('/users/{user_id}')
async def get_user(user_id: int):
    if user_id == 0:
        return Response(content='User not found', status_code=404, media_type='text/plain')
    return {'user_id': user_id}
AStatus code 404 with plain text body 'User not found'
BStatus code 200 with JSON body {'user_id': 0}
CStatus code 404 with JSON body {'detail': 'User not found'}
DStatus code 500 with empty body
Attempts:
2 left
💡 Hint
Look at the Response object and its parameters.
🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI status code control is true?
Select the correct statement about how FastAPI handles HTTP status codes in endpoint responses.
AReturning a dictionary from an endpoint always results in status code 500 unless a status_code is set explicitly.
BSetting status_code in the decorator changes the default response status code unless overridden by returning a Response with a different status_code.
CFastAPI automatically sets status code 201 for all POST requests regardless of decorator or return value.
DRaising HTTPException changes the response body but does not affect the HTTP status code sent to the client.
Attempts:
2 left
💡 Hint
Think about how decorator status_code and return values interact.

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

  1. Step 1: Understand HTTP status codes

    Status codes communicate the result of a request, like success (200) or error (404).
  2. Step 2: Role of status_code in FastAPI

    Setting status_code in a route tells the client what happened with their request.
  3. Final Answer:

    To tell the client if the request was successful or if there was an error -> Option C
  4. 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

  1. Step 1: Check FastAPI decorator usage

    FastAPI allows setting status_code directly in the route decorator.
  2. 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).
  3. Final Answer:

    @app.post('/items', status_code=201) def create_item(): return {'message': 'Created'} -> Option D
  4. 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

  1. Step 1: Identify the response type and status code

    The route returns a JSONResponse with status_code=202.
  2. Step 2: Understand HTTP status code 202

    Status code 202 means "Accepted" indicating the request is accepted but not completed yet.
  3. Final Answer:

    202 Accepted -> Option A
  4. 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:
from fastapi import FastAPI

app = FastAPI()

@app.get('/item/{item_id}', status_code=404)
async def read_item(item_id: int):
    return {'item_id': item_id}
medium
A. Function must raise HTTPException for 404, not set status_code
B. Setting status_code=404 in decorator always returns 404 even if item exists
C. Route path is invalid syntax
D. Missing return type annotation causes error

Solution

  1. Step 1: Understand status_code in decorator

    Setting status_code=404 in the decorator makes every response return 404 status regardless of logic.
  2. Step 2: Why this is a problem

    The route returns data but status 404 means "Not Found" which is misleading if item exists.
  3. Final Answer:

    Setting status_code=404 in decorator always returns 404 even if item exists -> Option B
  4. Quick Check:

    Decorator status_code sets fixed response code [OK]
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

  1. Step 1: Understand status code control methods

    Setting status_code=201 in decorator sets default success code. Raising HTTPException sends error with desired status.
  2. 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.
  3. Final Answer:

    Use status_code=201 in decorator and raise HTTPException(status_code=400) if username missing -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard