3
votes

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
Image files are normally sent as urls... - thebjorn
It sounds like you should start with a basic API 101 tutorial to get familiar with request/response stuff with REST. That might ease your entry in using an API platform like FastAPI - dfundako
Been there, done that. Gets all the prinicples and ideas, but finds it hard to find information on how I can form the response. - Henrik Leijon
First of all, images are received (from server) as URLs. Are you trying to return the URL? @HenrikLeijon - JPG

1 Answers

0
votes

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