I'm trying to deploy my production ready code to Heroku to test it. Unfortunately, it is not taking JSON data so we converted into x-www-form-urlencoded.
params = urllib.parse.quote_plus(json.dumps({
'grant_type': 'X',
'username': 'Y',
'password': 'Z'
}))
r = requests.post(URL, data=params)
print(params)
It is showing an error in this line as I guess data=params
is not in proper format.
Is there any way to POST the urlencoded parameters to an API?
To send parameters in URL, write all parameter key:value pairs to a dictionary and send them as params argument to any of the GET, POST, PUT, HEAD, DELETE or OPTIONS request. then https://somewebsite.com/?param1=value1¶m2=value2 would be our final url.
Whenever we call a web API or submit an HTTP form data, we use an encoded URL to encode the query string. In Python, we can URL encode a query string using the urlib. parse module, which further contains a function urlencode() for encoding the query string in URL. The query string is simply a string of key-value pairs.
You'll want to adapt the data you send in the body of your request to the specified URL. Syntax: requests. post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)
The POST method is used to send data mostly through a form to the server for creating or updating data in the server. The requests module provides us with post method which can directly send the data by taking the URL and value of the data parameter.
You don't need to explicitly encode it, simply pass a dict.
>>> r = requests.post(URL, data = {'key':'value'})
From the documentation:
Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made
Set the Content-Type
header to application/x-www-form-urlencoded
.
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
r = requests.post(URL, data=params, headers=headers)
Just to an important thing to note is that for nested json data you will need to convert the nested json object to string.
data = { 'key1': 'value',
'key2': {
'nested_key1': 'nested_value1',
'nested_key2': 123
}
}
The dictionary needs to be transformed in this format
inner_dictionary = {
'nested_key1': 'nested_value1',
'nested_key2': 123
}
data = { 'key1': 'value',
'key2': json.dumps(inner_dictionary)
}
r = requests.post(URL, data = data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With