How should a fastapi response be formatted?

Viewed 3532

I am new to web communication. I use ubuntu and try to learn fastapi. However, I think it is really hard to understand how to format the response that I intend to send back to the client.

What are the rules for the responses that are to be sent back? And if you want to send back a customized answer - for example two image files - how is that encoded?

Thus far, I only managed to get something like this to work:

@app.post("/")
async def post_test():
    print("Bonjour")
    return {"I don't know what options I have to format this response and for example return images :( "}

Please help with this!

1 Answers

If not done already, I encourage you to read the full fastAPI tutorial which is very clear and step by step. Generally speaking a fastAPI app will convert the object returned by your function into a json string in the HTTP response.

You can use pydantic schemas in your responses because pydantic handles the conversion to json for you.

As said in other answers, you can return the url to a file, or you can return the file directly using a starlette FileResponse.

from starlette.responses import FileResponse

@app.get("/my_file")
async def download_file(self):
    return FileResponse(path="my_file.png", filename="my_file", media_type="image/png")
Related