I’m really new to this and it is probably obvious but I can’t see to figure out why this doesn’t work, i just get <Response [401]> key name and secret is confirmed many times:
import jwt
from cryptography.hazmat.primitives import serialization
import time
import secrets
import requests
key_name = "organizations/KEY/apiKeys/KEY"
key_secret = "-----BEGIN EC PRIVATE KEY-----*MYKEY*-----END EC PRIVATE KEY-----\n"
request_method = "GET"
request_host = "api.coinbase.com"
request_path = "/api/v3/brokerage/accounts"
service_name = "retail_rest_api_proxy"
def build_jwt(service, uri):
private_key_bytes = key_secret.encode('utf-8')
private_key = serialization.load_pem_private_key(private_key_bytes, password=None)
jwt_payload = {
'sub': key_name,
'iss': "coinbase-cloud",
'nbf': int(time.time()),
'exp': int(time.time()) + 120,
'aud': [service],
'uri': uri,
}
jwt_token = jwt.encode(
jwt_payload,
private_key,
algorithm='ES256',
headers={'kid': key_name, 'nonce': secrets.token_hex()},
)
return jwt_token
def main():
uri = f"{request_method} {request_host}{request_path}"
jwt_token = build_jwt(service_name, uri)
# Define the endpoint for account balance
balance_url = "https://api.coinbase.com/v2/accounts"
# Define the headers with the JWT token
headers = {
"Authorization": f"Bearer {jwt_token}",
"Content-Type": "application/json"
}
# Send a GET request to retrieve account information
response = requests.get(balance_url, headers=headers)
print(response)
if __name__ == "__main__":
main()