0
0
FastAPIframework~5 mins

Multiple response types in FastAPI

Choose your learning style9 modes available
Introduction

Sometimes, your API needs to send different kinds of answers depending on the situation. Using multiple response types lets your app do that clearly and safely.

When your API might return either data or an error message.
When you want to send JSON for success but plain text for errors.
When different clients expect different formats from the same endpoint.
When you want to clearly document all possible responses your API can send.
Syntax
FastAPI
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse, PlainTextResponse

app = FastAPI()

@app.get("/item/{item_id}", responses={
    200: {"content": {"application/json": {}}},
    404: {"content": {"text/plain": {}}}
})
async def read_item(item_id: int):
    if item_id == 1:
        return JSONResponse(content={"item_id": item_id, "name": "Item One"})
    else:
        return PlainTextResponse("Item not found", status_code=404)

Use the responses parameter in the route decorator to declare possible response types.

Return the appropriate response class like JSONResponse or PlainTextResponse inside the function.

Examples
This example returns JSON if success is true, otherwise plain text with an error code.
FastAPI
from fastapi.responses import JSONResponse, PlainTextResponse

@app.get("/status")
async def get_status(success: bool):
    if success:
        return JSONResponse(content={"status": "ok"})
    else:
        return PlainTextResponse("Failed to get status", status_code=400)
This endpoint returns JSON data when ready, or plain text with status 202 if still processing.
FastAPI
@app.get("/data", responses={
    200: {"content": {"application/json": {}}},
    202: {"content": {"text/plain": {}}}
})
async def get_data(ready: bool):
    if ready:
        return {"data": [1, 2, 3]}
    else:
        return PlainTextResponse("Data processing", status_code=202)
Sample Program

This FastAPI app has one endpoint that returns user info as JSON if found, or a plain text error if not.

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

app = FastAPI()

@app.get("/user/{user_id}", responses={
    200: {"content": {"application/json": {}}},
    404: {"content": {"text/plain": {}}}
})
async def get_user(user_id: int):
    users = {1: "Alice", 2: "Bob"}
    if user_id in users:
        return JSONResponse(content={"user_id": user_id, "name": users[user_id]})
    else:
        return PlainTextResponse("User not found", status_code=404)
OutputSuccess
Important Notes

Always specify the responses dict to help API docs show all response types.

Use response classes from fastapi.responses to control content type and status code.

Returning plain dicts defaults to JSON response automatically.

Summary

Multiple response types let your API send different formats based on conditions.

Use responses in the route decorator to declare them.

Return the right response class inside your function to match the declared types.