Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the 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 create app with a wrong class name.
✗ Incorrect
FastAPI is the main class to create an app instance.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of HTTPException.
Not raising an exception at all.
✗ Incorrect
HTTPException is used to raise HTTP errors in FastAPI.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response in the decorator instead of HTTPException.
Not specifying any exception class.
✗ Incorrect
The exception handler must specify the exception class it handles, here HTTPException.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing or returning HTMLResponse or PlainTextResponse instead of JSONResponse.
Returning RedirectResponse which is for redirects.
✗ Incorrect
JSONResponse is used to send JSON formatted responses in FastAPI.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request instead of HTTPException for errors.
Returning HTTPException instead of a response.
Not importing JSONResponse.
✗ Incorrect
We import JSONResponse to send JSON data, raise HTTPException for errors, and use JSONResponse to return data.