Bird
Raised Fist0
FastAPIframework~20 mins

HTTPException usage in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of using HTTPException in FastAPI?
easy
A. To create database models automatically
B. To define API routes
C. To handle user authentication
D. To send HTTP error responses with a status code and message

Solution

  1. Step 1: Understand HTTPException role

    HTTPException is designed to send HTTP error responses with specific status codes and messages.
  2. Step 2: Compare with other options

    Other options like database models, authentication, or route definition are unrelated to HTTPException's purpose.
  3. Final Answer:

    To send HTTP error responses with a status code and message -> Option D
  4. Quick Check:

    HTTPException = send error response [OK]
Hint: HTTPException sends errors, not data or routes [OK]
Common Mistakes:
  • Confusing HTTPException with route creation
  • Thinking it manages database or authentication
  • Using it to send successful responses
2. Which of the following is the correct way to raise an HTTP 404 error with a message in FastAPI?
easy
A. return HTTPException(404, "Item not found")
B. raise HTTPException(status_code=404, detail="Item not found")
C. HTTPException(404, detail="Item not found")
D. raise HTTPException(404, message="Item not found")

Solution

  1. Step 1: Check correct syntax for raising HTTPException

    The correct syntax uses raise HTTPException(status_code=404, detail="Item not found").
  2. Step 2: Identify errors in other options

    return HTTPException(404, "Item not found") wrongly uses return instead of raise. HTTPException(404, detail="Item not found") misses raise keyword. raise HTTPException(404, message="Item not found") uses incorrect keyword 'message' instead of 'detail'.
  3. Final Answer:

    raise HTTPException(status_code=404, detail="Item not found") -> Option B
  4. Quick Check:

    Use raise + status_code + detail [OK]
Hint: Always use raise with status_code and detail keys [OK]
Common Mistakes:
  • Using return instead of raise
  • Missing status_code or detail keywords
  • Using wrong keyword like message
3. What will happen when this FastAPI endpoint is called and the item is not found?
from fastapi import FastAPI, HTTPException
app = FastAPI()

items = {"apple": "A juicy fruit"}

@app.get("/items/{item_name}")
async def read_item(item_name: str):
    if item_name not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_name]}
medium
A. The API returns the string 'Item not found'
B. The API returns an empty JSON response
C. The API returns a 404 error with message 'Item not found'
D. The API crashes with a server error

Solution

  1. Step 1: Analyze the condition for missing item

    If the requested item_name is not in the items dictionary, the code raises HTTPException with status 404 and detail message.
  2. Step 2: Understand FastAPI behavior on HTTPException

    FastAPI catches HTTPException and sends an HTTP response with the given status code and detail message as JSON.
  3. Final Answer:

    The API returns a 404 error with message 'Item not found' -> Option C
  4. Quick Check:

    Missing item triggers HTTPException 404 [OK]
Hint: Missing item triggers HTTPException with 404 [OK]
Common Mistakes:
  • Expecting empty or string response instead of error
  • Thinking the server crashes
  • Ignoring the raise keyword effect
4. Identify the error in this FastAPI code snippet:
from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get("/users/{user_id}")
def get_user(user_id: int):
    if user_id < 0:
        HTTPException(status_code=400, detail="Invalid user ID")
    return {"user_id": user_id}
medium
A. Missing raise keyword before HTTPException
B. Incorrect status_code value for error
C. user_id should be a string, not int
D. The endpoint path is invalid

Solution

  1. Step 1: Check how HTTPException is used

    The code calls HTTPException but does not use raise, so the exception is not actually raised.
  2. Step 2: Verify other parts

    Status code 400 is valid for bad request. user_id as int is correct. Endpoint path syntax is valid.
  3. Final Answer:

    Missing raise keyword before HTTPException -> Option A
  4. Quick Check:

    Always use raise before HTTPException [OK]
Hint: Use raise before HTTPException to trigger error [OK]
Common Mistakes:
  • Calling HTTPException without raise
  • Using wrong status codes for errors
  • Confusing parameter types
5. You want to create a FastAPI endpoint that returns a 403 Forbidden error with a custom message if a user is not an admin. Which code snippet correctly implements this?
hard
A. if not is_admin: raise HTTPException(status_code=403, detail="Access denied: Admins only")
B. if not is_admin: return HTTPException(status_code=403, detail="Access denied: Admins only")
C. if not is_admin: raise HTTPException(403, message="Access denied: Admins only")
D. if not is_admin: HTTPException(status_code=403, detail="Access denied: Admins only")

Solution

  1. Step 1: Check correct way to raise HTTPException with 403

    The correct way is to use raise with status_code=403 and detail message.
  2. Step 2: Identify errors in other options

    if not is_admin: return HTTPException(status_code=403, detail="Access denied: Admins only") uses return instead of raise, so no error is raised. if not is_admin: raise HTTPException(403, message="Access denied: Admins only") uses wrong keyword 'message'. if not is_admin: HTTPException(status_code=403, detail="Access denied: Admins only") calls HTTPException without raise, so no exception is triggered.
  3. Final Answer:

    if not is_admin: raise HTTPException(status_code=403, detail="Access denied: Admins only") -> Option A
  4. Quick Check:

    Use raise + status_code + detail for errors [OK]
Hint: Raise HTTPException with status_code and detail for errors [OK]
Common Mistakes:
  • Using return instead of raise
  • Wrong keyword 'message' instead of 'detail'
  • Calling HTTPException without raise