Custom Response - HTML, Stream, File, others

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

By default, FastAPI will return the responses using JSONResponse.

You can override it by returning a Response directly as seen in Return a Response directly.

But if you return a Response directly, the data won’t be automatically converted, and the documentation won’t be automatically generated (for example, including the specific “media type”, in the HTTP header Content-Type as part of the generated OpenAPI).

But you can also declare the Response that you want to be used, in the path operation decorator.

The contents that you return from your path operation function will be put inside of that Response.

And if that Response has a JSON media type (application/json), like is the case with the JSONResponse and UJSONResponse, the data you return will be automatically converted (and filtered) with any Pydantic response_model that you declared in the path operation decorator.

Note

If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.

Use ORJSONResponse

For example, if you are squeezing performance, you can install and use orjson and set the response to be ORJSONResponse.

Import the Response class (sub-class) you want to use and declare it in the path operation decorator.

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

Info

The parameter response_class will also be used to define the “media type” of the response.

In this case, the HTTP header Content-Type will be set to application/json.

And it will be documented as such in OpenAPI.

Tip

The ORJSONResponse is currently only available in FastAPI, not in Starlette.

HTML Response

To return a response with HTML directly from FastAPI, use HTMLResponse.

  • Import HTMLResponse.
  • Pass HTMLResponse as the parameter content_type of your path operation.
  1. from fastapi import FastAPI
  2. from fastapi.responses import HTMLResponse
  3. app = FastAPI()
  4. @app.get("/items/", response_class=HTMLResponse)
  5. async def read_items():
  6. return """
  7. <html>
  8. <head>
  9. <title>Some HTML in here</title>
  10. </head>
  11. <body>
  12. <h1>Look ma! HTML!</h1>
  13. </body>
  14. </html>
  15. """

Info

The parameter response_class will also be used to define the “media type” of the response.

In this case, the HTTP header Content-Type will be set to text/html.

And it will be documented as such in OpenAPI.

Return a Response

As seen in Return a Response directly, you can also override the response directly in your path operation, by returning it.

The same example from above, returning an HTMLResponse, could look like:

  1. from fastapi import FastAPI
  2. from fastapi.responses import HTMLResponse
  3. app = FastAPI()
  4. @app.get("/items/")
  5. async def read_items():
  6. html_content = """
  7. <html>
  8. <head>
  9. <title>Some HTML in here</title>
  10. </head>
  11. <body>
  12. <h1>Look ma! HTML!</h1>
  13. </body>
  14. </html>
  15. """
  16. return HTMLResponse(content=html_content, status_code=200)

Warning

A Response returned directly by your path operation function won’t be documented in OpenAPI (for example, the Content-Type won’t be documented) and won’t be visible in the automatic interactive docs.

Info

Of course, the actual Content-Type header, status code, etc, will come from the Response object your returned.

Document in OpenAPI and override Response

If you want to override the response from inside of the function but at the same time document the “media type” in OpenAPI, you can use the response_class parameter AND return a Response object.

The response_class will then be used only to document the OpenAPI path operation, but your Response will be used as is.

Return an HTMLResponse directly

For example, it could be something like:

  1. from fastapi import FastAPI
  2. from fastapi.responses import HTMLResponse
  3. app = FastAPI()
  4. def generate_html_response():
  5. html_content = """
  6. <html>
  7. <head>
  8. <title>Some HTML in here</title>
  9. </head>
  10. <body>
  11. <h1>Look ma! HTML!</h1>
  12. </body>
  13. </html>
  14. """
  15. return HTMLResponse(content=html_content, status_code=200)
  16. @app.get("/items/", response_class=HTMLResponse)
  17. async def read_items():
  18. return generate_html_response()

In this example, the function generate_html_response() already generates and returns a Response instead of returning the HTML in a str.

By returning the result of calling generate_html_response(), you are already returning a Response that will override the default FastAPI behavior.

But as you passed the HTMLResponse in the response_class too, FastAPI will know how to document it in OpenAPI and the interactive docs as HTML with text/html:

Custom Response - HTML, Stream, File, others - 图1

Available responses

Here are some of the available responses.

Have in mind that you can use Response to return anything else, or even create a custom sub-class.

Technical Details

You could also use from starlette.responses import HTMLResponse.

FastAPI provides the same starlette.responses as fastapi.responses just as a convenience for you, the developer. But most of the available responses come directly from Starlette.

Response

The main Response class, all the other responses inherit from it.

You can return it directly.

It accepts the following parameters:

  • content - A str or bytes.
  • status_code - An int HTTP status code.
  • headers - A dict of strings.
  • media_type - A str giving the media type. E.g. "text/html".

FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types.

  1. from fastapi import FastAPI, Response
  2. app = FastAPI()
  3. @app.get("/legacy/")
  4. def get_legacy_data():
  5. data = """<?xml version="1.0"?>
  6. <shampoo>
  7. <Header>
  8. Apply shampoo here.
  9. </Header>
  10. <Body>
  11. You'll have to use soap here.
  12. </Body>
  13. </shampoo>
  14. """
  15. return Response(content=data, media_type="application/xml")

HTMLResponse

Takes some text or bytes and returns an HTML response, as you read above.

PlainTextResponse

Takes some text or bytes and returns an plain text response.

  1. from fastapi import FastAPI
  2. from fastapi.responses import PlainTextResponse
  3. app = FastAPI()
  4. @app.get("/", response_class=PlainTextResponse)
  5. async def main():
  6. return "Hello World"

JSONResponse

Takes some data and returns an application/json encoded response.

This is the default response used in FastAPI, as you read above.

ORJSONResponse

A fast alternative JSON response using orjson, as you read above.

UJSONResponse

An alternative JSON response using ujson.

Warning

ujson is less careful than Python’s built-in implementation in how it handles some edge-cases.

  1. from fastapi import FastAPI
  2. from fastapi.responses import UJSONResponse
  3. app = FastAPI()
  4. @app.get("/items/", response_class=UJSONResponse)
  5. async def read_items():
  6. return [{"item_id": "Foo"}]

Tip

It’s possible that ORJSONResponse might be a faster alternative.

RedirectResponse

Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default.

  1. from fastapi import FastAPI
  2. from fastapi.responses import RedirectResponse
  3. app = FastAPI()
  4. @app.get("/typer")
  5. async def read_typer():
  6. return RedirectResponse("https://typer.tiangolo.com")

StreamingResponse

Takes an async generator or a normal generator/iterator and streams the response body.

  1. from fastapi import FastAPI
  2. from fastapi.responses import StreamingResponse
  3. app = FastAPI()
  4. async def fake_video_streamer():
  5. for i in range(10):
  6. yield b"some fake video bytes"
  7. @app.get("/")
  8. async def main():
  9. return StreamingResponse(fake_video_streamer())

Using StreamingResponse with file-like objects

If you have a file-like object (e.g. the object returned by open()), you can return it in a StreamingResponse.

This includes many libraries to interact with cloud storage, video processing, and others.

  1. from fastapi import FastAPI
  2. from fastapi.responses import StreamingResponse
  3. some_file_path = "large-video-file.mp4"
  4. app = FastAPI()
  5. @app.get("/")
  6. def main():
  7. file_like = open(some_file_path, mode="rb")
  8. return StreamingResponse(file_like, media_type="video/mp4")

Tip

Notice that here as we are using standard open() that doesn’t support async and await, we declare the path operation with normal def.

FileResponse

Asynchronously streams a file as the response.

Takes a different set of arguments to instantiate than the other response types:

  • path - The filepath to the file to stream.
  • headers - Any custom headers to include, as a dictionary.
  • media_type - A string giving the media type. If unset, the filename or path will be used to infer a media type.
  • filename - If set, this will be included in the response Content-Disposition.

File responses will include appropriate Content-Length, Last-Modified and ETag headers.

  1. from fastapi import FastAPI
  2. from fastapi.responses import FileResponse
  3. some_file_path = "large-video-file.mp4"
  4. app = FastAPI()
  5. @app.get("/")
  6. async def main():
  7. return FileResponse(some_file_path)

Default response class

When creating a FastAPI class instance or an APIRouter you can specify which response class to use by default.

The parameter that defines this is default_response_class.

In the example below, FastAPI will use ORJSONResponse by default, in all path operations, instead of JSONResponse.

  1. from fastapi import FastAPI
  2. from fastapi.responses import ORJSONResponse
  3. app = FastAPI(default_response_class=ORJSONResponse)
  4. @app.get("/items/")
  5. async def read_items():
  6. return [{"item_id": "Foo"}]

Tip

You can still override response_class in path operations as before.

Additional documentation

You can also declare the media type and many other details in OpenAPI using responses: Additional Responses in OpenAPI.