I am trying to create reports with Python on dailymotion but I have error,According to my received error, renponse is empty. I don't get it. I guess, My user coudln't login to dailymotion. Please check error.
{'data': {'askPartnerReportFile': None}, 'errors': [{'message': 'Not authorized to access `askPartnerReportFile` field.', 'path': ['askPartnerReportFile'], 'locations': [{'line': 3, 'column': 9}], **'type': 'not_authorized**'}]}
Traceback (most recent call last):
File "get_reports.py", line 143, in <module>
product='CONTENT',
File "get_reports.py", line 65, in create_report_request
return response.json()['data']['askPartnerReportFile']['reportFile']['reportToken'];
TypeError: 'NoneType' object is not subscriptable
Here is my code;
`
def get_access_token(app_key, app_secret, username, password):
'''
Authenticate on the API in order to get an access token
'''
response = requests.post('https://graphql.api.dailymotion.com/oauth/token', data={
'client_id': app_key,
'client_secret': app_secret,
'username': username,
'password': password,
'grant_type': 'password',
'version': '2'
})
if response.status_code != 200 or not 'access_token' in response.json():
raise Exception('Invalid authentication response')
return response.json()['access_token']
def create_report_request(access_token, dimensions, metrics, start_date, end_date, product, filters = None):
'''
Creating a report request
'''
reportRequest = """
mutation ($input: AskPartnerReportFileInput!) {
askPartnerReportFile(input: $input) {
reportFile {
reportToken
}
}
}
"""
response = requests.post(
'https://graphql.api.dailymotion.com',
json={
'query': reportRequest,
'variables': {
'input': {
'metrics': metrics,
'dimensions': dimensions,
'filters': filters,
'startDate': start_date,
'endDate': end_date,
'product': product,
}
}
},
headers={'Authorization': 'Bearer ' + access_token}
)
print(response.status_code)
if response.status_code != 200 or not 'data' in response.json():
raise Exception('Invalid response')
print(response.json())
return response.json()['data']['askPartnerReportFile']['reportFile']['reportToken'];
def check_report_status(access_token, report_token):
'''
Checking the status of the reporting request
'''
report_request_status_check = """
query PartnerGetReportFile ($reportToken: String!) {
partner {
reportFile(reportToken: $reportToken) {
status
downloadLinks {
edges {
node {
link
}
}
}
}
}
}
"""
response = requests.post(
'https://graphql.api.dailymotion.com',
json={
'query': report_request_status_check,
'variables': {
'reportToken': report_token
}
},
headers={'Authorization': 'Bearer ' + access_token}
)
if response.status_code != 200 or not 'data' in response.json():
raise Exception('Invalid response')
status = response.json()['data']['partner']['reportFile']['status'];
if (status == 'FINISHED'):
download_links = []
for url in map(lambda edge: edge['node']['link'], response.json()['data']['partner']['reportFile']['downloadLinks']['edges']):
download_links.append(url)
return download_links
else:
return None
def download_report(download_links, base_path=None):
'''
Downloading the report files
'''
cpt = 1
if not base_path:
base_path = os.getcwd()
for url in download_links:
r = requests.get(url)
filename = 'report_{}.csv'.format(cpt)
file_path = os.path.join(base_path, filename)
open(file_path, 'wb').write(r.content)
print('Report file {} downloaded: {}'.format(cpt, file_path))
cpt += 1
print('Generating access token...')
access_token = get_access_token(
app_key='******',
app_secret='*******',
username='*****',
password='*****'
)
print('Creating report request...')
report_token = create_report_request(
access_token=access_token,
dimensions=('DAY', 'VIDEO_TITLE'),
metrics=('VIEWS'),
filters={'videoOwnerChannelSlug': 'B******'},
start_date='2022-11-23',
end_date='2022-11-24',
product='CONTENT',
)
download_links = None
while not download_links:
print('Checking report status...')
# Checks every 15secs the report status
time.sleep(15)
download_links = check_report_status(
access_token=access_token,
report_token=report_token
)
download_report(download_links=download_links)
`
I tried to get data dailymotion api.
Thanks
This feature requires a specific API access, which is missing on your API Key, that's why you get the message Not authorized to access askPartnerReportFile field.
As it's a feature restricted to verified-partners, you should reach out to your content manager to ask him this kind of access, or you can try to contact our support
Related
I'm working on python code to send an email from Outlook using Microsoft Graph API. For this, I have created an Enterprise Application in my Azure Active Directory Tenant. I have granted admin consent for the tenant to the application on Mail.Send permission. I'm able to get the access token for Graph API with the help of this application, but I'm not able to send the mail. Can anyone please help me to understand, what is the issue with my code?
Python Code:
from requests import post
CLIENT_SECRET_VALUE = 'CLIENT_SECRET_VALUE'
TENANT_ID = 'TENANT_ID'
CLIENT_ID = 'CLIENT_ID'
LOGIN_URI = f'https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token'
headers = {
'Host': 'login.microsoftonline.com',
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': CLIENT_ID,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': CLIENT_SECRET_VALUE,
'grant_type': 'client_credentials',
'tenant': TENANT_ID
}
response = post(url=LOGIN_URI, headers=headers, data=body)
response.raise_for_status()
response_body = response.json()
authorization_token = f"{response_body['token_type']} {response_body['access_token']}"
print(authorization_token)
email_header = {
'Authorization': authorization_token,
'Content-Type': 'application/json'
}
message = {
'body': {
'content': 'Outlook Mail Testing Demo',
'contentType': 'Text'
},
'sender': {
'emailAddress': {
'address': 'email.address.of.shared.mailbox#active-directory-tenant.tld',
'name': 'Name of Shared Mailbox'
}
},
'subject': 'Testing email',
'toRecipients': [
{
'emailAddress': {
'address': 'temprorary.email.address#another-domain.tld',
'name': 'Name of person to whom email belongs'
}
}
]
}
email_body = {
'message': message
}
email_send_response = post(url='https://graph.microsoft.com/v1.0/users/me/sendMail', headers=email_header, data=email_body)
email_send_response.raise_for_status()
[N.B.: CLIENT_SECRET_VALUE is getting generated by the enterprise application. TENANT_ID & CLIENT_ID are the tenant and client ids assigned to the application]
On running the code, I'm getting an error:
400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/users/me/sendMail
There are two problems in your code. As I specified the first issue in comments that the URL should be as below as you are using client credential flow.
https://graph.microsoft.com/v1.0/users/{userid/UPN}/sendMail
The second problem I have identified after a long research in python is that the body which you are sening with the API call is not in the format of json. So I have used import json and method json.dumps and tested it. Then it worked.
Code:
from requests import post
import json
CLIENT_SECRET_VALUE = 'aX27Q~insds3EvI4z8otRNGHRcCgdjeFOTSpCLPZ'
TENANT_ID = '363147dc-b3be-41a7-af56-f67894ef5a7'
CLIENT_ID = 'e61195e5-7955-4558-9126-37f6cf372d45'
LOGIN_URI = f'https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token'
headers = {
'Host': 'login.microsoftonline.com',
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': CLIENT_ID,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': CLIENT_SECRET_VALUE,
'grant_type': 'client_credentials',
'tenant': TENANT_ID
}
response = post(url=LOGIN_URI, headers=headers, data=body)
response.raise_for_status()
response_body = response.json()
authorization_token = f"{response_body['token_type']} {response_body['access_token']}"
print(authorization_token)
email_header = {
'Authorization': authorization_token,
'Content-Type': 'application/json'
}
message = {
'body': {
'content': 'Outlook Mail Testing Demo',
'contentType': 'Text'
},
'sender': {
'emailAddress': {
'address': 'email.address.of.shared.mailbox#active-directory-tenant.tld',
'name': 'Name of Shared Mailbox'
}
},
'subject': 'Testing email',
'toRecipients': [
{
'emailAddress': {
'address': 'temprorary.email.address#another-domain.tld',
'name': 'Name of person to whom email belongs'
}
}
]
}
email_body = {
'message': message
}
email_send_response = post(url='https://graph.microsoft.com/v1.0/users/1ab4e76f-5f52-44b8-8a72-7d03c05e6ff4/sendMail', headers=email_header, data=json.dumps(email_body))
print(email_send_response)
OUTPUT:
I've been trying to query the Notion API using Python, and as I have more than 100 results, I need to either filter them down or be able to paginate. I tried different variants of the following code to no avail:
headersNotion = {
"Authorization": "Bearer " + notionToken,
"Content-Type": "application/json",
"Notion-Version": "2021-05-13"
}
data = {
"start_cursor" : nextCursor
}
readUrl = f"https://api.notion.com/v1/databases/{databaseId}/query"
res = requests.request("POST", readUrl, data=data, headers=headers)
I've also tried with data = { "filter": {"cover" : "is_empty"} } or even with an idiotic or empty filter, but as soon as I add any sort of data to the request, I get a 400 error:
{"object": "error", "status": 400, "code": "invalid_json", "message": "Error parsing JSON body."}
Would anyone have any idea what I might be doing wrong?
look here headersNotion schould be headers.
https://developers.notion.com/reference/post-database-query
Just as example.
payload = {
'filter': {
'and': [
{
'property': 'aktualisiert am',
'date': {
'after': str(age)
}
},
{
'property': 'aktiv',
'text': {
'equals': 'yes'
}
}
]
}
}
headers = {
"Accept": "application/json",
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Notion-Version": "2021-08-16"
}
def readDatabase(databaseId, headers, payload):
readUrl = f"https://api.notion.com/v1/databases/{databaseId}/query"
res = requests.request("POST", readUrl, json=payload, headers=headers)
datadb = res.json()
print(res.text) #for Debug
# Errors Returns a 404 HTTP response if the database doesn't exist, or if the integration doesn't have access to the database.
# Returns a 400 or a 429 HTTP response if the request exceeds the request limits.
# Returns 200 HTTP responce if OK
#print ('')
print ('')
if res.status_code == 200:
print('200 Success!') # Yes everything OK!
elif res.status_code == 404:
print('404 Not Found.')
#sendmail
subject = " Fehler!! 404 Database Not Found"
send_email(user, password, recipient, subject, body)
return
elif res.status_code == 429:
print(' Fehler !! 429 request exceeds the request limits.')
#sendmail
subject = " Fehler !! 429 request exceeds the request limits."
send_email(user, password, recipient, subject, body)
return
elif res.status_code == 400:
print('400 request exceeds the request limits.')
#sendmail
subject = " Fehler !! 400 request exceeds the request limits. "
send_email(user, password, recipient, subject, body)
return
# print(res.text)
# write csv File
with open('./dbmain.json', 'w', encoding='utf8') as f:
json.dump(datadb, f, ensure_ascii=False)
Looks like I'm doing just about everything correct but I keep receiving this error....
Response text error:
response .text {"name":"INVALID_TRACKING_NUMBER","message":"The requested resource ID was not found","debug_id":"12345","details":[{"field":"tracker_id","value":"1234-567890","location":"path","issue":"INVALID_TRACKING_INFO"}],"links":[]}
Response status: <Response [404]>
I'm using a real transaction and a real tracking number.
I'm doing this through python and this is my code:
def paypal_oauth():
url = 'https://api-m.paypal.com/v1/oauth2/token'
headers = {
"Content-Type": "application/json",
"Accept-Language": "en_US",
}
auth = "1234-1234","0987"
data = {"grant_type":"client_credentials"}
response = requests.post(url, headers=headers, data=data, auth=(auth))
return response
def paypal_tracking(paypal_transaction_token, tracking_number, status, carrier):
try:
_paypal_oauth = paypal_oauth()
_paypal_oauth_response = _paypal_oauth.json()
except Exception as e:
print(e)
pass
access_token = _paypal_oauth_response['access_token']
url = 'https://api-m.paypal.com/v1/shipping/trackers/%s-%s/' % (paypal_transaction_token, tracking_number)
# https://api-m.paypal.com/v1/shipping/trackers/1234-567890/
carrier = carrier_code(carrier)
# This grabs carrier from a method and gets back: 'DHL'
headers = {
'Content-Type' : 'application/json',
'Authorization' : 'Bearer %s' % access_token,
}
# {'Content-Type': 'application/json', 'Authorization': 'Bearer 1234'}
data = {
"transaction_id":"%s" % paypal_transaction_token,
"tracking_number":"%s" % tracking_number,
"status": "%s" % status,
"carrier": "%s" % carrier
}
# {'transaction_id': '1234', 'tracking_number': '567890', 'status': 'SHIPPED', 'carrier': 'DHL'}
response = requests.put(url, headers=headers, data=json.dumps(data))
return HttpResponse(status=200)
Anyone with experience in paypal or using API's see my issue?
To add a tracking number (not update), use an HTTP POST request, as documented.
The URL to POST to is https://api-m.sandbox.paypal.com/v1/shipping/trackers-batch , with no additional URL parameters.
The body format is
{
"trackers": [
{
"transaction_id": "8MC585209K746392H",
"tracking_number": "443844607820",
"status": "SHIPPED",
"carrier": "FEDEX"
},
{
"transaction_id": "53Y56775AE587553X",
"tracking_number": "443844607821",
"status": "SHIPPED",
"carrier": "FEDEX"
}
]
}
Note that trackers is an array of JSON object(s).
Using python/urllib2 I've successfully created a tokbox/opentok project.
However I am unable to create the much-needed S3-archive. When attempted to get the S3-part working, I'm receiving the following:
403, Forbidden
{"code":-1,"message":"Invalid token","description":"Invalid token"}
I'm using jwt.encode to create the needed token, using ist:account.
Though for the S3 portion, I also tried ist:project.
When using the put-call, I've tried the original token, used for creating the original project, as well as a newly created token, (both account or project)...but I still see the "Invalid token" message.
token = jwt.encode({"iss": "*******",
"iat": int(time.time()),
"exp": int(time.time()) + 180,
"ist": "account",
"jti": str(uuid.uuid4())},
'***************************************',
algorithm='HS256')
url = 'https://api.opentok.com/v2/project'
headers = { "X-OPENTOK-AUTH": token }
values = {'name' : 'MyTestproject' }
data = json.dumps(values)
req = urllib2.Request(url, data, { 'X-OPENTOK-AUTH': token, 'Content-Type': 'application/json'})
try:
f = urllib2.urlopen(req)
except urllib2.URLError as e:
print e.reason
print e.code
print e.read()
sys.exit()
jsondump = json.loads(f.read())
api_key = jsondump['apiKey']
s3_token = jwt.encode({"iss": "*******",
"iat": int(time.time()),
"exp": int(time.time()) + 180,
"ist": "account",
"jti": str(uuid.uuid4())},
'***************************************',
algorithm='HS256')
s3_data = json.dumps( {
"type": "s3",
"config": {
"accessKey":s3_access_key,
"secretKey":s3_secret_key,
"bucket": s3_prod_bucket
},
"fallback":"opentok"
})
s3_url = 'https://api.opentok.com/v2/project/'+ api_key + '/archive/storage'
#s3_req = urllib2.Request(s3_url, s3_data, { 'X-OPENTOK-AUTH': token, 'Content-Type': 'application/json'})
s3_req = urllib2.Request(s3_url, s3_data, { 'X-OPENTOK-AUTH': s3_token, 'Content-Type': 'application/json'})
s3_req.get_method = lambda: 'PUT'
try:
f = urllib2.urlopen(s3_req)
except urllib2.URLError as e:
print e.reason
print e.code
print e.read()
sys.exit()
Expected result is to have the S3-Archive set within the tokbox project.
According to the documentation in [1], the token to do REST API requests must be in the following format:
{
"iss": "your_api_key",
"ist": "project",
"iat": current_timestamp_in_seconds,
"exp": expire_timestamp_in_seconds,
"jti": "jwt_nonce"
}
[1] https://tokbox.com/developer/rest/#authentication
After placing a call with Sinch API using a 'ttsCallout' method, I'm trying to get the status for that call. The calls goes through, I'm receiving its 'callId'. But when it comes to requesting my call's status, I receive 200 OK as a HTTP Response and empty ('null') content.
First, I though something is wrong with my code and the way I form Authorization headers (I use Python, its requests library and basic auth), but then I tried Sinch API explorer (https://www.sinch.com/dashboard/#/api) and it shows the same output to me (see the attached screenshot). Have to notice that this code worked about a month ago, and I was able to get call status.
Also, here is the code I use to communicate to Sinch API.
class CallNotification(Notification):
def __init__(self, data):
self.id = ""
self.call = self.data['call']
self.api_url = self.call['api_url']
self.auth = ("application:" + self.call['auth']['key'], self.call['auth']['secret'])
self.status = {'http': "new", 'result': "none", 'reason': "none"}
def send(self):
request_url = self.api_url + "/callouts"
request = requests.post(request_url,
auth=self.auth,
json={
'method': "ttsCallout",
'ttsCallout': {
'cli': "private",
'destination': {
'type': "number",
'endpoint': self.call['to']
},
'domain': "pstn",
'custom': "customData",
'locale': "en-US",
'text': self.call['message']
}
},
headers={'content-type': 'application/json'})
self.id = json.loads(request.content)['callId']
self.status['http'] = request.reason
return self.status['http']
def getstatus(self):
if not self.status['http'] == "new":
request_url = self.api_url + "/calls/id/" + self.id
request = requests.get(request_url,
auth=self.auth,
headers={'Content-type': 'application/json'})
try:
self.status['result'] = json.loads(request.content)['result']
except TypeError:
self.status['result'] = "Sent/Unknown"
return self.status['result']
Am I doing something wrong? What do I do to get status for a placed call?