How to make a python request to deepL API?
Asked Answered
A

5

9

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)
Astute answered 13/5, 2020 at 15:52 Comment(0)
S
7

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.

Seafaring answered 5/6, 2021 at 22:34 Comment(0)
H
3

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?'
                          })
Helsie answered 16/11, 2020 at 14:54 Comment(0)
S
1

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

Stantonstanway answered 21/5, 2020 at 13:14 Comment(0)
B
1

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 !"
Berner answered 30/8, 2021 at 15:41 Comment(3)
Good to know, however I get an error while trying to using it. I opened an issue on their Github, I hope they will answer quickly.Tamberg
@Tamberg thanks for sharing, did you get a response from them / is it working for you now?Berner
Yes, the API key I was using is not compatible with the API usage, but only with CAT tool.Tamberg
A
1
import os    
import deepl

def translate_with_deepl(text, target_language, deepl_auth_key):
   '''translate with the (free) deepl api - you have to sign in to get 
   your authentication key'''

   translator = deepl.Translator(deepl_auth_key)
   return translator.translate_text(text, target_lang=target_language)

text = '你好'
target_language = 'EN-GB'
deepl_auth_key = os.environ.get('DEEPL_KEY') #your key in env-variables


print(translate_with_deepl(text, target_language, deepl_auth_key))
# Hello
Absolutely answered 21/10, 2021 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.