Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the correct FastAPI class.
FastAPI
from fastapi import [1] app = [1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI
Trying to instantiate HTTPException as the app
✗ Incorrect
The FastAPI class is imported to create the app instance.
2fill in blank
mediumComplete the code to define a custom exception handler for HTTPException.
FastAPI
@app.exception_handler([1]) async def http_exception_handler(request, exc): return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of HTTPException
Using the base Exception class which is too broad
✗ Incorrect
The HTTPException class is used to catch HTTP errors in FastAPI.
3fill in blank
hardFix the error in the custom exception handler to return a JSON response.
FastAPI
from fastapi.responses import [1] @app.exception_handler(ValueError) async def value_error_handler(request, exc): return [1](status_code=400, content={"error": str(exc)})
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using PlainTextResponse or HTMLResponse which do not send JSON
Forgetting to import JSONResponse
✗ Incorrect
Use JSONResponse to send JSON content back to the client.
4fill in blank
hardFill both blanks to create a custom exception and handler that returns a JSON error message.
FastAPI
class CustomError(Exception): def __init__(self, message): self.message = message @app.exception_handler([1]) async def custom_error_handler(request, exc): return JSONResponse(status_code=[2], content={"error": exc.message})
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using HTTPException instead of CustomError in the handler decorator
Using wrong status code like 500
✗ Incorrect
The handler catches CustomError and returns status code 400.
5fill in blank
hardFill all three blanks to raise a custom exception and handle it with a JSON response.
FastAPI
class MyException(Exception): def __init__(self, detail): self.detail = detail @app.get("/error") async def error_route(): raise [1]("Something went wrong") @app.exception_handler([2]) async def my_exception_handler(request, exc): return JSONResponse(status_code=[3], content={"error": exc.detail})
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Raising a different exception than handled
Using status code 500 instead of 400
✗ Incorrect
The route raises MyException, which is handled by the custom handler returning status 400.