SendBird Error 400403 Invalid value: JSON body - python

I am trying to create user using send bird API
I am using python to make the API call, but getting error code 400403,
If I try from postman it works, not sure where I'm going wrong in the code
Following is my code -
import json
import requests
url = ‘https://api-someappidhere.sendbird.com/v3/users’
headers = {
'Content-Type' : 'application/json; charset=utf8',
'Api-Token' : 'secondaryApiToken'
}
data = {
'user_id' : 'someuserId',
'nickname' : 'somenickname',
'profile_url' : ''
}
try:
apiResponse = requests.post(url, headers=headers, data=data)
apiResponse = apiResponse.json()
return response
except Exception as error:
print(error)
I am getting the following response -
{
"hasError": false,
"result": {
"message": "Invalid value: \"JSON body.\".",
"code": 400403,
"error": true
}
}
References -
https://docs.sendbird.com/platform/quick_start
https://docs.sendbird.com/platform/error_codes

You should use json.dumps().
import json
import requests
url = ‘https://api-someappidhere.sendbird.com/v3/users’
headers = {
'Content-Type' : 'application/json; charset=utf8',
'Api-Token' : 'secondaryApiToken'
}
data = {
'user_id' : 'someuserId',
'nickname' : 'somenickname',
'profile_url' : ''
}
jsonData = json.dumps(data)
try:
apiResponse = requests.post(url, headers=headers, data=jsonData)
apiResponse = apiResponse.json()
return response
except Exception as error:
print(error)

Related

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

Send request to azure inkrecognizer

I have registered at the https://azure.microsoft.com/ru-ru/try/cognitive-services
From there I got an API-key and an endpoint https://api.cognitive.microsoft.com/inkrecognizer
Here is my code:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('POST', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
However it gives me
Response:
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
What am I doing wrong?
Here how the code should look like:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer/v1.0-preview/recognize'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('PUT', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
And you will need to add into body 'language' and 'strokes'
GIST

Facebook send API sending audio issue

Can't send audio through facebook send api. It always returns with an HTTP 400 Bad Request. I use python and urllib for the http request.
Json:
'recipient':{
'id' : userId
},
'message' : {
'attachment' : {
'type' : 'audio',
'payload' : {
'url' : url
}
}
}
}
Request:
def send_msg(userId,data,accessKey):
HEADERS = {
'Content-Type':'application/json'
}
url = 'https://graph.facebook.com/v2.6/me/messages?access_token='+accessKey
msg_json = {
'message' : {
'attachment' : {
'type' : 'audio',
'payload' : {
'url' : url
}
}
}
data = json.dumps(msg_json).encode('utf-8')
req = urllib.request.Request(url,data,HEADERS)
resp = urllib.request.urlopen(req)
The code works on image and file attachment but it doesn't work on audio.
The problem in the json blueprint is the missing 'Content-type' that should have a value of 'audio/mpeg' that specifies the file format for the mp3 audio uploads

YouTube API video upload error: parseError /w python

The example code for Google's YouTube Data API is a piece of junk. It's so complicated and tied to the oauth redirect flow that I can't use it. Trying to go raw with requests pip and not getting too far.
I've followed the instructions exactly (as far as I can tell), with the following code:
import json
import os
import sys
import urllib
import requests
payload_file = None
payload = None
print 'Loading Config'
# Get the directory path of this file. When using any relative file paths make
# sure they are relative to current_dir so that the script can be run from any CWD.
current_dir = os.path.dirname(os.path.abspath(__file__))
# Reads in the config.json file then parses it
config = json.loads(open(os.path.join(current_dir, '..', 'config.json')).read())
print 'Parsing Payload'
for i in range(len(sys.argv)):
if sys.argv[i] == "--json" and (i + 1) < len(sys.argv):
payload = json.loads(sys.argv[i + 1])
elif sys.argv[i] == "-payload" and (i + 1) < len(sys.argv):
payload_file = sys.argv[i + 1]
with open(payload_file,'r') as f:
payload = json.loads(f.read())
break
print 'Configuring youtube with token {0}'.format(payload['token'])
print 'Downloading video...'
# See how big it is
f = urllib.urlopen(payload['url'])
content_length = int(f.headers["Content-Length"])
# Download it
# urllib.urlretrieve(payload['url'], "video.mp4")
metadata = {
'snippet' : {
'title': payload['title'],
"categoryId": 22
},
'status' : {
"privacyStatus": "public",
"embeddable": True,
"license": "youtube"
}
}
if 'tags' in payload:
metadata['snippet']['tags'] = payload['tags']
if 'description' in payload:
metadata['snippet']['description'] = payload['description']
headers = {
'Authorization' : 'Bearer {0}'.format(payload['token']),
'Content-Type' : 'application/json; charset=UTF-8',
'Content-Length' : json.dumps(metadata).__len__(),
'X-Upload-Content-Length' : content_length,
'X-Upload-Content-Type' : 'video/*',
}
print 'Attempting to upload video'
print headers
# upload video file
r = requests.post('https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status', data=metadata, headers=headers);
print "RESPONSE!"
print r.text
# files = {
# 'file': video_file,
# }
# r = requests.post('https://www.googleapis.com/upload/youtube/v3/videos', data={ "video" : video }, headers=headers);
Obviously its not finished, but its dying on the metadata upload request with the following output:
Loading Config
Parsing Payload
Configuring youtube with token <access-token>
Downloading video...
Attempting to upload video
{'X-Upload-Content-Length': 51998563, 'Content-Length': 578, 'Content-Type': 'application/json; charset=UTF-8', 'X-Upload-Content-Type': 'video/*', 'Authorization': 'Bearer <access-token>'}
RESPONSE!
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
This error is not even listed in their "Errors" docs.
What is wrong with my code?
Here is an example in python that works. It assumes you've already done the oauth part though.
import requests
from os import fstat
import json
fi = open('myvideo.mp4')
base_headers = {
'Authorization': '%s %s' % (auth_data['token_type'],
auth_data['access_token']),
'content-type': 'application/json'
}
initial_headers = base_headers.copy()
initial_headers.update({
'x-upload-content-length': fstat(fi.fileno()).st_size,
'x-upload-content-type': 'video/mp4'
})
initial_resp = requests.post(
'https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails',
headers=initial_headers,
data=json.dumps({
'snippet': {
'title': 'my title',
},
'status': {
'privacyStatus': 'unlisted',
'embeddable': True
}
})
)
upload_url = initial_resp.headers['location']
resp = requests.put(
upload_url,
headers=base_headers,
data=fi
)
fi.close()
the above is graet, just adding: you can also get the youtube id from the response (for future use):
cont = json.loads(resp.content)
youtube_id = cont['id']

Categories