Error creating post - during Python script execution - python

import requests
import json
access_token = "538-olsMYl22DQrD6GMIcJFnpg"
group_id = "128222494720"
message = "My First Yammer#Bot Post"
data = {
"body": {
"message": message
},
"group_id": group_id
}
response = requests.post(
"https://api.yammer.com/api/v1/messages.json",
headers={
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
},
data=json.dumps(data)
)
if response.status_code == 201:
print("Post created successfully!")
else:
print("Error creating post: " + response.text)
I am trying to create a yammer post through python scripts. During executing the code I am getting:
Error creating post: {"status":500,"error":"Internal Server Error"}

Related

Sisense API build ElastiCube

I'm trying to trigger an ElastiCube rebuild within a python script but am running into some trouble. I'm using /v1/authentication/login to get my api key successfully, but when I pass it into /v2/builds in the form {"Authorization": "Bearer " + access_token, "body": {...}}, I get a 401 error.
credentials = {"username": *username*, "password": *password*}
r = requests.post("*host*/api/v1/authentication/login", data = credentials)
access_token = r.json()["access_token"]
data = {"Authorization": "Bearer " + access_token, "body": {
"datamode1Id": *id*,
"buildType": "full",
"rowLimit": 0,
"schemaOrigin": "latest"
}}
r = requests.post("*host*/api/v2/builds", data = data)
print(r.json())

Unable to filter, paginate, or add any data to Notion API query from python code

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)

PayPal Tracking showing INVALID_TRACKING_CODE

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

Successfully created a tokbox project, using python and urllib2, however I cannot create S3-archive

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

Update Sharepoint 2013 using Python3

I am currently trying to update a Sharepoint 2013 list.
This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error:
"b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'"
Any idea of what I am doing wrong?
def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname):
login_user = ad_domain + '\\' + sharepoint_user
auth = HttpNtlmAuth(login_user, sharepoint_password)
sharepoint_url = site_url + '/_api/web/'
sharepoint_contextinfo_url = site_url + '/_api/contextinfo'
headers = {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'odata': 'verbose',
'X-RequestForceAuthentication': 'true'
}
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue']
item_id = 4991 # This id is one of the Ids returned by the code above
api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id)
update_headers = {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose",
"odata": "verbose",
"X-RequestForceAuthentication": "true",
"X-RequestDigest": form_digest_value,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False)
if r.status_code == 204:
print(str('Updated'))
else:
print(str(r.status_code))
I used your code for my scenario and fixed the problem.
I also faced the same problem. I think the way that data passed for update is not correct
Pass like below:
json_data = {
"__metadata": { "type": "SP.Data.TasksListItem" },
"Title": "updated title from Python"
}
and pass json_data to requests like below:
r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text
Note: I used SP.Data.TasksListItem as it is my type. Use http://SharePointurl/_api/web/lists/getbytitle('name')/ListItemEntityTypeFullName to find the type

Categories