-2

Im using requests with the Bitmex API, im trying to get the lastPrice value from the get requests.

I stored the response into a variable, tried a few ways into pulling the lastPrice value including print(value[1]) print(value['lastPrice'], all of which didnt work, ive been reading for a while now on here and cant seem to find the correct working way to get the value. sorry if this is asked all the time.

import requests

r = requests.get('https://www.bitmex.com/api/v1/instrument?symbol=XBT&columns=lastPrice&count=1&reverse=true')

value = r.text
print(value)
#print(value[1]) 
#print(value['lastPrice'])

The output from this is

[{"symbol":"XBTUSD","timestamp":"2019-10-03T22:37:13.085Z","lastPrice":8190.5}]

using value[1] just returns the first letter in the print. So for ex [1] returns { and using ['lastPrice'] returns TypeError: string indices must be integers

  • Possible duplicate of [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Henry Henrinson Oct 03 '19 at 23:39

1 Answers1

1

Your return value is JSON string, you can use response.json() to decode it to python dict. Result contains list with single element, so you should refer to first element of list and then get value from dict by key:

r = requests.get('https://www.bitmex.com/api/v1/instrument?symbol=XBT&columns=lastPrice&count=1&reverse=true')

value = r.json()
print(value[0]['lastPrice'])
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
  • ty very much i tried converting it to json and using the same ways to get a value but i didnt think of adding the [0] before hand, figured this was an easy fix. –  Oct 03 '19 at 22:43
  • yep i accepted sorry it said i had to wait 10 mins since it was a new account ty for the help. –  Oct 04 '19 at 02:29