简体   繁体   中英

Python wrapper for pricing API

I wrote a python wrapper for a pricing API. At the end of my code I make a method calls to the API endpoints. There are 4 different API endpoints. When I do a test run and hit the endpoints 3 out of the 4 endpoints return a JSON response except for the third one called "test3". Maybe its the way I formatted the URL response in my f-string? I have tried to format it differently but still keep getting this error.

Error here: enter image description here

import http.client
import urllib.request, urllib.parse, urllib.error
import json
import base64

 
def loadJson(response):
   body = response.read()
   if body == "" or body is None:
       print(("Empty response found with status " + str(response.status)))
       return {}
   else:
       return json.loads(body)
 
class data_pricing_client:
 
   def __init__(self, host, clientId, clientSecret):
       conn = http.client.HTTPSConnection("sso.lukka.tech")
       path = "/oauth2/aus1imo2fqcx5Ik4Q0h8/v1/token"
       encodedData = base64.b64encode(bytes(f"{clientId}:{clientSecret}", "ISO-8859-1")).decode("ascii")
       authHeader = "Basic " + encodedData
       headers = {
           "Authorization": authHeader,
           "Accept": "application/json",
           "Content-Type": "application/x-www-form-urlencoded"
       }
       params = urllib.parse.urlencode({
           "grant_type": "client_credentials",
           "scope": "pricing"
       })
 
       conn.request("POST", path, params, headers)
       response = conn.getresponse()
 
       if response.status != 200:
           raise ApiErrorException(response.status, "Failed to get access token")
 
       self.host = host
       self.accessToken = loadJson(response)["access_token"]
 
   def default_headers(self):
       return {
           "Content-Type": "application/json",
           "Accept": "application/json",
           "Authorization": "Bearer " + self.accessToken
       }
  
   def send_message(self,path):
       conn = http.client.HTTPSConnection(self.host)
       headers = self.default_headers()
       conn.request("GET", path, None, headers)
       response_json = loadJson(conn.getresponse())
       conn.close()
       return response_json
 
   def get_available_sources(self):
       path = "/v1/pricing/sources"
       return self.send_message(path)
 
   def get_source_details(self, sourceId):
       path = f"/v1/pricing/sources/{sourceId}/prices"
       return self.send_message(path)
 
   def get_latest_prices(self, sourceId, pairCodes=None, asOf=None, variances=False):
       query_params = {
           "pairCodes":pairCodes,
           "asOf":asOf
       }
       path = f"/v1/pricing/sources/{sourceId}/prices/{'/variances' if variances else ''}?{urllib.parse.urlencode({k: v for k, v in query_params.items() if v is not None})}"
       print(path)
       return self.send_message(path)
  
   def get_historical_prices(self, sourceId, pairCode, from_ts=None, to_ts=None, fill=None, limit=None, variances=False):
       query_params = {
           "from":from_ts,
           "to":to_ts,
           "fill": fill,
           "limit": limit
       }
       path = f"/v1/pricing/sources/{sourceId}/prices/pairs/{pairCode}{'/variances' if variances else ''}?{urllib.parse.urlencode({k: v for k, v in query_params.items() if v is not None})}"
       print(path)
       return self.send_message(path)
 
       
 
class ApiErrorException(Exception):
   def __init__(self, status, msg):
       self.msg = "Error " + str(status) + ": " + msg
   def __str__(self):
       return self.msg
 
if __name__ == '__main__':
   from pricing_api_creds import lukka_pricing
   c = data_pricing_client(**lukka_pricing)

   test1 = c.get_available_sources()
   test1 = c.send_message("/v1/pricing/sources")
   print(test1)

   test2 = c.get_source_details(3000)
   test2 = c.send_message("/v1/pricing/sources/")
   print(test2)

   test3 = c.get_latest_prices(3000)
   test3 = c.send_message("v1/pricing/sources/1000/prices")
   print(test3)
 
   test4 = c.get_historical_prices(1000, "XBT-USD",)
   test4=c.send_message("/v1/pricing/sources/1000/prices/pairs/XBT-USD")
   print(test4)

You can see that the error is thrown from the JSONDecoder. Possibilities are response is corrupted or the response is not a valid Json that can be mapped. Try logging the response to get an detail idea on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM