2

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 "file=@mydoc.docx" \
    -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?

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
  • hmm, since you have to open `mydoc` in read binary, do you need to send the strings as bytes instead? Like for `target_lang` use `b'DE'` instead? – SuperStew Sep 12 '19 at 21:17
  • @SuperStew I tried it, but no use. – Bram Vanroy Sep 13 '19 at 07:55
  • I suggest you to first try converting the request in a tool like postman for example and then you can probably find all the info you need about python multipart request here: https://stackoverflow.com/questions/12385179/how-to-send-a-multipart-form-data-with-requests-in-python – Sébastien B Sep 15 '19 at 11:52
  • Have you tried opening the file for both reading and writing? It looks like the DeepL server encrypts the file after you upload it; not sure how they're doing that but it's possible they're trying to both read from and write to the file. Try `rb+` instead of `rb`. – Kayla Fuchs Sep 15 '19 at 20:25
  • @KaylaFuchs Tried it but no change. – Bram Vanroy Sep 17 '19 at 07:38
  • Hmmm...have you tried various different files, all with the same result? – Kayla Fuchs Sep 18 '19 at 02:32
  • The support team got back to me and provided a solution. See below. – Bram Vanroy Sep 18 '19 at 07:10

1 Answers1

1

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)
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239