Coinbase Pro post request - Malformed JSON

609 views Asked by At

I am currently working on a piece of software that automates trading with Coinbase Pro. I am using the request library and have code that works for "GET" requests but fails for "POST"s. I was wondering if someone could help me understand what is going on.

This is the code I am currently using:

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

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 '')
    message = message.encode('utf-8')
    hmac_key = base64.b64decode(self.secret_key)
    signature = hmac.new(hmac_key, message, hashlib.sha256)
    signature_b64 = base64.b64encode(signature.digest())

    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

When used with the following:

api_url = "https://api.pro.coinbase.com/"
auth = CoinbaseExchangeAuth("*****", "*****", "*****")
request = requests.get(api_url + "accounts", auth=auth).json()

It works perfectly. But as soon as I try:

order = {'size': '0.0001', 'price': '100', 'side': 'sell', 'product_id': 'BTC-EUR'}
request = requests.post(api_url + "orders", data=order, auth=auth)
print(request.json())

I get {'message': 'malformed json'}. I figure it has to do with the (request.body or '') but I can't find a fix for it.

Thank you anyone for help!

1

There are 1 answers

0
μMμ On BEST ANSWER

In the end, the problem was request = requests.post(api_url + "orders", data=order, auth=auth) - request = requests.post(api_url + "orders", data=json.dumps(order), auth=auth) solves the issue