Python / FastAPI Interview Questions
How do you control HTTP status codes and return custom responses in FastAPI?
FastAPI lets you set the default response status code on the decorator, raise HTTPException for errors, and return Response subclasses for full control over headers and body.
from fastapi import FastAPI, HTTPException, status
from fastapi.responses import JSONResponse, Response, FileResponse
app = FastAPI()
fake_db = {1: {"name": "Foo"}, 2: {"name": "Bar"}}
# Set default success status code
@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(name: str):
return {"name": name}
# Raise HTTP errors
@app.get("/items/{item_id}")
def get_item(item_id: int):
if item_id not in fake_db:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Item {item_id} not found",
headers={"X-Error": "Item missing"}, # custom header on error
)
return fake_db[item_id]
# Custom JSONResponse for full control
@app.get("/custom")
def custom_response():
return JSONResponse(
status_code=200,
content={"message": "ok"},
headers={"X-Custom": "value"},
)
# 204 No Content (no response body)
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int):
fake_db.pop(item_id, None)
return Response(status_code=204)| Constant | Value | Meaning |
|---|---|---|
| HTTP_200_OK | 200 | Success |
| HTTP_201_CREATED | 201 | Resource created |
| HTTP_204_NO_CONTENT | 204 | Success, no body |
| HTTP_400_BAD_REQUEST | 400 | Client error |
| HTTP_401_UNAUTHORIZED | 401 | Not authenticated |
| HTTP_403_FORBIDDEN | 403 | Authenticated but not authorised |
| HTTP_404_NOT_FOUND | 404 | Resource not found |
| HTTP_422_UNPROCESSABLE_ENTITY | 422 | Validation error |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
