11import os
22
3- from dataclasses import dataclass
4- from typing import Dict
5-
63import requests
74from requests .auth import HTTPBasicAuth
85from requests .exceptions import JSONDecodeError
96
7+ from .exceptions import PicketAPIException
8+ from .helpers import is_successful_status_code , snake_to_camel_keys
9+ from .types import (
10+ NonceResponse ,
11+ AuthorizedUser ,
12+ AuthResponse ,
13+ TokenOwnershipResponse ,
14+ )
15+
1016API_VERSION = "v1"
1117API_BASE_URL = os .path .join ("https://picketapi.com/api/" , API_VERSION )
1218
1319
14- def is_successful_status_code (status_code ):
15- return status_code >= 200 and status_code < 300
16-
17-
18- class PicketAPIException (Exception ):
19- def __init__ (self , msg : str , code : str ):
20- super ().__init__ (msg )
21- self .msg = msg
22- self .code = code
23-
24- def __str__ (self ):
25- return self .msg
26-
27-
28- @dataclass
29- class NonceResponse :
30- nonce : str
31- statement : str
32- format : str
33-
34- @classmethod
35- def from_dict (cls , d ):
36- return cls (d ["nonce" ], d ["statement" ], d ["format" ])
37-
38-
39- TokenBalances = Dict [str , Dict [str , str ]]
40-
41-
42- @dataclass
43- class AuthorizedUser :
44- chain : str
45- wallet_address : str
46- display_name : str
47- token_balances : TokenBalances
48-
49- @classmethod
50- def from_dict (cls , d ):
51- return cls (
52- d ["chain" ], d ["wallet_address" ], d ["display_name" ], d ["token_balances" ]
53- )
54-
55-
56- @dataclass
57- class AuthResponse :
58- access_token : str
59- user : AuthorizedUser
60-
61- @classmethod
62- def from_dict (cls , d ):
63- user = AuthorizedUser .from_dict (d ["user" ])
64- return cls (d ["accessToken" ], user )
65-
66-
67- @dataclass
68- class TokenOwnershipResponse :
69- allowed : bool
70- walletAddress : str
71- token_balances : TokenBalances
72-
73- @classmethod
74- def from_dict (cls , d ):
75- return cls (d ["allowed" ], d ["walletAddress" ], d ["token_balances" ])
76-
77-
7820class Picket :
7921 def __init__ (self , api_key : str , ** kwargs ):
8022 self .api_key = api_key
@@ -93,14 +35,20 @@ def post_request(self, path: str, **kwargs):
9335 auth = HTTPBasicAuth (self .api_key , "" )
9436 headers = self .headers ()
9537
96- req = requests .post (url , auth = auth , headers = headers , data = kwargs )
38+ # transform keys to camelCase
39+ req = requests .post (
40+ url , auth = auth , headers = headers , json = snake_to_camel_keys (kwargs )
41+ )
9742 try :
9843 data = req .json ()
9944 except JSONDecodeError :
10045 raise Exception (req .text )
10146
10247 if not is_successful_status_code (req .status_code ):
103- raise PicketAPIException (data ["msg" ], data ["code" ])
48+ if "msg" not in data :
49+ raise Exception (data )
50+ # msg is required, code is optional
51+ raise PicketAPIException (data ["msg" ], data .get ("code" , None ))
10452
10553 return data
10654
0 commit comments