How to fix Kucoin 400 Bad Request - APIs - Python - python

I wanted to place order limit with my kucoin api using python but all i got is (Bad Request) 400. How do I solve this, please I need help.
here is my code.
stringId = secrets.token_hex(8) #Generating TradeID
url = 'https://api.kucoin.com/api/v1/orders'
now = int(time.time() * 1000)
str_to_sign = str(now) + 'POST' + '/api/v1/orders'
signature = base64.b64encode(
hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"clientOid": stringId,
"side": "sell",
"symbol": "AFK-USDT",
"type": "limit",
"price": "0.05",
"size": "50.00",
}
response = requests.request('post', url, headers=headers)
print(response.status_code)
print(response.json())
This is the error response I got back
400
{'code': '400000', 'msg': 'Bad Request'}

There is a python module called kucoin-python-sdk that does all this for you.
If you would use this library it would boil down to one line like
client.create_limit_order('AFK-USDT', 'sell', '50', '0.05')
If you cannot use this module, you have to follow KuCoin's documentation:
According to KuCoin's documentation, parameters have to be sent in the body of the POST request, not as headers.
So your code should be similar to this:
params = {
"clientOid": stringId,
"side": "sell",
"symbol": "AFK-USDT",
"type": "limit",
"price": "0.05",
"size": "50.00"
}
data_json = json.dumps(params)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + data_json
signature = base64.b64encode(
hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
response = requests.request('post', url, headers=headers, data=data_json)

Related

How to pull the total balance on an SPL token for a wallet address in solana (python)

I'm looking to get the token balance for an SPL token in solana based on the:
Wallet address of the token holder
The token address
How can I do this?
I thought it would be something like:
import requests
import os
url = os.getenv("SOLANA_RPC_URL")
MY_WALLET_ADDRESS = "XXXXX"
MY_TOKEN_ADDRESS = "XXX"
MINTER = "XXXX"
TOKEN_PROGRAM_ID = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
payload = {
"id": 1,
"jsonrpc": "2.0",
"method": "getTokenAccountsByOwner",
"params": [
MY_WALLET,
{"programId": TOKEN_PROGRAM_ID},
{"encoding": "jsonParsed"},
],
}
headers = {"accept": "application/json", "content-type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
But I keep getting a blank response for what seems to be valid addresses:
{"jsonrpc":"2.0","result":{"context":{"apiVersion":"1.13.5","slot":176104484},"value":[]},"id":1}
I'm using alchemy as my node for Solana.
Summary
You can get a wallet's token balances by calling getTokenAccountsByOwner.
It takes the following parameters:
Pubkey: Your wallet address
dict: {"mint": TOKEN_ADDRESS} where TOKEN_ADDRESS is the address of the SPL token you want.
The dict can optionally be: "Pubkey of the Token program that owns the accounts" - which I don't understand what that means yet.
Code
MY_WALLET = "XXXXXX"
MY_TOKEN = "XXXX"
url = os.getenv("SOLANA_RPC_URL")
headers = {"accept": "application/json", "content-type": "application/json"}
payload = {
"id": 1,
"jsonrpc": "2.0",
"method": "getTokenAccountsByOwner",
"params": [
MY_WALLET,
{"mint": MY_TOKEN},
{"encoding": "jsonParsed"},
],
}
response = requests.post(url, json=payload, headers=headers)
print(
response.json()["result"]["value"][0]["account"]["data"]["parsed"]["info"][
"tokenAmount"
]["uiAmount"]
)

Microsoft Graph API how to send an attachment in a chat

I want to use the Microsoft Graph API to send messages with attachments to chats or channels.
https://learn.microsoft.com/en-us/graph/api/chatmessage-post?view=graph-rest-1.0&tabs=http#example-4-send-a-message-with-file-attachment-in-it
I can send normal messages already just fine like this:
def post_message(chat_id: str, subject: str = "", content_type: str = "text", content: str = "") -> None:
url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
json = {
"subject": subject,
"body": {
"contentType": content_type,
"content": content
}
}
res = requests.post(url, headers=header, json=json)
I try to copy the body from the example in the link above, substitute for my values and swap json variable for this one:
attachment_id = '7QW90B10D7-B5AK-420A-AC78-1156324A54F2' # not real, only to show how it looks like
json = {
"body": {
"contentType": 'html',
"content": f'i dunno what i\'m doing. <attachment id="{attachment_id}"></attachment>'
},
'attachments': [
{
'id': attachment_id,
'contentType': 'reference',
'contentUrl': 'https://foo.sharepoint.com/sites/bar/User%20documentation/Databricks/Databricks%20guide.pptx',
'name': 'Databricks guide.pptx'
}
]
}
I get requests.exceptions.HTTPError: 400 Client Error: Bad Request for url
What's wrong with the code? How to get attachment id from a file correctly because I am not sure I got the right value?
I was able to get it working with your code, (using both formats <attachment id=\"\"> and <attachment id="">), so it seems the error is probably with your attachment_id.
I retrieved the driveItem ID by following this answer, where the driveItem ID is the GUID value in the eTag property in the response.
You could get the file by the path:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/{item-path}
For example:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/test.docx
If the file is in a folder, it would be like this:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/folder1/test.docx
Sample request after obtaining the ID
access_token = ""
attachment_name = "file.txt"
attachment_path = "https://domain.sharepoint.com/Shared%20Documents"
attachment_id = "12345678-1234-1234-1234-123456789123"
attachment_url = f"{attachment_path}/{attachment_name}"
chat_id = ""
req_url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
req_headers = {
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
}
json = {
"body": {
"contentType": "html",
"content": f"Test message <attachment id=\"{attachment_id}\"></attachment>"
},
"attachments": [
{
"id": attachment_id,
"contentType": "reference",
"contentUrl": attachment_url,
"name": attachment_name
}
]
}
result = requests.post(url = req_url, headers = req_headers, json = json)

How to get from POST request .getresponse()(json) specific thing("access_token": value)? (using import http.client)

I get json as response as:
{"access_token":"QVQ6YmNlZjI0fdsfsFSZiLWE0OTgtZGUwMTJhMDdjMjYz","token_type":"Bearer","expires_in":7776000}
How do I write to a variable just one value from response?
Need "access_token" key value (= QVQ6YmNlZjI0fdsfsFSZiLWE0OTgtZGUwMTJhMDdjMjYz)?
Also should I better use import requests and if so, how this code would look in there?
Code: (New code with title fixed problem)
import http.client
import json
#Request Client Credential Grant (CCG) token
conn = http.client.HTTPSConnection("sandbox.handelsbanken.com")
payload = "client_id=45325132-fsafsa-saczx&grant_type=client_credentials&scope=AIS"
headers = {
'Accept': "application/json",
'Content-Type': "application/x-www-form-urlencoded",
'content-type': "application/x-www-form-urlencoded",
'accept': "application/json"
}
conn.request("POST", "/openbanking/oauth2/token/1.0", payload, headers)
res = conn.getresponse()
data = res.read()
y = json.loads(data)
access_token = y.get("access_token", None)
#print(data.decode("utf-8"))
Next problem is implementing it in new headers
payload = "{\"access\":\"ALL_ACCOUNTS\"}"
headers = { 'X-IBM-Client-Id': "REPLACE_THIS_VALUE", '
Authorization': "Bearer "+access_token, '
Country': "REPLACE_THIS_VALUE", '
TPP-Transaction-ID': "REPLACE_THIS_VALUE", '
TPP-Request-ID': "REPLACE_THIS_VALUE", '
content-type': "application/json", '
accept': "application/json" }
Do I do it like this?
I understood that I can't comprehend how do another thing with json..
{
"accounts": [
{
"accountId": "ae57e780-6cf3-11e9-9c41-e957ce7d7d69",
"iban": "SE5460000000000403333911",
"bban": "403333911",
"currency": "SEK",
"accountType": "Allkortskonto",
"bic": "HANDSESS",
"clearingNumber": "6295",
"ownerName": "Bo Bankkund",
"_links": {
"transactions": {
"href": "https://sandbox.handelsbanken.com/openbanking/psd2/v2/accounts/ae57e780-6cf3-11e9-9c41-e957ce7d7d69/transactions"
}
}
},
{
"accountId": "ae5835a0-6cf3-11e9-9c41-e957ce7d7d69",
"iban": "SE8160000000000401975231",
"bban": "401975231",
"currency": "SEK",
"accountType": "Allkonto Ung",
"bic": "HANDSESS",
"clearingNumber": "6295",
"name": "Almas konto",
"ownerName": "Alma Bankkund",
"_links": {
"transactions": {
"href": "https://sandbox.handelsbanken.com/openbanking/psd2/v2/accounts/ae5835a0-6cf3-11e9-9c41-e957ce7d7d69/transactions"
}
}
}
]
}
How to get first "accountId" key value in a variable?
1.How do I write to a variable just one value from response?:
data = res.read()
y = json.loads(data) #transforms "data" to json
access_token = y.get("access_token", None) #access "access_token" value and if there's no value makes it none with "None"
Next problem is implementing it in new headers:
headers = { 'X-IBM-Client-Id': "REPLACE_THIS_VALUE", '
Authorization': "Bearer "+access_token, '
Country': "REPLACE_THIS_VALUE", '
TPP-Transaction-ID': "REPLACE_THIS_VALUE", '
TPP-Request-ID': "REPLACE_THIS_VALUE", '
content-type': "application/json", '
accept': "application/json" }
How to get first "accountId" key value in a variable?
data = res.read()
y = json.loads(data)
accounts = y["accounts"][0] # saves in variable first accounts array elements
accountId = accounts["accountId"] #from accounts variable takes "accountId" value

Facing Issue Sending Gmail Using Google Gmail API

It shows credentials are missing when I try to use the Google Gmail API to send messages. I want to send an email to my other Gmail account using the Google Gmail API.
import sys
import requests
import base64
import sys
from email.mime.text import MIMEText
AccessToken = ""
params = {
"grant_type": "refresh_token",
"client_id": "xxxxxxxxxxxxxxx",
"client_secret": "xxxxxxxxxxxxxxx",
"refresh_token": "xxxxxxxxxxxxxxxxxxxx",
}
authorization_url = "https://www.googleapis.com/oauth2/v4/token"
r = requests.post(authorization_url, data=params)
if r.ok:
AccessToken = str((r.json()['access_token']))
EmailFrom = "Test1#gmail.com"
EmailTo = "test2#gmail.com"
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text, 'html')
message['to'] = to
message['from'] = sender
message['subject'] = subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
body = create_message(EmailFrom, EmailTo, "Just wanna Say Waka Waka!", "Waka Waka!")
url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
header = {
'Authorization': 'Bearer ' + AccessToken,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.post(
url,
header,
body
)
print("\n")
print(r.text)
print("\n")
Error:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING",
"domain": "googleapis.com",
"metadata": {
"method": "caribou.api.proto.MailboxService.SendMessage",
"service": "gmail.googleapis.com"
}
}
]
}
}
I'm not a google api user, but I've used oauth several times, and your setup is a bit different than what I usually use or what I see from a quick sniff of Google's documention. For example, I use client-creds instead of a refresh token. For what I'm seeing above in your code, no reason to refresh an old token, when you can just mint another one. Compared to yours, usually with oauth, we'll do something like auth=(client_id, client_secret)
Lastly, before you change anything big, when you changed your header to place the AccessToken variable in quotes, did you use an f-string? What is the output of
print(header)
after you have defined it? Is it what you expect? If you didn't format it, it's going to have the variable's name rather than value.
If that's all ok, I'd try to write it according to OAuth standards that I've used several times. Not telling you how to do it, but you could try something like:
def getKey():
url = "https://www.googleapis.com/oauth2/v4/token"
client_id = "*yourgoogleclientid*"
client_secret = "*yourgoogleclientsecret*"
data = {
'grant_type': 'client_credentials'
}
r = requests.post(url, json=data, auth=(client_id, client_secret))
key = r.json()['access_token']
return key
def getWhatever(key, url):
header = {
'Authorization': f'Bearer {key} '
}
params = {
'whatever params': 'you might need'
}
response = requests.get(url, headers=header, params=params)
* parse, process, return, whatever you'd like to do with the response.*
now to use it....
if __name__ == '__main__':
myKey = getKey()
whatImLookingFor = getWhatever(myKey, "*https://google_api_endpoint*")

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

Categories