Skip to main content
HTMLResponse is a response class for returning HTML content. It sets the appropriate text/html content type header.

Import

Class Signature

Constructor Parameters

str | bytes
default:"None"
The HTML content to return. Can be a string or bytes.
int
default:"200"
The HTTP status code for the response.
dict | None
default:"None"
Additional HTTP headers to include in the response.
str | None
default:"None"
Override the default media type. If not provided, uses text/html; charset=utf-8.
BackgroundTask | None
default:"None"
Background task to run after returning the response.

Usage

Using response_class

Specify HTMLResponse as the response class and return HTML as a string:

Direct HTMLResponse

Return an HTMLResponse object directly:

With Custom Headers

Default Response Class

Set HTMLResponse as the default for all endpoints:

Properties

media_type

The media type for HTML responses:
The actual Content-Type header will be text/html; charset=utf-8.

Notes

  • HTML content should be valid HTML markup
  • The charset is automatically set to UTF-8
  • Use this response class when building server-rendered pages or HTML fragments
  • For modern applications, consider using templating engines like Jinja2 with FastAPI