'How to use variable's value as HTTP POST parameter?
I am trying to send HTTP post request to an API, but instead of using preset text values as POST data, I am trying to use the variables, but can't seems to figure out how to do this?
This is the code:
url1 = "https://example.com/api/req"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = """
{
"type": "Direction",
"station": "Dept",
"status": "check",
"values": {
"Par1": "5",
"Par2" : "2",
"Par3": "3",
"Par4": "1",
"Par5": "4"
}
}
"""
resp1 = requests.post(url1, headers=headers, data=data)
So Instead of using the something like "type": "Direction"
I am trying to use "type": Variable_1
.
How can one achieve this?
Solution 1:[1]
You can use an f-string (as long as you are using Python 3.7+).
url1 = "https://example.com/api/req"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
Variable_1 = "Direction"
data = f"""
{{
"type": "{Variable_1}",
"station": "Dept",
"status": "check",
"values": {{
"Par1": "5",
"Par2" : "2",
"Par3": "3",
"Par4": "1",
"Par5": "4"
}}
}}
"""
resp1 = requests.post(url1, headers=headers, data=data)
Solution 2:[2]
As @CaiAllin points out, you can just pass requests a Python dictionary like this:
import json
import requests
from requests.structures import CaseInsensitiveDict
url1 = "https://example.com/api/req"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
type_ = "Direction"
station = "Dept"
status = "check"
values = {
"Par1": "5",
"Par2": "2",
"Par3": "3",
"Par4": "1",
"Par5": "4",
}
data = {
"type": type_,
"station": station,
"status": status,
"values": values,
}
resp1 = requests.post(url1, headers=headers, data=json.dumps(data))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark |
Solution 2 |