Search code examples
pythonapirestcoinbase-api

when connecting to coinbase (and coinbase sandbox) getting {'message': 'Invalid API Key'} errors with Python code


I am using the following demo code (written in Python 3.x) to attempt to connect to the Coinbase Sandbox. Below is the code I have been following. I keep getting {'message': 'Invalid API Key'} errors. I have created API keys twice on the sandbox site: https://public.sandbox.pro.coinbase.com/ but nothing is working.

What am I doing wrong? Any help, hints or advice would be appreciated.

TIA

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

# Before implementation, set environmental variables with the names API_KEY and API_SECRET

APIKEY = 'XXXXXXX-API'
API_PASS = 'rXXd0XX8XX'
API_SECRET = b'h2IUKbXXXXXXXXXXKL2d9XXXXXXXXXXWde5u+zcXXXXXXXXXXXXGJ8YqD8TXXXXXXXXXXXXXXX3dqM8pXXXXX8w=='

# Create custom authentication for Exchange
class CoinbaseExchangeAuth(AuthBase):
    def __init__(self, api_key, secret_key, passphrase):
        self.api_key = api_key
        self.secret_key = secret_key
        self.passphrase = passphrase

    def __call__(self, request):
        timestamp = str(time.time())
        message = timestamp + request.method + request.path_url + (request.body or b'').decode()
        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,
            'CB-ACCESS-PASSPHRASE': self.passphrase,
            'Content-Type': 'application/json'
        })
        return request

api_url = 'https://api-public.sandbox.pro.coinbase.com/'
auth = CoinbaseExchangeAuth(APIKEY, API_SECRET,  API_PASS)


# Get accounts
r = requests.get(api_url + 'accounts', auth=auth)
print(r.json())
# [{"id": "a1b2c3d4", "balance":...

# Place an order
order = {
    'size': 1.0,
    'price': 1.0,
    'side': 'buy',
    'product_id': 'BTC-USD',
}
r = requests.post(api_url + 'orders', json=order, auth=auth)
print(r.json())

Solution

  • My mistake. Was not using the right number for the API Keyenter image description here