3

I am trying to write endpoint for image uploading, it will accept just image in base64 format. I have read how to get file from request in FastAPI and implement that in this way:

server side

@router.post("/v1/installation/{some_identifier}/image")
@db.create_connection
async def upload_installation_image(some_identifier: int, data: UploadFile = File(...)):
    ...
    content = await data.read()
    image_uuid = await save_image(installation.uuid, content, data.content_type)
    
    return {"image_uuid": image_uuid}

And its works fine, but in this case I need to send data in this way:

client side

def test_upload_image(...):
    ...
    response = session.post(
            f"/v1/installation/{relink_serial}/image", files={"file": ("test_file_name.png", data, "image/png")}
        )
    ...

But I want to be able to upload image like this:

client side

def test_upload_image(...):
    ...
    response = session.post(
        f"/v1/installation/{installation_uuid}/image", data=data, headers={"content-type": "image/png"}
    )

I have read a lot of articles and other questions, but all of them suggest to use UploadFile and send data as json with file or body parameter. Is this even possible, to load just 1 file like in second test I show?

Vladyslav
  • 2,018
  • 4
  • 18
  • 44
  • Please have a look at [this answer](https://stackoverflow.com/a/70667530/17865804) (see Update section), as well as [this answer](https://stackoverflow.com/a/73443824/17865804). – Chris Sep 27 '22 at 11:54

1 Answers1

1

I have find solution. Instead of using predefined FastAPI types, I can directly get all data from request object, so my code looks like this:

@router.post("/v1/installation/{some_identifier}/image")
@db.create_connection
async def upload_installation_image(some_identifier: int, request: Request):
    ...
    content = await request.body()
    image_uuid = await save_image(installation.uuid, content, content_type)
    
    return {"image_uuid": image_uuid}

Thats exactly what I am looking for, because in my case client app have send to me whole file in body.

Vladyslav
  • 2,018
  • 4
  • 18
  • 44