Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python request to deepL API?

I'm trying to make a python script for making translations with the DeepL API. I've tried to make a request but it responses a HTTP error 400 (Bad request).

Here is the code of my script where I replaced the real authentication key with XXX:

import requests

url = "https://api.deepl.com"

auth_key = {
    'host' : "https://api.deepl.com/v2/translate?",
    'auth_key':"auth_key=XXX"
}

querystring = {
    "text" : "Che bellissima giornata",
    "target_lang" : "en"
}

response = requests.request("POST", url, headers=auth_key, data=querystring)

print(response)
print(response.text)
like image 928
Luca Guidotto Avatar asked May 13 '20 15:05

Luca Guidotto


4 Answers

EDIT: DeepL Python Library

I was unaware of this before, but DeepL has a python package that can be used to make text and document translations far more easily than through the requests package. Some of this is recycled from the DeepL documentation, but updated to answer your question.

First, run a simple pip install deepl.

If you don't care about hard coding your auth_key, you can set it up like so:

import deepl

translator = deepl.Translator("auth_key")

To translate a single string you can do this:

import deepl

result = translator.translate_text("Che bellissima giornata", target_lang="EN-US")
print(result)

You can now also pass multiple strings in a DeepL request by putting the strings in a list:

import deepl

result = translator.translate_text(["お元気ですか?", "Che bellissima giornata"], target_lang="EN-US")
print(result[0].text)  # "How are you?"
print(result[0].detected_source_lang)  # "JA"
print(result[1].text)  # "What a beautiful day"
print(result[1].detected_source_lang)  # "IT"

If you have full foreign language documents you would like to translate you can make a request using the DeepL package as well:

translator.translate_document_from_filepath(
    "path/to/write/to/WhatABeautifulDay.docx", # Translated File
    "path/to/original/CheBellissimaGiornata.docx", # Original File
    target_lang="EN-US"
)

Just as a side note, the DeepL "EN" option is deprecated, and you must now use "EN-US" or "EN-GB" in your request.


OUTDATED (Still Works for Text)

In order to get a correct response, you need to structure your query as such:

import requests
r = requests.post(
                url="https://api.deepl.com/v2/translate",
                data={
                    "target_lang": "EN",
                    "auth_key": auth_key,
                    "text": string_to_translate,
                },
            )

Where auth_key is your authentication key and string_to_translate is the text you want to translate.

I formatted the above code using black, which is why it looks different than what dwightkschruteIII included, though it is essentially doing the same thing.

To access this translation using python, however, you need to use the following code:

r.json()["translations"][0]["text"]

Because DeepL will return a json with translations as its only key, with a list containing another json as the corresponding value. The json within the list has two keys: detected_source_language and text. This was a verbose explanation, so I've provided a sample below:

The commands:

sample = requests.post(url="https://api.deepl.com/v2/translate", data={"target_lang": "EN", "auth_key": auth_key, "text": "Che bellissima giornata"})

print(sample.json())

Return:

{'translations': [{'detected_source_language': 'IT', 'text': 'What a beautiful day'}]}

So to reiterate, you must use sample.json()["translations"][0]["text"] to access the translation, where sample is whatever you named your response, and the first code block to get a successful request.

like image 149
Thomas-C Avatar answered Oct 05 '22 10:10

Thomas-C


In some cases it is necessary to write a POST request, then you should proceed as follows (also from the DeepL FAQs):

How can I avoid error 414, "Request-URI Too Long"? This error occurs if the API URLs are too long and is due to a length limit of the web server. You can avoid this error message by using a POST request instead of a GET request.

Therefore you can use the requests package as follows:

import requests

r =  requests.post(url='https://api.deepl.com/v2/translate',
                          data = {
                            'target_lang' : 'EN',  
                            'auth_key' : 'XXXXXXXXXXXXXXXXXXXX',
                            'text': 'Was ist denn los hier?'
                          })
like image 30
dwightkschruteIII Avatar answered Oct 05 '22 12:10

dwightkschruteIII


You should add the credentials, text and target_lang as parameters to the url, like:

https://api.deepl.com/v2/translate?auth_key=&text=Che%20bellissima%20giornata&source_lang=IT&target_lang=EN

DeepL provides a tool for creating example requests: See How can I create URL examples for API requests? on https://www.deepl.com/pro-faq.html

like image 31
clemens Avatar answered Oct 05 '22 12:10

clemens


As of August 2021, DeepL also offers an open source Python client library for its API: https://github.com/DeepLcom/deepl-python.

Below is an example request from the README. You'll need to pip install --upgrade deepl first (here's the project in PyPI: https://pypi.org/project/deepl/).

import deepl

# Create a Translator object providing your DeepL API authentication key
translator = deepl.Translator("YOUR_AUTH_KEY")

# Translate text into a target language, in this case, French
result = translator.translate_text("Hello, world!", target_lang="FR")
print(result) # "Bonjour, le monde !"
like image 43
speaksgermansortof Avatar answered Oct 05 '22 12:10

speaksgermansortof