4
@app.get('/status')
def get_func(request: Request):
  output = 'this output should have a line break'
  return output

Things I've tried:

  • output = this output should \n have a line break
  • output = this output should <br /> have a line break

The text itself is returned and I don't get the line break.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Peter
  • 143
  • 2
  • 11

2 Answers2

6

Use response_class=PlainTextResponse

from fastapi.responses import PlainTextResponse
@app_fastapi.get("/get_log", response_class=PlainTextResponse)
async def get_log():
    return "hello\nbye\n"
Mats Bohlinsson
  • 176
  • 2
  • 5
4

A line break only makes sense if the response is an HTML response (i.e. an HTML page). And a \n does not render properly as new lines or line breaks, you have to use <br> or an HTML template + some CSS styling to preserve line breaks.

FastAPI returns, by default, a JSONResponse type.

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

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

But you can tell it to use an HTMLResponse type using the response_class parameter:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get('/status', response_class=HTMLResponse)
def get_func():
    output = 'this output should <br> have a line break'
    return output

output using plain string + HTMLResponse

Or, for better control, use an actual HTML template. FastAPI supports Jinja2 templates, see section on FastAPI Templates.

proj/templates/output.html

<html>
<head>
</head>
<body>
    <p>This output should have a <br>line break.</p>
    <p>Other stuff: {{ stuff }}</p>
</body>
</html>

proj/main.py

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")

@app.get('/status', response_class=HTMLResponse)
def get_func(request: Request):
    return templates.TemplateResponse("output.html", {"request": request, "stuff": 123})

output using HTML template + HTMLResponse

With HTML templates, you can then use CSS styling to preserve line breaks.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135