Request for help with API signature

I have an application that uses the Coinbase Pro API. I’m trying to migrate the code to Advanced Trading and it’s not going well. The API documentation is not great and the examples don’t work.

I’m trying to get a basic API call signed and it’s not working.

import json
import hmac
import hashlib
import time
import requests
import base64
from requests.auth import AuthBase

API_KEY = '<removed>
API_SECRET = b'<removed>'


class CoinbaseWalletAuth(AuthBase):
    def __init__(self, api_key, secret_key):
        self.api_key = api_key
        self.secret_key = secret_key

    def __call__(self, request):
        timestamp = str(int(time.time()))
        body = (request.body or b"").decode()
        message = f"{timestamp}{request.method}{request.path_url}{body}"
        hmac_key = base64.b64decode(self.secret_key)
        signature = hmac.new(hmac_key, message.encode(), hashlib.sha256)
        signature_b64 = base64.b64encode(signature.digest()).decode()

        request.headers.update(
            {
                "CB-ACCESS-SIGN": signature_b64,
                "CB-ACCESS-TIMESTAMP": timestamp,
                "CB-ACCESS-KEY": self.api_key,
                "Content-Type": "application/json",
            }
        )

        return request


api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth(API_KEY, API_SECRET)

r = requests.get(api_url + 'user', auth=auth)
print(r.text)

The response is:
{“errors”:[{“id”:“authentication_error”,“message”:“invalid signature”}]}

Is anyone able to spot the issue above and advise on how to fix it?

You don’t need to decode secret key and also you don’t need to encode signature.

Do you mean like this?

    timestamp = str(int(time.time()))
    body = (request.body or b"").decode()
    message = f"{timestamp}{request.method}{request.path_url}{body}"
    signature = hmac.new(self.secret_key, message.encode(), hashlib.sha256)

That doesn’t work. It now says…
TypeError: key: expected bytes or bytearray, but got ‘str’

Do you have a working example you can share?

I still don’t have a working Python example to sign and API request on Advanced Trading. I am unable to migrate my app(s) from Coinbase Pro until I have found a solution. If someone can provide a basic example to sign and execute an API request in Python on Advanced Trading that would be very helpful. Thanks

How does nobody have a working example of this? :smiley: