How to Return HTML Response in FastAPI: Simple Guide
In FastAPI, you can return an HTML response by importing and using
HTMLResponse from fastapi.responses. Return an instance of HTMLResponse with your HTML content as a string to send HTML to the client.Syntax
To return HTML in FastAPI, import HTMLResponse from fastapi.responses. Use it as the response class in your route or return it directly with your HTML string.
Parts explained:
HTMLResponse: A special response class that tells FastAPI to send HTML content.content: Your HTML code as a string.response_class=HTMLResponse: Declares the route will return HTML.
python
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/", response_class=HTMLResponse) def read_root(): return "<html><body><h1>Hello, FastAPI!</h1></body></html>"
Example
This example shows a FastAPI app returning a simple HTML page with a heading and paragraph. The HTMLResponse ensures the browser renders the content as HTML.
python
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/welcome", response_class=HTMLResponse) def welcome(): html_content = """ <html> <head> <title>Welcome Page</title> </head> <body> <h1>Welcome to FastAPI!</h1> <p>This is an HTML response.</p> </body> </html> """ return HTMLResponse(content=html_content)
Output
When you visit /welcome, the browser shows a page with a big heading 'Welcome to FastAPI!' and a paragraph below it.
Common Pitfalls
Common mistakes when returning HTML in FastAPI include:
- Not using
HTMLResponseso the browser treats the response as plain text. - Returning raw HTML string without specifying
response_class=HTMLResponseor wrapping it inHTMLResponse. - Forgetting to import
HTMLResponse.
Wrong way (renders as plain text):
python
from fastapi import FastAPI app = FastAPI() @app.get("/wrong") def wrong(): return "<h1>This will show as plain text, not HTML</h1>"
Common Pitfalls
Right way (renders as HTML):
python
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/right", response_class=HTMLResponse) def right(): return "<h1>This will render as HTML</h1>"
Key Takeaways
Use HTMLResponse from fastapi.responses to send HTML content.
Set response_class=HTMLResponse in your route decorator or return HTMLResponse directly.
Without HTMLResponse, HTML strings are sent as plain text and won't render in browsers.
Always import HTMLResponse to avoid errors.
Returning HTMLResponse lets browsers display your content as a web page.