Skip to content
Advertisement

Whatsapp cloud API uploading media get error file type using python

So i’m trying to upload an image to facebook graph API whatsapp media (having a hard time with how they name things) i tried on postman first and successfully get the uploaded media ID, but when i tried this on python with request objects i got error response 400 something like this:

… Param file must be a file with one of the following types: …

This is what i tried

url = f"https://graph.facebook.com/v15.0/{phone_id}/media"
head = {'Authorization': 'Bearer ' + auth_token}
files = {
    'file': open(current+'default.png', 'rb'),
}

upload_media = requests.post(
    url, 
    data={
        'messaging_product' : 'whatsapp', 
        'type': 'image/png',
    },
    files=files,
    headers=head
)

current here is the local path to my file and i checked out there is nothing wrong with the file (i got the binary version of the file, when printing request), i read on other answer in stackoverflow and they said i should not put Content-Type in the headers and let the request object handles this so i follow.

Here is the response i got after printing out upload_media and upload_media.text:

<Response [400]>

{ “error”:{ “message”:”(#100) Param file must be a file with one of the following types: audio/aac, audio/mp4, audio/mpeg, audio/amr, audio/ogg, audio/opus, application/vnd.ms-powerpoint, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/pdf, text/plain, application/vnd.ms-excel, image/jpeg, image/png, image/webp, video/mp4, video/3gpp. Received file of type ”.”, “type”:”OAuthException”, “code”:100, “fbtrace_id”:”let me hide this seems sensitive” } }

i did make sure the file type is image .png (i also tried .jpeg, .pdf same result i think it is the header or maybe the way python request send the file)

Advertisement

Answer

I have found the problems quoting answer from stackoverflow

answer by runejuhl

Requests has changed since some of the previous answers were written. Have a look at this Issue on Github for more details and this comment for an example.

so i changed this

files = {
    'file': open(current+'/default.png', 'rb'),
}

into this

files = {
    'file': ('default.png', open(current+'/default.png', 'rb'), 'image/png', {'Expires': '0'}),
}

It seems the new request object required the format as tupple with the file type like image/png

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement