0
0
FastAPIframework~20 mins

HTTPException usage in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
HTTPException Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when HTTPException is raised in FastAPI?
Consider this FastAPI endpoint code:
from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    if item_id < 1:
        raise HTTPException(status_code=400, detail='Invalid item ID')
    return {'item_id': item_id}

What will the client receive if they request /items/0?
FastAPI
from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    if item_id < 1:
        raise HTTPException(status_code=400, detail='Invalid item ID')
    return {'item_id': item_id}
AA JSON response with status 400 and body {"detail": "Invalid item ID"}
BA server crash with a traceback error
CA JSON response with status 200 and body {"item_id": 0}
DA redirect to the root path '/'
Attempts:
2 left
💡 Hint
Think about what HTTPException does in FastAPI when raised inside a route.
📝 Syntax
intermediate
2:00remaining
Identify the correct way to raise HTTPException with a custom header
Which of the following code snippets correctly raises an HTTPException with status 403 and a custom header X-Error: Forbidden?
Araise HTTPException(status_code=403, detail='Forbidden', headers={'X-Error': 'Forbidden'})
Braise HTTPException(403, 'Forbidden', headers={'X-Error': 'Forbidden'})
Craise HTTPException(status=403, message='Forbidden', headers={'X-Error': 'Forbidden'})
Draise HTTPException(code=403, detail='Forbidden', header={'X-Error': 'Forbidden'})
Attempts:
2 left
💡 Hint
Check the exact parameter names in HTTPException constructor.
🔧 Debug
advanced
2:00remaining
Why does this HTTPException raise a TypeError?
Given this code snippet:
from fastapi import HTTPException

raise HTTPException(status_code=404, detail=123)

What error will occur and why?
FastAPI
from fastapi import HTTPException

raise HTTPException(status_code=404, detail=123)
ASyntaxError due to missing parentheses
BNo error, it raises HTTPException with detail 123
CValueError because status_code 404 is invalid
DTypeError because detail must be a string or dict, not an integer
Attempts:
2 left
💡 Hint
Check the expected type for the detail parameter in HTTPException.
state_output
advanced
2:00remaining
What is the response status code after catching HTTPException?
Consider this FastAPI code:
from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get('/test')
async def test():
    try:
        raise HTTPException(status_code=401, detail='Unauthorized')
    except HTTPException as e:
        return {'caught': True, 'status': e.status_code}

What will the HTTP status code of the response be when calling /test?
FastAPI
from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get('/test')
async def test():
    try:
        raise HTTPException(status_code=401, detail='Unauthorized')
    except HTTPException as e:
        return {'caught': True, 'status': e.status_code}
A500 Internal Server Error due to unhandled exception
B401 Unauthorized with JSON body {'caught': True, 'status': 401}
C200 OK with JSON body {'caught': True, 'status': 401}
DNo response because the server crashes
Attempts:
2 left
💡 Hint
Think about what happens when you catch the exception and return a normal dict.
🧠 Conceptual
expert
2:00remaining
Which statement about HTTPException in FastAPI is true?
Select the one correct statement about how HTTPException works in FastAPI.
AHTTPException can only be raised inside dependency functions, not route handlers.
BRaising HTTPException immediately returns an HTTP response with the given status and detail without executing further code in the route.
CHTTPException automatically logs the error to a file named 'http_errors.log'.
DRaising HTTPException changes the global server status code for all future requests.
Attempts:
2 left
💡 Hint
Think about the purpose of HTTPException in request handling.