make an order kucoin API in python - python

import requests, json, time
url = 'https://api.kucoin.com/api/v1/orders'
headers = {
"KC-API-KEY": '',
"KC-API-PASSPHRASE": '',
"clientOid": "AAA",
"side": "sell",
"symbol": "BTC-USDT",
"type": "market",
"size": "0.001",
}
response = requests.post(url, headers=headers)
print(response.status_code)
print(response.json())
I am trying to place an order but it isn't working. Am I missing some parameters?
Error:
{'code': '400001', 'msg': 'Please check the header of your request for KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE'}

According to the official docs, all private request must contain the following headers:
KC-API-KEY
KC-API-SIGN
KC-API-TIMESTAMP
KC-API-PASSPHRASE
KC-API-VERSION
Here is an example of the endpoint to place a order limit:
import base64, hmac, hashlib, json
# constants
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
API_PASSPHRASE = "YOUR_API_PASSPHRASE"
url = "https://api.kucoin.com/api/v1/orders"
now = int(time.time() * 1000)
data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}
data_json = json.dumps(data)
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"
}
try:
res = requests.post(
url, headers=headers, data=data_json).json()
print(res)
except Exception as err:
print(err)
Hope it will help.

Did you consider using wrapped library like Python-kucoin ?
https://python-kucoin.readthedocs.io/en/stable/index.html
it is really great and will definitely help you. Have a look to the documentation
from kucoin.client import Client
api_key = '<api_key>'
api_secret = '<api_secret>'
api_passphrase = '<api_passphrase>'
client = Client(api_key, api_secret, api_passphrase)
# place a market buy order
order = client.create_market_order('BTC-USDT', Client.SIDE_BUY, size=0.001)

try removing the spaces from :
data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}

Related

Amadeus Flight Availabilities in Python - Error 400

I am trying to use the POST method of Amadeus flight availabilities API on Python, but is is still giving me error 400. Any suggestions? Many thanks.
from amadeus import Client, ResponseError, Location
import requests
amadeus = Client(
client_id='My ID',
client_secret='My Secret')
try:
flights = amadeus.get('/v2/shopping/flight-offers',originLocationCode = "GIG",destinationLocationCode = "ATL",departureDate = "2023-01-31",nonStop = "true",travelClass = "BUSINESS",adults = 1)
body = flights.data[0]
print(body)
except ResponseError as error:
print(error)
try:
availability = amadeus.post('/v1/shopping/availability/flight-availabilities', body)
print(availability.result)
except ResponseError as error:
print('headers: ', error.response.request.headers)
print('body: ', error.response.request.params)
As per their API documentation, the body of the second API call needs to be in the following format:
{
"originDestinations": [
{
"id": "1",
"originLocationCode": "BOS",
"destinationLocationCode": "MAD",
"departureDateTime": {
"date": "2021-11-14",
"time": "21:15:00"
}
}
],
"travelers": [
{
"id": "1",
"travelerType": "ADULT"
}
],
"sources": [
"GDS"
]
}
Right now you are just feeding the second call the return from the first, which doesn't seem to be what they're looking for.
You might also need to feed the proper headers, something like:
headers = {"Content-Type": "application/json; charset=utf-8"}
then you would do
response = requests.post(url, headers=headers, json=body)

How to use API QR Monkey with post or get method on Python

I'm trying to use the free api https://www.qrcode-monkey.com and I can't find anywhere a valid example for python, I think I followed thru the documentation. I'm doing some trial and on POST I continue getting method errors and on GET I get a lot of 400 errors...
Here is the code with both, anyone knows what I'm doing wrong? Thank you!
import requests
from urllib.parse import quote, urlencode
class QrManager:
def __init__(self):
self.url = "https://qrcode-monkey.com/"
def get_data_post(self):
url = self.url + "qr/custom"
payload = {
"data": "https://www.google.com",
"config": {
"body": "circle",
},
"size": 300,
"download": False,
"file": "png"
}
req = requests.post(url, json=payload)
return req
def get_data_get(self):
template_url = self.url + "qr/custom/?{}"
params = {
"data": "https://www.google.com",
"config": {
"body": "circle",
},
"size": 300,
"download": False,
"file": "png"
}
url = template_url.format(urlencode(params, safe="()", quote_via=quote))
req = requests.get(url)
return req
qrm = QrManager()
# response = dm.get_data_post()
response = qrm.get_data_get()
print(response.status_code)
print(response.url)
print(response.text)
They didn't show it in documentation but it needs different URL - with api. instead of www.
https://api.qrcode-monkey.com/qr/custom
I used DevTools in Firefox/Chrome (tab:Network) to see url used when page generates QR.
There is other problem.
POST gives QR with circles but GET gives with normal squares.
GET needs to convert config to json to get circles
"config": json.dumps({"body": "circle"})
(but it doesn't need urlencode)
Full code.
import requests
#from urllib.parse import quote, urlencode
import json
class QrManager:
def __init__(self):
self.url = "https://api.qrcode-monkey.com/qr/custom"
def get_data_post(self):
# it converts `config` to `json` automatically (because it sends all `payload` as `json`)
payload = {
"data": "https://blog.furas.pl",
"config": {
"body": "circle",
},
"size": 300,
"download": False,
"file": "png"
}
response = requests.post(self.url, json=payload)
return response
def get_data_get(self):
# it needs to convert `config` to `json` manually
payload = {
"data": "https://blog.furas.pl",
"config": json.dumps({
"body": "circle"
}),
"size": 300,
"download": False,
"file": "png"
}
#payload = urlencode(payload, safe="()", quote_via=quote)
response = requests.get(self.url, params=payload)
return response
# --- main ---
qrm = QrManager()
print('\n--- GET ---\n')
response = qrm.get_data_get()
print('status:', response.status_code)
print('url:', response.url)
print(response.text[:100])
with open('QR_GET.png', 'wb') as f:
f.write(response.content)
print('\n--- POST ---\n')
response = qrm.get_data_post()
print('status:', response.status_code)
print('url:', response.url)
print(response.text[:100])
with open('QR_POST.png', 'wb') as f:
f.write(response.content)
Result:
--- GET ---
status: 200
url: https://api.qrcode-monkey.com/qr/custom?data=https%3A%2F%2Fblog.furas.pl&config=%7B%22body%22%3A+%22circle%22%7D&size=300&download=False&file=png
�PNG
IHDR\\t�{bKGD��������IDATx��ON[��š�6#�P��hŮ#H� ��[��M��T=3#J
--- POST ---
status: 200
url: https://api.qrcode-monkey.com/qr/custom
�PNG
IHDR\\t�{bKGD��������IDATx��ON[��š�6#�P��hŮ#H� ��[��M��T=3#J

response 422 after trying to send post request with json file

I have been trying to find an answer that work on my case but had no success.
I am getting a response 422 when running the code below. I have replaced the json in the response variable and also used json.dumps around the data variable but I am still getting this response. Would you be able to find the issue within my json file? Thanks a lot
todaystr = datetime.today().strftime('%Y-%m-%d')
today = datetime.strptime(todaystr, '%Y-%m-%d')
first_day_of_month = today.replace(day=1)
day_count_str = today - first_day_of_month
day_count_int = day_count_str / timedelta(days=1)
day_count_split = str(day_count_int)
sep = '.'
day_count = day_count_split.split(sep, 1)[0]
dt = str(first_day_of_month.timestamp())
data = {"requestId": "numberOfUniqueAccountsAndVisitors", "timeSeries": {"period": "dayRange", "count": day_count, "first": dt}, "source": {"events": None}, "pipeline": [{"reduce": [{"reduce": {"visitors": {"count": "visitorId"}, "accounts": {"count": "accountId"}}}]}]}
headers = {
'x-pendo-integration-key': API_Key,
'content-type': "application/json"
}
response = requests.post(url, json=data, headers=headers)
print(response)
response_dictionary = json.loads(response.content)
print(response_dictionary)
In the payload to the Pendo Aggregation API, the request object should not be an array. And make sure the "key" should be named as "request"(singular), not as "requests"(plural).
Try something like this
{
"response": {
"mimeType": "application/json"
},
"request": {
"name": "accounts-last7days",
"requestId": "accounts-last7days"
}
}

Working with session cookies in Python

I am trying to get access to the Kerio Connect (mailserver) api which uses jsonrpc as a standard for their api.
There is Session.login method that works just fine, I get back a SESSION_CONNECT_WEBADMIN cookie that gets saved in the session:
SESSION_CONNECT_WEBADMIN=2332a56d0203f27972ebbe74c09a7f41262e5b224bc6a05e53e62e5872e9b698; \
path=/admin/; domain=<server>; Secure; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;
But when I then do my next request with the same session, I get back a message that tells me, that my session has expired:
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32001,
"message": "Session expired.",
"data": {
"messageParameters": {
"positionalParameters": [],
"plurality": 1
}
}
}
}
So here's the Python script leading to that message
import json
import requests
userName = "username"
password = "password"
n=1
application = {}
application["name"] = "Log in"
application["vendor"] = "My Company"
application["version"] = "1.0"
params = {}
params["userName"] = userName
params["password"] = password
params["application"] = application
payload = {}
payload["jsonrpc"] = "2.0"
payload["id"] = n
n += 1
payload["method"] = "Session.login"
payload["params"] = params
headers = {}
headers["Content-Type"] = "application/json-rpc"
json_payload =json.dumps(payload, sort_keys=True, indent=2)
url = "https://<server>:4040/admin/api/jsonrpc/"
session = requests.Session()
response = session.post(url, headers=headers, data=json_payload, verify=False)
# Results in a token / a cookie with that token
payload2 = {}
payload2["jsonrpc"] = "2.0"
payload2["id"] = n
n += 1
payload2["method"] = "Users.get"
json_payload2 = json.dumps(payload2, sort_keys=True, indent=2)
response2 = session.post(url, data=json_payload2, verify=False)
print(response2.text)
What am I missing here because of my lack of experience?
[EDIT]:
I just now realise that when I log in with a browser, two cookies are actually created, each with another token, whereas I get only one cookie back when I try to access the api with Python. Why is that?
Cookies received with Chrome:
TOKEN_CONNECT_WEBADMIN
SESSION_CONNECT_WEBADMIN
Cookie received with Python:
SESSION_CONNECT_WEBADMIN
Working example:
import json
import urllib.request
import http.cookiejar
import ssl
jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
urllib.request.install_opener(opener)
server = "https://mail.smkh.ru:4040"
username = "admin"
password = "pass"
ssl._create_default_https_context = ssl._create_unverified_context # disable ssl cert error
def callMethod(method, params, token=None):
"""
Remotely calls given method with given params.
:param: method string with fully qualified method name
:param: params dict with parameters of remotely called method
:param: token CSRF token is always required except login method. Use method "Session.login" to obtain this token.
"""
data = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
req = urllib.request.Request(url=server + '/admin/api/jsonrpc/')
req.add_header('Content-Type', 'application/json')
if token is not None:
req.add_header('X-Token', token)
httpResponse = opener.open(req, json.dumps(data).encode())
if httpResponse.status == 200:
body = httpResponse.read().decode()
return json.loads(body)
session = callMethod("Session.login", {"userName": username, "password": password, "application": {"vendor":"Kerio", "name":"Control Api Demo", "version":"8.4.0"}})
token = session["result"]["token"]
sessions = callMethod("Users.get",
{"query": {
"fields": [
"id",
"loginName",
"fullName",
"description",
"authType",
"itemSource",
"isEnabled",
"isPasswordReversible",
"emailAddresses",
"emailForwarding",
"userGroups",
"role",
"itemLimit",
"diskSizeLimit",
"consumedItems",
"consumedSize",
"hasDomainRestriction",
"outMessageLimit",
"effectiveRole",
"homeServer",
"migration",
"lastLoginInfo",
"accessPolicy"
],
"start": 0,
"limit": 200,
"orderBy": [
{
"columnName": "loginName",
"direction": "Asc"
}
]
},
"domainId": Example:"keriodb://domain/908c1118-94ef-49c0-a229-ca672b81d965"
},
token)
try:
user_names = []
for user in users["result"]["list"]:
print(user["fullName"], " (", user["loginName"], ")", sep="")
user_names.append(user["fullName"])
call_method("Session.logout", {}, token)
return users
except KeyError:
print('Error: {}'.format(users['error']['message']))
call_method("Session.logout", {}, token)
return None

How to send data and custom headers using urllib2

Hi I am using urrlib2 to send some data and custom headers to a link. Am getting 500 internal server error. I have contacted the service, and they are saying the data(json data) is correct but there is some error in my python code. What am I doing wrong ?
Following is the code.
import urllib2,urllib
import json
PREPAYMENT_URL = "https://services.gharpay.in/rest/GharpayService/"
PREPAYMENT_USERNAME = "somename"
PREPAYMENT_PASSWORD = "somepass"
data = {
"customerDetails":{
"address": "ads",
"contactNo": "9663924147",
"email": "a#c.com",
"firstName": "akash",
"lastName": "deshpande",
"prefix": "Mr."
},
"orderDetails" : {
"pincode": "411036",
"clientOrderID": "21234",
"deliveryDate": "13-10-2013",
"orderAmount": "123",
"clientComments": "please be carefull",
"paymentMode": "Cash",
"productDetails": {
"productID": "21334",
"productQuantity": "1",
"unitCost": "123",
"productDescription": "tshirt"
},
"templateID": ""
},
}
def create(request):
function = 'createOrder'
url = PREPAYMENT_URL
url = url+ function
headers= {'username':PREPAYMENT_USERNAME,'password':PREPAYMENT_PASSWORD,'Content-type':'application/json'}
data1 = urllib.urlencode(data)
req = urllib2.Request(url,data1,headers)
try:
contents = urllib2.urlopen(req).read()
except urllib2.HTTPError as e:
error_message = e.read()
print error_message # this error message is being printed. It is showing 500 error.
Your code is perfect except for one teensy-weensy detail:
The header should be Content-Type, not Content-type.
Maybe try changing this header and let me know if it works!

Categories

Resources