0

I am using this script to make a POST request to the Deepl API. In this case the text parameter is passed as a data parameter. I want to pass the text as a variable so I can use it in other scripts, but I can't make the post request if it is not a data parameter.


url = "https://api.deepl.com/v2/translate?auth_key=xxxx-xxxx-xxx-xxxx-xxxxxxxxx"

querystring = {
    "text" = "When we work out how to send large files by email",
    "target_lang" : "es"
}

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

print(response.text)  

Is it possible to make this request using the text as a variable?

As a better example, this text comes from a previous script. If I use the text as a data parameter I cannot use the previous variable that contains the text. If the text comes from a previous variable, I can't use this variable inside the data parameter. For example:

Variable before the script: text = "When we work out how to send large files by email" I want to use this text variable in the POST request.

Folleloide
  • 39
  • 8

1 Answers1

2

I want to use this text variable in the POST request.

I'm confused. Why are you not using this text as a variable in your POST request?

url = "https://api.deepl.com/v2/translate?auth_key=xxxx-xxxx-xxx-xxxx-xxxxxxxxx"

text = "When we work out how to send large files by email"

querystring = {
    "text": text,
    "target_lang": "es"
}

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

print(response.text)

Apart from that - as a matter of principle, don't call a variable querystring when it does not contain a query string. Naming things properly is important.

For the purpose of a POST request, the data you post is data, or a payload, a body:

body = {
    "text": text,
    "target_lang": "es"
}

response = requests.request("POST", url, data=body)

but there's nothing wrong with not even creating a separate variable at all:

response = requests.request("POST", url, data={
    "text": text,
    "target_lang": "es"
})
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Oh Ok. This works perfectly now. Thanks!. I am learning to use python to make calls to different APIs. Sometimes the easiest thing becomes the hardest thing to do. Forgive my ignorance. Thanks also for the notes on how to name the data, I will keep it in mind. I mark this answer as correct. – Folleloide Mar 21 '21 at 12:26
  • @Folleloide It's all good, I wasn't really taunting you. :) It was meant as a gentle nudge, not more. – Tomalak Mar 21 '21 at 13:14
  • ...next up, make a function that takes `(text, target_lang)` as parameters and returns the translation. – Tomalak Mar 21 '21 at 13:17