This one beats me try everything such as base64 converting it into binary just keep getting this error below
{"error":{"code":"InvalidImageSize","message":"Image size
is too small or too big."}}
here is my code is written in python :
import httplib, urllib, base64
import json
import sys
import base64
# require for authentication
key = "YourKey"
# leave as one header so ther three steps can access the same format
# application/octet-stream
headers = {
# Request headers
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': key,
}
# params for detection return FaceId
params = urllib.urlencode({
# Request parameters
'returnFaceId': 'true',
})
with open("C://Python-Windows//random_test//unknowfaces//Adam.jpg", "rb") as
imageFile:
f = imageFile.read()
b = bytearray(f)
print f
#image_64_encode = base64.encodestring(image_read)
"""
body = {
"url":"https://lh6.googleusercontent.com/-
dKxIImkT0to/WApnOYQSIFI/AAAAAAAAAAA/H9IsZ2xGxiE/photo.jpg"
}
"""
#below is for the binary
body = {
f[0]
}
# conn to be use at all three steps
conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/face/v1.0/detect?%s" % params, str(body), headers)
response = conn.getresponse()
data = response.read()
print(data)
#Parse json data to print just faceId
somedata = json.loads(data)
faceid = somedata[0]['faceId']
print somedata[0]['faceId']
print " :is what face id has produce ==> " + faceid
conn.close()
not sure if I have intended the above code properly on this tread so do please check.
I would appreciate your support thanks
Here's how you might change your code:
with open("your-image.jpg", "rb") as imageFile:
image = imageFile.read()
conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/face/v1.0/detect?%s" % params, headers=headers, body=image)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
Related
I'm trying to get a payment card data from wallester throught API. But whenever I try to decode the data, the library just giving me error, also online tools are not very helpfull. I Have no Idea, where it can be a problem, if you guys have made something in wallester, please let me know.
I have made a code in python to get this, but I'm lost in this moment. Wallester support is not helping at all.
import json
import base64
import jwt
import requests
import rsa
import time
def get_encrypted_card_number(api_key, rsa_public_key, rsa_private_key, card_id):
# Generate the JWT token
jwt_private_key = rsa_private_key.encode()
timestamp = int(time.time())
claims = {
"api_key": api_key,
"ts": timestamp
}
jwt_token = jwt.encode(claims, jwt_private_key, algorithm="RS256")
request_data = {
'public_key': base64.b64encode(rsa_public_key.encode()).decode()
}
headers = {
'Authorization': "Bearer " + jwt_token,
'Content-Type': 'application/json'
}
url = f"https://api-frontend.wallester.com/v1/cards/{card_id}/encrypted-card-number"
# Send the API request
response = requests.post(url, headers=headers, data=json.dumps(request_data))
response_data = response.json()
if response.status_code != 200:
raise Exception("API request failed")
response_data = response.json()
res = response_data['encrypted_card_number']
res = res.replace("-----BEGIN CardNumber MESSAGE-----", "")
res = res.replace("-----END CardNumber MESSAGE-----", "")
res = res.replace("\n", "")
print(res)
encrypted_card_number = base64.b64decode(res.encode())
# Decrypt the card number
private_key = rsa.PrivateKey.load_pkcs1(rsa_private_key.encode())
decrypted_card_number = rsa.decrypt(encrypted_card_number, private_key).decode()
return decrypted_card_number
# Example usage
api_key = ""
with open("private.pem", "r") as f:
rsa_private_key = f.read()
with open("public.pem", "r") as f:
rsa_public_key = f.read()
card_id = "ce7b54a6-8165-49e1-97b2-bca7af5abaa5"
decrypted_card_number = get_encrypted_card_number(api_key, rsa_public_key, rsa_private_key, card_id)
print(f"Decrypted card number: {decrypted_card_number}")
I've encountered with the same issue on Node.js.
It didn't work until I've added label.
Here is my Node.js example. Hope it helps.
const cardNumberBase64Encoded = cardNumberPem.replace(/\n/g, '')
.replace('-----BEGIN CardNumber MESSAGE-----', '')
.replace('-----END CardNumber MESSAGE-----', '');
const decryptedData = crypto.privateDecrypt(
{
key: encPkcs8Pem,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha256",
//
// IMPORTANT
// IMPORTANT
// IMPORTANT
// IMPORTANT
oaepLabel: Buffer.from("CardNumber"), // <======
// IMPORTANT
// IMPORTANT
// IMPORTANT
// IMPORTANT
//
},
Buffer.from(cardNumberBase64Encoded, 'base64'),
);
console.log(decryptedData.toString());
I’ve quite recently found this feature on Bitget which enables users to essentially copy other ranked traders. This feature comes with a corresponding api documentation. But after going through it im more confused than ever. Firstly, im trying to obtain the historical data trading data of specific traders which are available data on their “orders tab” from the website (shown in excerpt above). I reckon this is possible from the following get request from the documentation: “GET /api/mix/v1/trace/waitProfitDateList”.
Based on the above http request from i have produced the following python code below. The request response is 403. Help a fellow novice
import requests
import hmac
import base64
import hashlib
import json
import time
def sign(message, secret_key):
mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
d = mac.digest()
return base64.b64encode(d).decode('utf-8')
def pre_hash(timestamp, method, request_path, query_string, body):
return str(timestamp) + str.upper(method) + request_path + query_string + body
if __name__ == '__main__':
params = {
"pageSize": 10,
"pageNo": 1
}
rest_url = "https://api.bitget.com"
secret_key = ""
api_key = ""
passphrase = ""
timestamp = int(time.time_ns() / 1000000);
query_string = '&'.join([f'{k}={v}' for k, v in params.items()])
message = pre_hash(timestamp, 'GET', '/api/mix/v1/trace/waitProfitDateList', "?"+query_string,"")
sign = sign(message, secret_key)
headers = {
"ACCESS-KEY":api_key,
"ACCESS-SIGN":sign,
"ACCESS-TIMESTAMP":str(timestamp),
"ACCESS-PASSPHRASE":passphrase,
"Content-Type":"application/json",
"locale":"en-US"
}
response = requests.get(rest_url, headers=headers, params=params)
if response.status_code == 200:
result = response.json()
print(result)
else:
print(response.status_code)
I need to send csv file as input in the request along with url,data & headers as this is import request. But the Request is not supporting the files. Can you assist me how to send files input in the urllib.request.
headers = {
'SESSION-ID': 'xxx',
'keyid': 'xxx'
}
payload = {"delimiter":"COMMA","textQualifier":"DOUBLE_QUOTE","codepage":"UTF8",
"dateFormat":"ISO"}
payload1 = json.dumps(payload).encode("utf-8")
payload2 = {'importSettings':payload1}
data = json.dumps(payload2).encode("utf-8")
#print(data)
files = [('file',('import.csv', csvstr,'text/csv'))]
url = xxx
try:
req = urllib.request.Request(url, data, headers,files=files)
with urllib.request.urlopen(req) as f:
res = f.read()
print(res.decode())
return res
except Exception as e:
print(e)
Getting this error - init() got an unexpected keyword argument 'files'
I'm using a python script to send an API request to get the attachments of an email. The email I'm using has 4 attachments (plus pictures in the signature in the email). The python request only retrieves 1 attachment along with the pics from the signature. When using Postman with the exact same information, it retrieves all attachments along with the pics.
Any ideas on how I can get the other attachments?
import requests
url = 'https://graph.microsoft.com/v1.0/users/{{users email}}/messages/{{messageID}}/attachments'
body = None
head = {"Content-Type": "application/json;charset=UFT-8", "Authorization": "Bearer " + accessToken}
response1 = requests.get(url, data=body, headers=head)
response = response1.text
Below shows the response from the python script, with only 7 items, and the Postman response with 10 items.
Below code retrieves multiple attachments
(files being an array of attachment names)
def execute(accessToken, messageID, files, noAttachments):
import os
from os import path
import requests
import base64
import json
if noAttachments == "False":
url = 'https://graph.microsoft.com/v1.0/users/{{users email}}/messages/{{messageID}}/attachments'
body = {}
head = {"Authorization": "Bearer " + accessToken}
responseCode = requests.request("GET", url, headers=head, data = body)
response = responseCode.text
test = json.loads(responseCode.text.encode('utf8'))
x, contentBytes = response.split('"contentBytes":"',1)
if len(files) == 1:
imgdata = base64.b64decode(str(contentBytes))
filename = "C:/Temp/SAPCareAttachments/" + files[0]
with open(filename, 'wb') as f:
f.write(imgdata)
else:
for file in test["value"]:
imgdata = base64.b64decode(file["contentBytes"])
if file["name"] in files:
filename = "C:/Temp/" + file["name"]
with open(filename, 'wb') as f:
f.write(imgdata)
print(responseCode)
I am trying to make a basic authenticated api call to their new v2 api and getting an invalid api key error returned.
I reissued the api key just to verify, same error.
from time import time
import urllib.request
import urllib.parse
import hashlib
import hmac
APIkey = b'myapikeyyouarenotsupposedtosee'
secret = b'myceeeeecretkeyyyy'
url = 'https://api.bitfinex.com/v2/auth/r/wallets'
payload = {
#'request':'/auth/r/wallets',
'nonce': int(time() * 1000),
}
paybytes = urllib.parse.urlencode(payload).encode('utf8')
print(paybytes)
sign = hmac.new(secret, paybytes, hashlib.sha512).hexdigest()
print(sign)
headers = {
'Key': APIkey,
'Sign': sign
}
req = urllib.request.Request(url, headers=headers, data=paybytes)
with urllib.request.urlopen(req) as response:
the_page = response.read()
print(the_page)
How do I make an authenticated api call to the new v2 API for bitfinex?
Your headers are wrong. I was also trying to do this and tried using the example code from the bitfinex v2 api docs, however their example contained a bug in that they needed to encode the strings into UTF-8 byte arrays first. So I've fixed it and posting the entire example below.
#
# Example Bitfinex API v2 Auth Python Code
#
import requests # pip install requests
import json
import base64
import hashlib
import hmac
import os
import time #for nonce
class BitfinexClient(object):
BASE_URL = "https://api.bitfinex.com/"
KEY = "API_KEY_HERE"
SECRET = "API_SECRET_HERE"
def _nonce(self):
# Returns a nonce
# Used in authentication
return str(int(round(time.time() * 10000)))
def _headers(self, path, nonce, body):
secbytes = self.SECRET.encode(encoding='UTF-8')
signature = "/api/" + path + nonce + body
sigbytes = signature.encode(encoding='UTF-8')
h = hmac.new(secbytes, sigbytes, hashlib.sha384)
hexstring = h.hexdigest()
return {
"bfx-nonce": nonce,
"bfx-apikey": self.KEY,
"bfx-signature": hexstring,
"content-type": "application/json"
}
def req(self, path, params = {}):
nonce = self._nonce()
body = params
rawBody = json.dumps(body)
headers = self._headers(path, nonce, rawBody)
url = self.BASE_URL + path
resp = requests.post(url, headers=headers, data=rawBody, verify=True)
return resp
def active_orders(self):
# Fetch active orders
response = self.req("v2/auth/r/orders")
if response.status_code == 200:
return response.json()
else:
print('error, status_code = ', response.status_code)
return ''
# fetch all your orders and print out
client = BitfinexClient()
result = client.active_orders()
print(result)
Why not use one of the open source api clients out there ? and you can compare to your work .
https://github.com/scottjbarr/bitfinex
https://github.com/tuberculo/bitfinex