Complete the code to import the FastAPI class.
from fastapi import [1] app = [1]()
FastAPI is the main class to create an app instance.
Complete the code to raise an HTTP 404 error when item not found.
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]
HTTPException is used to raise HTTP errors in FastAPI.
Fix the error in the exception handler decorator.
@app.exception_handler([1]) async def http_exception_handler(request, exc): return JSONResponse(status_code=exc.status_code, content={'message': exc.detail})
The exception handler must specify the exception class it handles, here HTTPException.
Fill both blanks to return a JSON response with error details.
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})
JSONResponse is used to send JSON formatted responses in FastAPI.
Fill all three blanks to create a reliable endpoint with error handling.
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]})
We import JSONResponse to send JSON data, raise HTTPException for errors, and use JSONResponse to return data.
