I am creating a charge and I want from it to take its 'hosted_url' in order to redirect a user from page.
I am trying to extract it from json, but I newbie and don't know how
...
url = "https://api.commerce.coinbase.com/charges"
payload = {
"local_price": {
"amount": 1,
"currency": USDT
},
"name": "Test for fun",
"description": "Project 2",
"pricing_type": "fixed_price"
}
headers = {
"accept": "application/json",
"X-CC-Version": "2018-03-22",
"X-CC-Api-Key" : "**********",
"content-type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
This is a code to make a request to an api in order to create a charge and in JSON Response I get these fields:
{
"data":{
"code": "123DVAS",
"hosted_url": "https://commerce.coinbase.com/charges/123DVAS",
...
}
}
I want somehow to put this message '123DVAS' in variable or to make a redirect like this:
return render(request, 'https://commerce.coinbase.com/charges/123DVAS')
CodePudding user response:
You can do like this:
# Suppose it's your response looks like this
response = {"hosted_url": "https://commerce.coinbase.com/charges/123DVAS"}
id_fecthed = response.get('hosted_url').split('/')[-1]
# You can redner like this
render(request, f'https://commerce.coinbase.com/charges/{id_fecthed}')
# If you sure that always you want to redirect to hosted_url
# Then you can use this
render(request, response.get('hosted_url'))
Edit:
Full code with data read from requests.
import json
response = requests.post(url, json=payload, headers=headers)
data = json.loads(response.text)
hosted_url = data.get("data",{}).get('hosted_url')
if hosted_url:
id_fecthed = hosted_url.split('/')[-1]
return redirect(f'https://commerce.coinbase.com/charges/{id_fecthed}')
else:
print('Host URL not available')