0
0
FastAPIframework~10 mins

Why error handling ensures reliability in FastAPI - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AHTTPException
BRequest
CResponse
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI.
Trying to create app with a wrong class name.
2fill in blank
medium

Complete the code to raise an HTTP 404 error when item not found.

FastAPI
from fastapi import HTTPException

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    if item_id not in items:
        raise [1](status_code=404, detail='Item not found')
    return items[item_id]
Drag options to blanks, or click blank then click option'
AFastAPI
BHTTPException
CResponse
DRequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of HTTPException.
Not raising an exception at all.
3fill in blank
hard

Fix the error in the exception handler decorator.

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'
AHTTPException
BRequest
CResponse
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response in the decorator instead of HTTPException.
Not specifying any exception class.
4fill in blank
hard

Fill both blanks to return a JSON response with error details.

FastAPI
from fastapi.responses import [1]

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return [2](status_code=exc.status_code, content={'error': exc.detail})
Drag options to blanks, or click blank then click option'
AJSONResponse
BHTMLResponse
CPlainTextResponse
DRedirectResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Importing or returning HTMLResponse or PlainTextResponse instead of JSONResponse.
Returning RedirectResponse which is for redirects.
5fill in blank
hard

Fill all three blanks to create a reliable endpoint with error handling.

FastAPI
from fastapi import FastAPI, HTTPException
from fastapi.responses import [1]

app = FastAPI()

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

@app.get('/items/{item_id}')
async def read_item(item_id: int):
    if item_id not in items:
        raise [2](status_code=404, detail='Item not found')
    return [3](content={'item': items[item_id]})
Drag options to blanks, or click blank then click option'
AJSONResponse
BHTTPException
CResponse
DRequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request instead of HTTPException for errors.
Returning HTTPException instead of a response.
Not importing JSONResponse.