API GET request fails with custom headers - python

I have this API GET request that works fine with the full address:
# Transactions
transaction_url = "https://api.whale-alert.io/v1/transaction/ethereum/0015286d8642f0e0553b7fefa1c168787ae71173cbf82ec2f2a1b2e0ffee72b2"
transaction_querystring = {
"api_key":"APIKEY"
}
transaction_response = requests.request("GET", transaction_url, params=transaction_querystring)
print(transaction_response)
print(transaction_response.text)
but, when I try to pass the variables as headers:
# Transactions
transaction_url = "https://api.whale-alert.io/v1/transaction"
transaction_querystring = {
"api_key":"APIKEY"
}
transaction_headers = {
'blockchain': "ethereum",
'hash': "0015286d8642f0e0553b7fefa1c168787ae71173cbf82ec2f2a1b2e0ffee72b2"
}
transaction_response = requests.request("GET", transaction_url, headers=transaction_headers, data=transaction_querystring, )
print(transaction_response)
print(transaction_response.text)
It won't work:
<Response [404]
Not Found

made it work with {0}".format(startime_unix)

Related

Facebook Graph API | Request [400] Errorr

I create a bot to monitor the comment if there is any new comment and if so it will automatically private_replies them But instead i got a Request [400] Error instead.
def monitor_comment():
print("Bot is monitoring comments")
time.sleep(5)
comment_data = graph.get_connections(COMBINED_POST_ID_TO_MONITOR,"comments",order='reverse_chronological')
commends = []
for comment in comment_data['data'][:10]:
commends.append (comment)
data = commends[0]['id']
data_converted = str(data)
#time.sleep(5)
print(data)
return data_converted
def private_reply(comment_ids):
url = "https://graph.facebook.com/v12.0/me/messages?"
access = {"access_token":Page_Token}
params = {
"recipient": {
"comment_id": comment_ids
},
"message": {
"text":"Testing Private_Replies"
}
request = requests.post(url=url, files=access, json=params)
print(request)
This is the logs
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500,"fbtrace_id":"AMCiqy1Aw8CyODPlUBE1b98"}}

New Twitch API getting json data Python 3

I am trying to get a python script to say whether a twitch channel is live but haven't been able to do it, any and all help would be appreciated.
here are the docs I've been able to find
https://dev.twitch.tv/docs/api/guide
This is what I have atm but I keep on getting "'set' object has no attribute 'items'". This is modified code from "Is There Any Way To Check if a Twitch Stream Is Live Using Python?" however it is now outdated because of the new API.
import requests
def checkUser():
API_HEADERS = {
'Client-ID : [client id here from dev portal]',
'Accept : application/vnd.twitchtv.v5+json',
}
url = "https://api.twitch.tv/helix/streams/[streamer here]"
req = requests.Session().get(url, headers=API_HEADERS)
jsondata = req.json()
print(jsondata)
checkUser()
The answer to your problem of "'set' object has no attribute 'items'" is just a simple typo. It should be
API_HEADERS = {
'Client-ID' : '[client id here from dev portal]',
'Accept' : 'application/vnd.twitchtv.v5+json'
}
Notice how the Colon's aren't part of the text now
And to answer your overarching question of how to tell if a channel is online you can look at this sample code I made.
import requests
URL = 'https://api.twitch.tv/helix/streams?user_login=[Channel_Name_Here]'
authURL = 'https://id.twitch.tv/oauth2/token'
Client_ID = [Your_client_ID]
Secret = [Your Client_Secret]
AutParams = {'client_id': Client_ID,
'client_secret': Secret,
'grant_type': 'client_credentials'
}
def Check():
AutCall = requests.post(url=authURL, params=AutParams)
access_token = AutCall.json()['access_token']
head = {
'Client-ID' : Client_ID,
'Authorization' : "Bearer " + access_token
}
r = requests.get(URL, headers = head).json()['data']
if r:
r = r[0]
if r['type'] == 'live':
return True
else:
return False
else:
return False
print(Check())

Form Input (Array) as PUT request in Python

I'm trying to replicate a PUT request using Python3. The Form Data I need to send looks like this in Firefox:
And like this in Chrome:
I've tried the following:
explanation_data = user_a1.put(
f"/review/{card_id}/verify", f"answerIds%5B%5D={answer1_id}&answerIds%5B%5D={answer2_id}"
)
explanation_data = user_a1.put(
f"/review/{card_id}/verify", {
"answerIds":[answer1_id],
"answerIds":[answer2_id]
}
)
explanation_data = user_a1.put(
f"/review/{card_id}/verify", {
"answerIds":[answer1_id,answer2_id]
}
)
explanation_data = user_a1.put(
f"/review/{card_id}/verify", {
"answerIds":[answer1_id],
"answerIds":[answer2_id]
}
)
And other permutations, to no avail. When the question has a single answer (like below):
Then the following code functions perfectly:
explanation_data = user_a1.put(
f"/review/{card_id}/verify", {
"answerIds":[answer2_id]
}
)
I'm sure it's something very obvious. Where am I going wrong?
With requests==2.6.2, below is the sample python code to make PUT request with your desire URL.
import requests
headers = {'Content-Type': 'application/json'}
url = "http://localhost:5000"
params = (
('answerIds', ['1234', '5678']),
)
req = requests.put(url, params=params, headers=headers)
print req.status
When I am printing URL for above request server side. Below is the output.
http://localhost:5000/?answerIds=1234&answerIds=5678
Hope this helps.

How to write a python loop to change a value for a dictionary key in API request?

I am writing an API request that gives paginated results.
To get results from the next page I need to take a value of 'next_page_cursor' and put it in the parameters of my request that is a dictionary.
This is what I have tried so far. Need to keep changing cursor value in params until there are no more pages.
params = {'title': 'Cybertruck',
'per_page':100,
'cursor': '*'
}
response = requests.get("https://api.aylien.com/news/stories",
headers = headers, params=params).json()
if "next_page_cursor" in response:
cursor = response["next_page_cursor"]
You can use a while loop:
params = {
"title": "Cybertruck",
"per_page": 100,
"cursor": "initial_cursor"
}
def make_request(params)
return requests.get("https://api.aylien.com/news/stories",
headers=headers, params=params).json()
result = []
response = make_request(params)
while "next_page_cursor" in response:
params["cursor"] = response["next_page_cursor"]
response = make_request(params)
result.append(response["information_your_are_interested_in"])

How do we download Amazon Advertising Api reports?

I am working on a sandbox environment and I am trying to download the report based on the https://advertising.amazon.com/API/docs/v2/reference/reports
The issue is that the report which is downloaded is empty. Doesn't contain any data inside. How do we download the report from amazon advertising api?
I follow this steps as described: https://gist.github.com/dbrent-amazon/ca396a63c1670ee0ec83aad26b0ce55b
here's a script that works for me using python and requests, make sure to:
create a campaign, adGroupd and keywords
create reports with the right metrics
make sure you have actual data to view in the report
make sure reportDate is correct
import requests
version = 'v2'
advertise = 'sp'
headers = {
"Authorization": f"Bearer {token.access}",
"Amazon-Advertising-API-ClientId": AmazonSecurityProfile.ClientID,
"Content-Type": "application/json",
}
class urls:
class api:
test = 'https://advertising-api-test.amazon.com'
# create report
recordType = "keywords"
r = requests.post(
f'{urls.api.test}/{version}/{advertise}/{recordType}/report',
json={
# "campaignType": "sponsoredProducts",
"segment": "query",
"reportDate": '20201025', #YYYYMMDD
"metrics": ",".join([
"campaignName",
"campaignId",
"campaignStatus",
"campaignBudget",
"clicks",
"cost",
"attributedConversions1d",
"attributedConversions7d",
"attributedConversions1dSameSKU",
"attributedConversions7dSameSKU",
"attributedUnitsOrdered1d",
"attributedUnitsOrdered7d",
"attributedSales1d",
"attributedSales7d",
"attributedSales1dSameSKU",
"attributedSales7dSameSKU",
"attributedUnitsOrdered1dSameSKU",
"attributedUnitsOrdered7dSameSKU",
"adGroupName",
"adGroupId",
"keywordText",
"keywordId",
"matchType",
"impressions",
]),
},
headers=headers,
)
r.raise_for_status()
r = r.json()
print(r)
reportId = r["reportId"]
while r['status'] == 'IN_PROGRESS':
r = requests.get(
f'{urls.api.test}/{version}/reports/{reportId}',
headers=headers,
)
r = r.json()
print(r)
assert r['status'] == 'SUCCESS'
r = requests.get(
r["location"],
headers=headers,
)
print(r)

Categories

Resources