Complete the code to return a 201 status code from the FastAPI endpoint.
from fastapi import FastAPI, status app = FastAPI() @app.post("/items", status_code=[1]) def create_item(): return {"message": "Item created"}
The status_code parameter sets the HTTP status code returned by the endpoint. status.HTTP_201_CREATED means the item was successfully created.
Complete the code to raise a 404 error when an item is not found.
from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/items/{item_id}") def read_item(item_id: int): if item_id != 1: raise HTTPException(status_code=[1], detail="Item not found") return {"item_id": item_id}
Raising HTTPException with status code 404 indicates the requested item was not found.
Fix the error in the code to correctly return a 204 No Content response.
from fastapi import FastAPI, Response, status app = FastAPI() @app.delete("/items/{item_id}") def delete_item(item_id: int): # Delete logic here return Response(status_code=[1])
Status code 204 means the request was successful but there is no content to return. Using Response with status_code=204 is correct.
Fill both blanks to return a JSON response with a 202 Accepted status code.
from fastapi import FastAPI, JSONResponse, status app = FastAPI() @app.post("/process") def process_data(): return JSONResponse(content=[1], status_code=[2])
The content should be a JSON object with a message, and the status_code should be 202 to indicate the request was accepted for processing.
Fill all three blanks to return a custom status code and message in a FastAPI endpoint.
from fastapi import FastAPI, Response app = FastAPI() @app.put("/update/{item_id}") def update_item(item_id: int): # Update logic here return Response(content=[1], media_type=[2], status_code=[3])
The content is a plain text message, media_type is set to text/plain, and the status code 202 means the update was accepted.