I am building software to track my portfolio and trade from. I am currently trying to get my account positions from the TD API.
acct_endpt = 'https://api.tdameritrade.com/v1/accounts/{accountId}'
full_url_acct = acct_endpt.format(accountId='accountId')
account = requests.get(url=full_url_acct,
params={'fields' : 'positions', 'apikey' : 'apikey'})
acct_content = json.loads(account.content)
My code above is returning me the following error:
json.decoder.JSONDecodeError: Expecting value: line 2 column 11 (char 11)
Update:
I removed the line containing json.loads() as it was returning a 401 error [An error message indicating the caller must pass a valid AuthToken in the HTTP authorization request header]. I must be passing the fields and apikey parameters incorrectly. How would the syntax look to properly pass these parameters?
Your parameters look correct, but I think the url formatting isn't doing what you want. Instead, you can format your url using f-string as follows:
accountId = "ACCOUNT_ID"
acct_endpt = f"https://api.tdameritrade.com/v1/accounts/{accountId}"
Related
I'm trying to send a request to a WSDL WebServices. According to documentation, the requests must be formatted in XML.
I'm using Python and Zeep module. The operation a want to use is called 'Consulta' and parameters are called 'Comercio' and 'NumPedido' (first one is numeric type and second is alphanumeric).
The code I've tried is the following:
from zeep import Client, Settings
settings = Settings(strict=False, xml_huge_tree=True)
client = Client('https://testws.punto-web.com/wcfadproc/srvproceso.svc?wsdl', settings=settings)
request_data = { 'Comercio': '8004749', 'NumPedido': '7030510'}
client.service.Consulta_Marca(**request_data)
But this gives me error TypeError: {http://tempuri.org/}Consulta_Marca() got an unexpected keyword argument 'NumPedido'. Signature: `xml: xsd:string`
Can anyone give me some advice about fixing this? Because seems that the operation is correct, but do not why the parameters are bad.
EDIT:
I've tried this little new code
from zeep import Client, xsd, Settings
settings = Settings(strict=False, xml_huge_tree=True)
client = Client('https://testws.punto-web.com/wcfadproc/srvproceso.svc?wsdl', settings = settings)
parameters = xsd.Element(
'Consulta',
xsd.ComplexType([
xsd.Element(
'Comercio', xsd.Integer()
),
xsd.Element(
'NumPedido', xsd.String()
)
])
)
parameters_values = parameters( Comercio=8004749, NumPedido='7030510')
operation = client.service.Consulta_Marca(parameters_values)
operation
This gives me another error
The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'Consulta_Marca'. End element 'xml' from namespace 'http://tempuri.org/' expected. Found element 'Comercio' from namespace ''. Line 2, position 465
But think I'm closer because if I execute
client.service.Consulta_Marca(parameters), I get a valid response, but with null values because no parameters values were passed.
Please some help!
I'm making an api call, and trying to store its response in Postgres using Django models.
Here's what I have been doing:
response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'})
response_data = json.loads(response.content.decode('utf-8'))
#handler is a object of a model
handler.api_response = response_data
handler.save()
But this used to fail, when my json had fields like 'field_name': '\x00\x00\x00\x00\x00'. It used to give following error :
DataError at /api/booking/reprice/
unsupported Unicode escape sequence
LINE 1: ... NULL, "api_status" = 0, "api_response" = '{"errorRe...
^
DETAIL: \u0000 cannot be converted to text.
CONTEXT: JSON data, line 1: ..."hoursConfirmed": 0, "field_name":...
How i tried to resolve this is by using the following:
response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'})
response_data = json.loads(response.content.decode('utf-8'))
#handler is a object of a model
handler.api_response = json.loads(json.dumps(response_data).encode("unicode-escape").decode())
handler.save()
The initial issue was solved then. But recently, when i got a field with value 'field2_name': 'Hey "Whats up"'. This thing failed by giving error:
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 143 (char 142)
Probably because json.loads() got confused with " inside the value as an enclosing " and not an escaped ".
Now, If i print the initial response just after json.loads(response.content.decode('utf-8')) statement, it shows the field as \x00\x00\x00\x00\x00.
But output of following code:
response = requests.post(url='some.url.com', data=json.dumps(data), headers={'some': 'header'})
response_data = json.loads(response.content.decode('utf-8'))
print(json.dumps(response_data))
This shows the field as \\u0000\\u0000\\u0000\\u0000\\u0000.
How does \x00 change to \\u0000
And how do i save this field into postgres tables ?
This is what i could think of.
json.loads(json.dumps(response_data).replace('\\u0000',''))
To add this statement before saving to postgres.
Is there a better way ?
Is the code response_data = json.loads(response.content.decode('utf-8')) wrong ? Or causing not to escape that particular character ?
FWIW, I recently ran into this and your proposed solution also worked for me. I think it's probably the simplest way to deal with it. Apparently this is the only character that can't go into a Postgres JSON column.
json.loads(json.dumps(response_data).replace('\\u0000',''))
So I've got a python google cloud function running from an HTTP trigger. For some reason I have to put in a parameter (myfakeinput) in order to trigger this function. I can't find any documentation to see what the function is actually and what formatting is required. I've tried adding in a second parameter but have had no success and get a 500 error with nothing in the issue log. I've also tried to return 'myfakeinput' but that also ends up causing a 500 error.
Does anyone know what the value of the parameter being passed in looks like or what its formatting is so I can actually pass in a parameter?
Thanks!
I would recommend you take a look at this documentation here.
from flask import escape
def hello_http(request):
"""HTTP Cloud Function.
Args:
request (flask.Request): The request object.
<http://flask.pocoo.org/docs/1.0/api/#flask.Request>
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
<http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
"""
request_json = request.get_json(silent=True)
request_args = request.args
if request_json and 'name' in request_json:
name = request_json['name']
elif request_args and 'name' in request_args:
name = request_args['name']
else:
name = 'World'
return 'Hello {}!'.format(escape(name))
So "flask" make available to your code the object "request". In the above code, a list of the arguments is then extracted from the object and put into the variable "request_args".
request_json = request.get_json(silent=True)
request_args = request.args
Hope this helps,
Frederic
I am running the following:
import geopy
geolocator = geopy.geocoders.OpenMapQuest(api_key='my_key_here')
location1 = geolocator.geocode('Madrid')
where my_key_here is my consumer key for mapquest, and I get the following error:
GeocoderInsufficientPrivileges: HTTP Error 403: Forbidden
Not sure what I am doing wrong.
Thanks!
I've also tried the same with the same result. After checking the Library, I found out, that the error is referring to the line, where the request ist build and it seems, that the API Key is not transmitted. If you add no key in the init statement, the api_key='' so I tried to change the line 66 in my own Library of the file: https://github.com/geopy/geopy/blob/master/geopy/geocoders/openmapquest.py to my key.
Still no success! The key itself works, I've tested it with calling the URL that is also called in the Library:
http://open.mapquestapi.com/nominatim/v1/search.php?key="MY_KEY"&format=json&json_callback=renderBasicSearchNarrative&q=westminster+abbey
no idea why this isn't working…
Cheers.kg
I made slight progress with fixing this one. I was able to get the query written correctly, but its the json parsing that kind of have me stumped. Maybe someone knows. I know the url is being sent correctly (I checked it in the browser and it returned a json object). Maybe someone knows how to parse the returned json object to get it to finally work.
Anyways, I had to go in the openmapquest.py source code, and starting from line 66, I made the following modifications:
self.api_key = api_key
self.api = "http://www.mapquestapi.com/geocoding/v1/address?"
def geocode(self, query, exactly_one=True, timeout=None): # pylint: disable=W0221
"""
Geocode a location query.
:param string query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
.. versionadded:: 0.97
"""
params = {
'key': self.api_key,
'location': self.format_string % query
}
if exactly_one:
params['maxResults'] = 1
url = "&".join((self.api, urlencode(params)))
print url # Print the URL just to make sure it's produced correctly
Now the task remains to get the _parse_json function working.
I'm trying to remove invalid GCM Tokens from my database after they failed in a broadcast request.
I send it via:
payload = {
"registration_ids": gcm_keys,
"data": messageData
}
headers = {
'Content-type': 'application/json',
'Authorization': Message_Broker.api_key
}
try:
return requests.post(Message_Broker.host, data=json.dumps(payload), headers=headers)
Lets say I try to send a message to:
gcm_keys = ['daöodaeöoijiö','12345','fwiorjpfwj'] # Lets pretend the second one is a valid token
From the content of the response object I get a dict like this:
response_results = [{u'error': u'InvalidRegistration'}, {u'registration_id': u'1234567', u'message_id': u'0:14339323424213768%540eeb39f9fd7aed'}, {u'error': u'InvalidRegistration'}]
To find out which tokens failed I made a set substraction with a list comprehension:
failed_keys = list(set(gcm_keys) - set([r.get('registration_id') for r in response_results]))
This should give me back only the tokens which produced an error.
My first question is, is there a more common way to do so or any kind of best practice?
Second question is, as you can see in the response_results and the gcm_keys, the valid token is not returned. Instead a kinda similar token is given back.
I did not find any on this. Why do I get a different token back?
-> Just found out that in case I get a different token back, I should replace the old one. That leads to another question. When I send to several tokens, how can I find out to which gcm token in the request this returned token belongs?
Is the order in the results always the same as in the request?
The response body's results parameter should have an array of objects that are listed in the same order as the request. Please refer here.