import requests
import json
from getpass import getpass as get_api_key
'''
For documentation on how this request must be structured and
what the response will look like, see
funtranslations.com/api/yoda
'''
apikey = get_api_key(prompt='Enter your API key')
url = 'http://api.funtranslations.com/translate/yoda.json'
english_text = raw_input('Enter the text you want yoda-fied:\n')
response = requests.get(url, params={'text': english_text}, headers={'X-FunTranslations-Api-Secret': apikey})
'''
Here's the example JSON response that is document at the URL
funtranslations.com/api/yoda
{
"success": {
"total": 1
},
"contents": {
"translated": "Lost a planet, master obiwan has. ",
"text": "Master Obiwan has lost a planet.",
"translation": "yoda"
}
}
'''
decodedResponse = json.loads(response.content)
successIndicator = decodedResponse['success']
numberSuccessful = successIndicator['total']
if numberSuccessful != 1:
print "Unable to successfully translate", english, "to yoda"
else:
contents = decodedResponse['contents']
print 'The translation of', contents['text'], 'is ' + '"' + contents['translated'] + '"'