HomeToolsAbout a20k

Responses

Default Response

By default, FastAPI will return the responses using JSONResponse

  • automatically convert that return value to JSON using the jsonable_encoder

Custom Response

Returning a Response

Example of returning XML as a custom Response

from fastapi import FastAPI, Response app = FastAPI() @app.get("/legacy/") def get_legacy_data(): data = """<?xml version="1.0"?> <shampoo> <Header> Apply shampoo here. </Header> <Body> You'll have to use soap here. </Body> </shampoo> """ return Response(content=data, media_type="application/xml")

ORJSONResponse

Installation

pip3 install --upgrade orjson

HTTP header Content-Type will be set to application/json

from fastapi import FastAPI from fastapi.responses import ORJSONResponse app = FastAPI() @app.get("/items/", response_class=ORJSONResponse) async def read_items(): return ORJSONResponse([{"item_id": "Foo"}])

HTMLResponse

from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/items/", response_class=HTMLResponse) async def read_items(): return """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """

RedirectResponse

from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/typer") async def redirect_typer(): return RedirectResponse("https://typer.tiangolo.com")

StreamingResponse

from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() async def fake_video_streamer(): for i in range(10): yield b"some fake video bytes" @app.get("/") async def main(): return StreamingResponse(fake_video_streamer()) # Use with file-like objects from fastapi import FastAPI from fastapi.responses import StreamingResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/") def main(): # yield = generator function def iterfile(): # with closes the file-like object after generator function is done with open(some_file_path, mode="rb") as file_like: yield from file_like return StreamingResponse(iterfile(), media_type="video/mp4")
© VincentVanKoh