I'm making a request:
import request in python:
url = "http://myweb.com/call"
payload = {}
headers = { 'Content-Type': 'application/json', 'Token': '123456789' }
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
and I'm receiving and printing the response as :
{"name":"Peter","LastName":JOHN,"RegDate":"2020-03-25T17:34:42.5306823Z","Number":7755}
but I want the print statement to show only "Name" and "Number" params. Not the whole response should be printed. How do I do this?
Thanks in advance.
Response is a dictionary object, so you want to print two values from that dictionary using the keys for those values:
response_text = response.text.encode('utf8')
print(response_text['name'], response_text['Number'])
edit: the dict is actually deeper within the response object than I originally understood.
You can do this:
import json
response = requests.request("POST", url, headers=headers, data = payload)
response_txt=json.loads(response.text.encode('utf8'))
print(response_txt['name'])
print(response_txt['Number'])
response.text.encode('utf8') produces a string, so you need import the json library and convert that string to an object with json.loads. Then you can access the keys with response_txt['name'] and response_txt['Number'].
Related
url = "url"
headers = CaseInsensitiveDict()
headers["Authorization"] = "Bearer mytoken"
headers["Content-Type"] = "application/json"
profile_id='string'
data = """
{
"browsersIds": [
"{{profile_id}}"
]
}
resp = requests.patch(url, headers=headers, data=data)
the problem is that I cannot assign profile_id variable in the JSON therefore i got 400 bad requests
Remove the content type header.
Use json argument with a dictionary rather than needing to create a template string
profile_id='string'
data = {
"browsersIds": [
profile_id
]
}
resp = requests.patch(url, headers=headers, json=data)
Source=["SGD"]
Destination=["USD"]
Amount=[5000]
```import requests
url = "https://api.currencyfair.com/comparisonQuotes"
payload = "{\"currencyFrom\":\"SGD\",\"currencyTo\":\"EUR\",\"type\":\"SELL\",\"amountInfo\":
{\"amount\":50000,\"scale\":2}}"
headers = {
'user-agent': "vscode-restclient",
'content-type': "application/json",
'accept': "application/json"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
I need to pass values to payload string -
payload = "{"currencyFrom":"SGD","currencyTo":"EUR","type":"SELL","amountInfo":{"amount":50000,"scale":2}}"
Need to pass values to payload using 3 list created above```
Could you please try to explain a bit more what you're after?
I suspect what you mean is that you'd like to dynamically update the values in the text payload every time you call the function to post data.
I'd usually go about doing this by creating a placeholder string then updating that by replacing placeholder values at runtime.
payload = "{\"currencyFrom\":\"#currencyFrom\",\"currencyTo\":\"#currencyTo\",\"type\":\"SELL\",\"amountInfo\": {\"amount\":#amountInfo,\"scale\":2}}"
currencyFrom = 'USD'
currencyTo = 'EUR'
amountInfo = 50000
payload = payload.replace('#currencyFrom', currencyFrom).replace('#currencyTo', currencyTo).replace('#amountInfo', amountInfo)
Looking at the API you're trying to interact with, this is a sample of what it expects:
{"currencyFrom": "EUR",
"currencyTo": "GBP",
"type": "SELL",
"amountInfo": {"amount": 100},
"ignoreFee": false}
This is a JSON object that follows a specific format, if you try and pass a list as opposed to a string in the "currencyFrom", "currencyTo" fields etc you'll get an error.
To get multiple values as responses simply conduct multiple requests to the API, for example:
payload = "{\"currencyFrom\":\"#currencyFrom\",\"currencyTo\":\"#currencyTo\",\"type\":\"SELL\",\"amountInfo\": {\"amount\":#amountInfo,\"scale\":2}}"
currencyFrom = ['USD', 'GBP']
currencyTo = ['EUR', 'CHF']
amountInfo = 50000
payload = payload.replace('#currencyFrom', currencyFrom).replace('#currencyTo', currencyTo).replace('#amountInfo', amountInfo)
for currFrom in currencyFrom:
for currTo in currencyTo:
for amount in amountInfo:
payload = payload.replace('#currencyFrom', currFrom ).replace('#currencyTo', currTo ).replace('#amountInfo', amount )
response = requests.request("POST", url, data=payload, headers=headers)
Hope this makes sense!
Edit: Updating code as per your comments.
I am sending the post request to the TAP PAYMENT GATEWAY in order to save the card, the url is expecting two parameters like one is the source (the recently generated token) and inside the url the {customer_id}, I am trying the string concatenation, but it is showing the error like Invalid JSON request.
views.py:
ifCustomerExits = CustomerIds.objects.filter(email=email)
totalData = ifCustomerExits.count()
if totalData > 1:
for data in ifCustomerExits:
customerId = data.customer_id
print("CUSTOMER_ID CREATED ONE:", customerId)
tokenId = request.session.get('generatedTokenId')
payload = {
"source": tokenId
}
headers = {
'authorization': "Bearer sk_test_**********************",
'content-type': "application/json"
}
# HERE DOWN IS THE url of TAP COMPANY'S API:
url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D"
response = requests.request("POST", url, data=payload, headers=headers)
json_data3 = json.loads(response.text)
card_id = json_data3["id"]
return sponsorParticularPerson(request, sponsorProjectId)
Their expected url = https://api.tap.company/v2/card/{customer_id}
Their documentation link: https://tappayments.api-docs.io/2.0/cards/create-a-card
Try this..
First convert dict. into JSON and send post request with request.post:
import json
...
customerId = str(data.customer_id)
print("CUSTOMER_ID CREATED ONE:", customerId)
tokenId = request.session.get('generatedTokenId')
payload = {
'source': tokenId
}
headers = {
'authorization': "Bearer sk_test_**************************",
'content-type': "application/json"
}
pd = json.dumps(payload)
# HERE DOWN IS THE url of TAP COMPANY'S API:
url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D"
response = requests.post(url, data=pd, headers=headers)
json_data3 = json.loads(response.text)
card_id = json_data3["id"]
return sponsorParticularPerson(request, card_id)
Please tell me this works or not...
In order to extract data from a private API, I need to generate access tokens using my auth key and credentials. My current code is split in two parts. The first generates the access token:
import requests
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
The response looks like this:
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTg0MjEsIm5hbWUiOiJyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk2Mjg1NzcsImlhdCI6MTU3OTYyNDk3OCwiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NjI0OTc4fQ.rEZiMHPsE1inwuWFME1oV_oD54TqkU00-uml3NjCkClW3R-_bVC7A3PxI4zGlJms1rvsZkgO3XX8-1coeV6_jtI-l3nCHixVk2nboepqAspoxT3o9w4vhBhZzvs-TAsqyk4fCrSwwHFXwn8xOMdfrqZqknXHLlVtKlGJg_Uy3bmwEiioocMN3BRZE_269_v5Ez4b94_juUHLPDWye7kS5-8cs4Izsk7HePn-Sm_-FLEqEeb2C09NUGWU8SdyA3EtQhMAiHkU-wN8uQ8wKcWoUfO7WtrSO4zbicFZHgA9Cw",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"pDYllH2UsVIYq3Pn3Dg==",
"scope":"Api",
"resource_server_base_uri":"https://api-c31.it.com/itAPI/",
"refresh_token_server_uri":"https://api-c31.it.com/AuthorizationServer/Token",
"agent_id":162,
"team_id":24355,
"bus_no":4421}'
The access token is part of the output and I paste this into the following code to generate the response:
def getPerformance():
# api-endpoint
#Give the specified url ,accessToken
BASEURL = 'https://api-c31.ict.com/tAPI/'
accessToken = "{eyJ0eXAiOiJKV1QiLCJhbGciSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTgyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk1NjA0MjYsImlhdCI6MTU3OTU1NjgyNywiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NTU2ODI2fQ.JIzsPLK8kg8Zqq_uITeNp6b24xuglcmtjVbD9Ll-ooq943gIILvr_SQ8cTKNl50YMyiX_mu48pupf-D0b-Ntbmb7hYOTNY7tjp8skM8uBDmuSzG1GnVQh3ZotdlofhiEDU9_U4sQsovqdDtXyi5inaoJ95TeBS_YQp_3LSv3pjfXQNWdt1bcn7arHWdIdl6qD5qXm0DhXQArhTr35mViZn-ZxITW4nvEi-gwZz6DdLWuWcW5kTbbzvucroVUPM-dZvzNJvMEruJvriUGl3Y2DSlB5qTLo3JqbLwujsoZfhaxfJ1eAFKd13t6mMenQ5TOwVV3Rg_yp7DfeBbnWcmwtA}"
#Check if accessToken is empty or null
if accessToken != "":
#Give necessary parameters for http request
payload={'startDate':'1/1/2020',
'endDate':'1/6/2020',
'fields':'"teamId","calls"'}
#add all necessary headers
header_param = {'Authorization': 'bearer ' + '{accessToken}','content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json, text/javascript, */*'}
# Make get http request
answer = requests.get(BASEURL + 'services/{version}/g/h' , headers = header_param, params=payload)
#print response appropriately
print (answer)
else: print('error')
My issue is that I need to be able to merge both scripts in order to be able to automate the process.
Try adding the following changes to the first part of your code, then with the access token at the bottom, pass it into the getPerformance() function:
#Added json import here
import json
import requests
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
#Note the changes here
json = response.read()
data = json.loads(json)
accessToken = data['access_token']
Then wherever you call the getPerformanceFunction(), you want to change it to getPerformance(accessToken). You'll need to change the function definition to this too.
Based on #Cutter's response above, making the following changes worked for me:
import requests
import json
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
testresp = response.text
data = json.loads(testresp)
#Change function definition to :
def getPerformance(data):
# api-endpoint
#Give the specified url ,accessToken
# =============================================================================
BASEURL = 'https://api-c31.ict.com/API/'
accessToken = (data["access_token"])
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?
You don't need to explicitly encode it, simply pass your dict to data argument and it will be encoded automatically.
>>> r = requests.post(URL, data = {'key':'value'})
From the official 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)