Noob questions here but I am trying to place an order using Questrade API. This is my python script so far:
import requests
uri = "https://api01.iq.questrade.com/v1/accounts/<id>/orders"
headers = {'Authorization': 'Bearer <my_bearer>'}
r = requests.post(uri, headers=headers, accountNumber=31455565, symbolId=8049, quantity=10, icebergQuantity=1, limitPrice=10, isAllOrNone=True, isAnonymous=False, timeInForce="GoodTillCanceled", primaryRoute="Auto", secondaryRoute="Auto", orderType="Limit", action="Buy")
response = r.json()
print (response)
This is a sample request from Questrade's webpage:
http://www.questrade.com/api/documentation/rest-operations/order-calls/accounts-id-orders
This is the error I'm getting: TypeError: request() got an unexpected keyword argument 'quantity'
Any help will be highly appreciated. Thankss!
All the parameters of your request (accountNumber, symbolId, quantity, ...) are parameters for Questrade API, not for the post method of request. You need to set them in the body of the request, in json format: http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests
import requests
uri = "https://api01.iq.questrade.com/v1/accounts/<id>/orders"
headers = {'Authorization': 'Bearer <my_bearer>'}
payload = {'accountNumber': 31455565, 'symbolId': 8049, 'quantity': 10, 'icebergQuantity': 1, 'limitPrice': 10, 'isAllOrNone': True, 'isAnonymous': False, 'timeInForce': "GoodTillCanceled", 'primaryRoute': "Auto", 'secondaryRoute': "Auto", 'orderType': "Limit", 'action': "Buy"}
r = requests.post(uri, headers=headers, json=payload)
response = r.json()
print (response)
I created a simple python wrapper to access the questrade API. https://github.com/antoineviscardi/questradeapi
Using it you would get something like this:
import questradeapi as qapi
sess = qapi.Session(<your_bearer>)
sess.post_order(31455565, 8049, 10, 1, 10, None, True, False, "Limit",
"GoodTillCanceled", "Buy", "Auto", "Auto)
Related
This is my code to extract player data from an endpoint containing basketball data for a Data Science project.NOTE: I changed the name of the actual API key I was given since it's subscription. And I change the username/password because for privacy purposes. Using the correct credentials, I wouldn't receive a syntax error but the status code always returns 401. Since it wasn't accepting the API key, I added my account username, password, and the HTTP authentication header as well, but the status code still returns 401.
In case this is relevant, this is the website's recommendation in the developer portal: **The API key can be passed either as a query parameter or using the following HTTP request header.
Please let me know what changes I can make to my code. Any help is appreciated.
Ocp-Apim-Subscription-Key: {key}**
PS: My code got fragmented while posting this, but it is all in one function.
def getData():
user_name = "name#gmail.com"
api_endpoint = "https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7"
api_key = "a45;lkf"
password = "ksaljd"
header = "Ocp-Apim-Subscription-Key"
PARAMS = {'user': user_name, 'pass': password, 'header': header, 'key': api_key}
response = requests.get(url = api_endpoint, data = PARAMS)
print(response.status_code)
file = open("Data.csv", "w")
file.write(response.text)
file.close()
def _get_auth_headers() -> dict:
return {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': "`Insert key here`"
}
api_endpoint = "https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7"
PARAMS = {
# Your params here
}
response = requests.get(
api_endpoint,
headers=_get_auth_headers(),
params=PARAMS
)
Instead of just a string, you need to pass dict in the headers parameter and auth param exist so you can use it as follow:
def getData():
[...]
header = {
"Ocp-Apim-Subscription-Key": api_key
}
[...]
response = requests.get(url = api_endpoint, data = PARAMS, headers=header, auth = (user_name, password))
According to the API documentation you don't need to provide email and password. You're only need to add your API Key to header:
import requests
r = requests.get(url='https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7', headers={'Ocp-Apim-Subscription-Key': 'API_KEY'})
print(r.json())
Output:
[{
'StatID': 768904,
'TeamID': 25,
'PlayerID': 20000788,
'SeasonType': 1,
'Season': 2020,
'Name': 'Tim Hardaway Jr.',
'Team': 'DAL',
'Position': 'SF',
'Started': 1,
'FanDuelSalary': 7183,
'DraftKingsSalary': 7623,
'FantasyDataSalary': 7623,
...
I am writing an API request that gives paginated results.
To get results from the next page I need to take a value of 'next_page_cursor' and put it in the parameters of my request that is a dictionary.
This is what I have tried so far. Need to keep changing cursor value in params until there are no more pages.
params = {'title': 'Cybertruck',
'per_page':100,
'cursor': '*'
}
response = requests.get("https://api.aylien.com/news/stories",
headers = headers, params=params).json()
if "next_page_cursor" in response:
cursor = response["next_page_cursor"]
You can use a while loop:
params = {
"title": "Cybertruck",
"per_page": 100,
"cursor": "initial_cursor"
}
def make_request(params)
return requests.get("https://api.aylien.com/news/stories",
headers=headers, params=params).json()
result = []
response = make_request(params)
while "next_page_cursor" in response:
params["cursor"] = response["next_page_cursor"]
response = make_request(params)
result.append(response["information_your_are_interested_in"])
I am trying to push this JSON into the data request, but I tink that the format is not passing in correctly. I keep getting a bad request. I know this request works when I put it in my REST client.
Am I not formating JSON correctly forthe post request?
import json
import requests
import pprint
json_obj1 = """
'dateStart': '2019-11-25T00:00:00.000Z',
'dateEnd': '2019-11-26T23:59:59.999Z',
'subscriptions':
{
'category': {
'name': 'Accessories',
'childrenUuids': [],
'uuid': 'c35cb71f-5dcd-4ae3-86b3-d642208ad7f5'
},
'geography': {
'uuid': 'ad63a8ff-f636-44e1-9fe0-1d1664dfd530',
'name': 'New York',
'geoType': 'METRO',
'childrenUuids': []
}
}
"""
s = requests.session()
s.headers = {'Content-Type': 'application/json'}
infra_link = <someURL>
infra_content = s.request(
method='POST', url=infra_link, data=json_obj1, headers=s.headers,
).text
RESULT:
{"timestamp":"2019-11-27T16:22:49.885+0000","status":400,"error":"Bad '
'Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Bad '
'Request","path":"/index"}')
Try to change this
infra_content = s.request(
method='POST', url=infra_link, data=json_string1, headers=s.headers,
).text
To this
infra_content = s.request(
method='POST', url=infra_link, data=json.dumps(json_string1), headers=s.headers,
).text
Added json.dump() in request data parameter.
You're not passing a json string as your data argument, you're passing a dict.
Try the following:
infra_content = s.request(
method='POST', url=infra_link, data=json.dumps(json_string1), headers=s.headers,
).text
Your variable json_string1 is badly named, which might be confusing you. As you can see, it's not a string but a dict (and json is a specific string format, but a string format nonetheless). json.dumps (which stands for dump as string) is used to serialize a dict into a json string.
I'm connecting to API which has 500 rows limit per call.
This is my code for a single API call (Works great):
def getdata(data):
auth_token = access_token
hed = {'Authorization': 'Bearer ' + auth_token, 'Accept': 'application/json'}
urlApi = 'https://..../orders?Offset=0&Limit=499'
datar = requests.get(urlApi, data=data, headers=hed, verify=True)
return datar
Now I want to scale it up so it will get me all the records.
This is what I tried to do:
In order to make sure that I have all the rows, I must iterate until there is no more data:
get 1st page
get 2nd page
merge
get 3rd page
merge
etc...
each page is an API call.
This is what I'm trying to do:
def getData(data):
auth_token = access_token
value_offset = 0
hed = {'Authorization': 'Bearer ' + auth_token, 'Accept': 'application/json'}
datarALL = None
while True:
urlApi = 'https://..../orders?Offset=' + value_offset + '&Limit=499'
responsedata = requests.get(urlApi, data=data, headers=hed, verify=True)
if responsedata.ok:
value_offset = value_offset + 499
#to do: merge the result of the get request
datarALL= datarALL+ responsedata (?)
# to do: check if response is empty then break out.
return datarALL
I couldn't find information about how I merge the results of the API calls nor how do I check if I can break the loop.
Edit:
To clear what I'm after.
I can see the results of the API call using:
logger.debug('response is : {0}'.format(datar.json()))
What I want to be able to do:
logger.debug('response is : {0}'.format(datarALL.json()))
and it will show all results from all calls. This requires generate API calls until there is no more data to get.
This is the return sample of API call:
"offset": 0,
"limit": 0,
"total": 0,
"results": [
{
"field1": 0,
"field2": "string",
"field3": "string",
"field4": "string"
}
]
}
In this case, you are almost correct with the idea.
is_valid = True
while is_valid:
is_valid = False
...
...
responsedata = requests.get(urlApi, data=data, headers=hed, verify=True)
if responsedata.status_code == 200: #Use status code to check request status, 200 for successful call
responsedata = responsedata.text
value_offset = value_offset + 499
#to do: merge the result of the get request
jsondata = json.loads(responsedata)
if "results" in jsondata:
if jsondata["results"]:
is_valid = True
if is_valid:
#concat array by + operand
datarALL = datarALL + jsondata["results"]
As I don't know if "results" still exists when the data ran out, so I checked both level.
I am trying to update a value in REST API of openhab using requests.put in Python. But I am getting error 404.
My code is copied below
import requests
import json
from pprint import pprint
TemperatureA_FF_Office = 20
headers = {'Content-type': 'application/json'}
payload = {'state' : TemperatureA_FF_Office}
payld = json.dumps(payload)
re = requests.put("http://localhost:8080/rest/items/TemperatureA_FF_Office
/state/put", params= payld, headers = headers)
pprint(vars(re))
The error code I am getting is
{'_content': '',
'_content_consumed': True,
'connection': <requests.adapters.HTTPAdapter object at 7fd3b55ec9d0>,
'cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>,
'elapsed': datetime.timedelta(0, 0, 4019),
'encoding': None,
'history': [],
'raw': <urllib3.response.HTTPResponse object at 0x7fd3b55ecd90>,
'reason': 'Not Found',
'request': <PreparedRequest [PUT]>,
'status_code': 404,
'url': u'http://localhost:8080/rest/items/TemperatureA_FF_Office/state/put?state=21.0'}
Is this the way to use requests.put? Please help.
Try something along these lines:
import requests
req = "http://localhost:8080/rest/items/YOUR_SENSOR_HERE/state"
val = VARIABLE_WITH_YOUR_SENSOR_DATA
try:
r = requests.put(req,data=val)
except requests.ConnectionError as e:
r = "Response Error"
print e
print r
This is a massively simplified version of what I'm using for some of my presence detection and temperature scripts.
The printing of 'r' and 'e' is useful for debug purposes and can be removed once you've got your script working properly.