Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return plain text in FastAPI

In this example, the entrypoint http://127.0.0.1:8000/ returns formatted text:

"Hello \"World\"!"

The quotes are masked by a slash, and quotes are added both at the beginning and at the end. How to return unformatted text, identical to my string Hello "World"!.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import uvicorn
from fastapi import FastAPI

app = FastAPI()


@app.get("/",)
def read_root():
    return 'Hello "World"!'


uvicorn.run(app)

>Solution :

When you return a string from a FastAPI endpoint, FastAPI will automatically convert it to a JSON response, which is why the quotes are being escaped in your example. JSON strings must escape double quotes with a backslash.

If you want to return unformatted text (plain text) and not JSON, you can do so by using FastAPI’s PlainTextResponse object (docs here).

I’m using FastApi version 0.104 here:

import uvicorn
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()


@app.get(
    "/",
    response_class=PlainTextResponse,
)
def read_root():
    return 'Hello "World"!'


uvicorn.run(app)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading