Search code examples
pythongoogle-colaboratorydeepl

Using variable as data parameter in a POST request with Deepl API


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.


Solution

  • 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"
    })