2

Trying to fetch currency quotes from Oanda's API. Here is the code I have:

s = requests.Session()
url = "https://stream-fxpractice.oanda.com/v1/prices"
headers = {'Authorization': 'Bearer ' + access_token}
params = {'instruments': pairs_oanda, 'accountId': account_id}
resp = s.get(url, headers=headers, params=params, stream=True)

The access_token and account_id are authentication for the API. When I supply one currency pair, for instance "EUR_USD", to pairs_oanda it works fine, resulting in the following url:

https://streamfxpractice.oanda.com/v1/prices?instruments=GBP_USD&accountId=*******

However, when I supply a list of currency pairs, for instance

["EUR_USD", "GBP_USD"]

to pairs_oanda, I get this URL:

https://stream-fxpractice.oanda.com/v1/prices?instruments=EUR_USD&instruments=GBP_USD&accountId=*******

However, what I need the url to look like to properly access the API is this:

https://stream-fxpractice.oanda.com/v1/prices?instruments=EUR_USD%2CGBP_USD&accountId=*******

Is there anyway to get Requests to parse the list differently?

1 Answer 1

4

The API wants you to use a comma to separate the currency pairs. You'll have to do so yourself; use str.join() here:

pairs_oanda = ["EUR_USD", "GBP_USD"]
params = {'instruments': ','.join(pairs_oanda), 'accountId': account_id}

The %2C character sequence is a , encoded to URL encoding:

>>> from urlparse import unquote
>>> unquote('%2C')
','

and requests takes care of quoting for you provided you give it the unquoted parameter values:

>>> from requests import Request
>>> url = "https://stream-fxpractice.oanda.com/v1/prices"
>>> pairs_oanda = ["EUR_USD", "GBP_USD"]
>>> params = {'instruments': ','.join(pairs_oanda), 'accountId': 'foobarbaz'}
>>> r = Request('GET', url, params=params)
>>> r.prepare().url
'https://stream-fxpractice.oanda.com/v1/prices?instruments=EUR_USD%2CGBP_USD&accountId=foobarbaz'
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, there we go. Bit new to the website, as you can probably tell. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.