kwn kwn - 1 month ago 16
Python Question

Issue while sending a file to an API

I'm trying to send a file to an API and then get the response - a CSV file
(I've seen different posts about it but I couldn't make it work)

The examples in the documentation use httpie

http --timeout 600 -f POST http://api-adresse.data.gouv.fr/search/csv/ data@path/to/file.csv


but when I'm using requests, I get an
400 Bad Request


path = '/myfile.csv'
url = 'http://api-adresse.data.gouv.fr/search/csv/'
files = {'file': open(path, 'rb')}
res = requests.post(url, data=files)

Answer

You need to specify files keyword argument, not data to post multipart/form-data request.

And the key should match: file -> data

path = 'path/to/file.csv'
url = 'http://api-adresse.data.gouv.fr/search/csv/'
files = {'data': open(path, 'rb')}
#        ^^^^^^
res = requests.post(url, files=files)
#                        ^^^^^