PythonAPI Request - python

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.

Related

Assign value in json then send it with requests

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)

Pinterest API 'bookmark' always returning the same string and data

I am trying to use pagination the way it is instructed in the Pinterest API Documentation, by passing 'bookmark' as a parameter to the next GET request in order to get the next batch of data.
However, the data returned is the EXACT same as the initial data I had received (without passing 'bookmark') and the value of 'bookmark' is also the same!
With this issue present, I keep receiving the same data over and over and can't get the entirety of the data. In my case I'm trying to list all campaigns.
Here is my python code:
url = f'https://api.pinterest.com/v5/ad_accounts/{ad_account_id}/campaigns'
payload = f"page_size=25"
headers = {
"Accept": "text/plain",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"Bearer {access_token}"
}
response = requests.request("GET", url, data=payload, headers=headers)
print(response)
feed = response.json()
print(feed)
bookmark=''
if 'bookmark' in feed:
bookmark = feed['bookmark']
print(bookmark)
while(bookmark != '' and bookmark != None and bookmark != 'null'):
url = f'https://api.pinterest.com/v5/ad_accounts/{ad_account_id}/{level}s'
payload = f"page_size=25&bookmark={bookmark}"
headers = {
"Accept": "text/plain",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"Bearer {access_token}"
}
response = requests.request("GET", url, data=payload, headers=headers)
print(response)
feed = response.json()
print(feed)
bookmark = feed['bookmark']
print(bookmark)
I think your condition in while is wrong, therefore you end up in the same loop. I'm currently also working with Pinterest API and below is my modified implementation how to get a list of ad accounts.
Basically you're testing if the bookmark is None. If yes, then you can return the result, otherwise you append the bookmark into query parameters and call the endpoint again.
from app.api.http_client import HttpClient
class PinterestAccountsClient():
def get_accounts(self, credentials) -> list[dict]:
headers = {
'Authorization': f"Bearer {credentials('access_token')}"
}
params = {
'page_size': 25
}
accounts = []
found_last_page = False
while not found_last_page:
try:
response = HttpClient.get(self.listing_url, headers=headers, params=params)
items = response.get('items', [])
bookmark = response.get('bookmark')
if bookmark is None:
found_last_page = True
else:
params['bookmark'] = bookmark
accounts.extend([{
'id': account['id'],
'name': account['name']
} for account in items])
return accounts

How to pass the customer id dynamically in the tap payment method to save the card value

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...

Python - print some data from response

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'].

Unexpected token END OF FILE at position 0 on Python POST request to Firebase

I am trying to send a message via Firebase to a certain client. This is my current (test) code:
import json
import requests
import urllib
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
payload = json.dumps(payload)
res = requests.post(server, headers=headers, json=payload)
return res
which produces the following error, returned by Firebase:
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.
The following JSON sent to Firebase seems correct to me:
{
"data": {
"type":"dataUpdate"
},
"to":"xxx"
}
which is in the format described by the Firebase documentation. Any idea why Firebase doesn't accept the given data?
When you use json=payload as a parameter to requests.post() you don't need to specify 'Content-Type': 'application/json' in the header. In addition, you are passing a string when the parameter should be payload as a dict (ie. no need for json.dumps())
Try this:
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
res = requests.post(server, headers=headers, json=payload)
return res

Categories