Quickstart for Microsoft Translator Text API with Python

This article shows you how to use the Translate method to translate text from one language to another. For information on how to use the other Translator Text APIs, see this Github repository.


You will need Python 3.x to run this code.

You must have a Cognitive Services API account with Microsoft Translator Text API. You will need a paid subscription key from your Azure dashboard.

Translate text

The following code translates source text from one language to another, using the Translate method.

  1. Create a new Python project in your favorite IDE.
  2. Add the code provided below.
  3. Replace the key value with an access key valid for your subscription.
  4. Run the program.
# -*- coding: utf-8 -*-

import http.client, urllib.parse

# **********************************************
# *** Update or verify the following values. ***
# **********************************************

# Replace the subscriptionKey string value with your valid subscription key.
subscriptionKey = 'ENTER KEY HERE'

host = 'api.microsofttranslator.com'
path = '/V2/Http.svc/Translate'

target = 'fr-fr'
text = 'Hello'

params = '?to=' + target + '&text=' + urllib.parse.quote (text)

def get_suggestions ():

    headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
    conn = http.client.HTTPSConnection(host)
    conn.request ("GET", path + params, None, headers)
    response = conn.getresponse ()
    return response.read ()

result = get_suggestions ()
print (result.decode("utf-8"))

Translate response

A successful response is returned in XML, as shown in the following example:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Salut</string>

Next steps

See also

Translator Text overview
API Reference