Making HTTP Requests and processing JSON Response in python

We can make HTTP GET requests with python libraries like urllib , httplib and request.
In the below example we will make an API call with requests library and process
the JSON data returned from server.

import requests
import json

requests.packages.urllib3.disable_warnings()

base_url = 'https://api.binance.com/api/v1/ticker/price'
full_url= 'https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT'

PARAMS = {'symbol':'BTCUSDT'}

#Request with parameters
response = requests.get( url = base_url , params = PARAMS , verify = False )
print(response)
#print(response.text)
#print(response.status_code)
data = response.json()
print(data)

#Request with full API request
resp = requests.get(full_url,verify=False)
temp_data = json.dumps(resp.json())
data_json = json.loads(temp_data)

print( data_json["symbol"] + " : " + data_json["price"] )

Here we are fetching the current cryptocurrency price from binnace API calls. First request is made with the full API url . The second call is made y providing the GET parameters to the api end point. Both the calls return same data. The response contains both response_code ( response.status_code ) and response_data ( response.text )

Output of the program.

<Response [200]>
{'symbol': 'BTCUSDT', 'price': '56127.48000000'}
BTCUSDT : 56149.99000000

References:

  • https://www.w3schools.com/python/ref_requests_get.asp
  • https://www.dataquest.io/blog/python-api-tutorial/

Leave a Reply