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"!.
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)