[Python] How to Authenticate Messages with Advanced Trade

This post is for anyone who is seeking help with setting up authentication on the Advanced Trade API.

I took the liberty of re-writing a functioning Advanced Trade authentication script using much of the same structure as the previous approved Coinbase Pro API Authentication Docs. I have not seen a similar solution elsewhere online and I do not prefer the solution given by the Coinbase Advanced Trade Authentication Docs.

This is an unofficial solution. Use at your own risk and test first. The only modificiations you will need to make is to place your public and secret key strings in place of '***' under the init function. Otherwise this is a fully-functioning copy-paste solution. Hopefully you are able to break apart the components enough to fit it to your code.

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

class CoinbaseAdvancedTradeAuth(AuthBase):
    def __init__(self):
        self.public_key = '***'
        self.secret_key = '***'

    def __call__(self, request):
        timestamp = str(int(time.time()))
        message= timestamp + request.method + request.path_url.split('?')[0] + request.body.decode()
        signature = hmac.new(self.secret_key.encode(), message.encode(), hashlib.sha256).hexdigest()
        # implicit 'utf-8' encoding

        request.headers.update({
            'CB-ACCESS-KEY': self.public_key,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-SIGN': signature,
            'Content-Type': 'application/json'
        })
        return request

auth_access = CoinbaseAdvancedTradeAuth()
api_url = 'https://api.coinbase.com/api/v3/brokerage/'

endpoint = 'accounts'
method = 'GET'
order = None

response = requests.request(method,api_url+endpoint,json=order,auth=auth_access)
print(response.status_code) # 200
print(response.json()) # Output

## Example Where Order is Not None ##

order = {
    'type': 'market',
    'side': 'buy',
    'funds': '500.00',
    'product_id': 'ETH-USD'
    }

## Good Luck!

EDIT

request.path_url.split('?')[0] is a necessary component of this code. See the linked comment from another post below.

1 Like

Hello @tripster202! Welcome to the Coinbase Developer Forum! We appreciate your time and effort for making such a script to help this forum community and to those who are having an error when setting up authentication to Advanced Trade API. We’re looking forward to more helpful insights from you on this forum community! Have a nice day!