Sobes.tech
Junior — Middle

What types of responses can be returned from an API implemented with FastAPI?

sobes.tech AI

Answer from AI

FastAPI allows returning various types of responses from an API:

  • Standard Python objects — dictionaries, lists, Pydantic models. FastAPI automatically serializes them into JSON.

  • Response objects — for example, JSONResponse, HTMLResponse, PlainTextResponse for explicitly specifying the response type and content.

  • HTTP status codes — you can return tuples like (data, status_code), for example, (data, 201).

  • Pydantic models — for data validation and serialization.

  • Files — using FileResponse to return files.

  • HTTPException exceptions — for returning errors with a code and message.

Example:

from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 0:
        raise HTTPException(status_code=404, detail="Item not found")
    return JSONResponse(content={"item_id": item_id, "name": "Item Name"}, status_code=200)

Thus, FastAPI flexibly handles various response types, simplifying API development.