Search code examples
curlpostpython-requestsdeepl

requests equivalent to cURL returning error


I am trying to use the DeepL API. In the documentation they speak of a cURL command like so:

curl https://api.deepl.com/v2/document \
    -F "[email protected]" \
    -F "auth_key=<your-api-key>" \
    -F "target_lang=DE"

which I converted to requests like so.

import requests

files = {
    'file': ('mydoc.docx', open('mydoc.docx', 'rb')),
    'auth_key': (None, '<your-api-key>'),
    'target_lang': (None, 'DE'),
}

response = requests.post('https://api.deepl.com/v2/document', files=files)

Strangely enough, the cURL command does work from the command line, but I can't get the Python code to work. The server keeps returning the following data:

{'message': 'Invalid file data.'}

The documentation explicitly states

Because the request includes a file upload, it must be an HTTP POST request containing multipart/form-data.

But as far as I know, the above is the correct way to do this. What am I doing wrong?


Solution

  • The DeepL support team got back to me, and the solution was to specify the data type to the file (in my case text/plain). So the request should look like this:

    import requests
    
    files = {
        'file': ('mydoc.docx', open('mydoc.docx', 'rb'), 'text/plain'),
        'auth_key': (None, '<your-api-key>'),
        'target_lang': (None, 'DE')
    }
    
    response = requests.post('https://api.deepl.com/v2/document', files=files)