Generating Request Signatures

In order to make an authenticated request to the SnapTrade API, you will need to generate a signature for each request that proves you hold the consumer key that was created for you.

Steps to generate a signature

In order to create the signature, you will need to start by constructing the signature content, which is a string that contains all the relevant request information that needs to be signed. The signature content is a serialized JSON object that is rendered in a specific, non-ambiguous way.

Once you have defined the signature content, you then use your consumer key to produce a cryptographic digest of the signature content.

Finally, you convert the digest into its Base64 representation and attach it to the request in the Signature header. This signature is sufficient for SnapTrade to be able to verify that the entire request was generated by you and not modified in transit.

At a high level, here are the steps

  1. Prepare the signature content, which will be signed in the next step.
  2. Sign the signature content (encoded as UTF-8) with HMAC-SHA256 using your consumer key.
  3. Include the Base64 encoding of the signed content as the Signature header.



Use the consumer key provided by SnapTrade to sign the request (not the example included here).

How to prepare the signature content

The signature content is a JSON object with 3 required key-value pairs:

  • content: Content which is passed along as the request body. Set this value to null for empty request bodies (for example, GET requests or POST requests with no body).
  • path: The URL path for the request.
  • query: The exact query param string that is included in the request. (ex: "clientId=PASSIVTEST&timestamp=1635790389"

After creating the JSON object with all the required information, it must be rendered as a flat string so that it can be signed. The JSON spec has some flexibility on whitespace, but cryptographic digests do not. For example, while the following two JSON strings would be parsed to result in the same JSON object, they would NOT produce the same cryptographic digest:

  • {"hello":"world","blue":"moon"} <-- this is the correct format to use for SnapTrade
  • {"hello": "world", "blue": "moon"}

As a result, we need to be very specific about how to render the signature content JSON object as a flat string. The requirements are as follows:

  1. Sort keys alphabetically.

  2. Remove any extra whitespace characters from the signed content.

  3. Render as a UTF-8 encoded string.

Sample signature code

Here are a few examples of how to produce the signature in several languages. If your language isn't included here, contact SnapTrade support and we will help you figure it out!

import hmac
import json
from base64 import b64encode
from hashlib import sha256
from urllib.parse import urlencode

consumer_key = "YOUR_CONSUMER_KEY".encode()

request_data = {'userId': 'new_user_123'}
request_path = "/api/v1/snapTrade/registerUser"
request_query = "clientId=PASSIVTEST&timestamp=1635790389"

sig_object = {"content": request_data, "path": request_path, "query": request_query}

sig_content = json.dumps(sig_object, separators=(",", ":"), sort_keys=True)
sig_digest =, sig_content.encode(), sha256).digest()

signature = b64encode(sig_digest).decode()
const crypto = require("crypto");

const JSONstringifyOrder = (obj) => {
  var allKeys = [];
  var seen = {};
  JSON.stringify(obj, function (key, value) {
    if (!(key in seen)) {
      seen[key] = null;
    return value;
  return JSON.stringify(obj, allKeys);

const consumerKey = encodeURI('YOUR_CONSUMER_KEY');

const requestData = {'userId': 'new_user_123'}
const requestPath = "/api/v1/snapTrade/registerUser"
const requestQuery = "clientId=PASSIVTEST&timestamp=1635790389"

const sigObject = {"content": requestData, "path": requestPath, "query": requestQuery}

const sigContent = JSONstringifyOrder(sigObject)

const hmac = crypto.createHmac("sha256", consumerKey);
const signature = hmac.update(sigContent).digest('base64');

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class main {
	public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
		System.out.println("Hello, World!");
        final String data = "{\"content\":{\"userId\":\"new_user_123\"},\"path\":\"/api/v1/snapTrade/registerUser\",\"query\":\"clientId=PASSIVTEST&timestamp=1635790389\"}";

        final String key = "YOUR_CONSUMER_KEY";
        final String algorithm = "HmacSHA256";
        final SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
        final Mac mac = Mac.getInstance(algorithm);
        final String base64 = new String(Base64.encodeBase64(mac.doFinal(data.getBytes())));
package main

import (
 type QueryParams struct {
    ClientId string	    `json:"clientId"`
	Timestamp int64 	`json:"timestamp"`
	UserId string		`json:"userId"`
	UserSecret string 	`json:"userSecret"`
 type Signature struct {
    Content map[string]interface{}	`json:"content"`
	Path string						`json:"path"`
	Query string 					`json:"query"`

func main() {
	var sig_content = new(Signature)
	var timestamp = time.Now().Unix()

	var client_id = "YOUR_CLIENT_ID"
	var user_id = "USER_ID"
	//var user_secret = "USER_SECRET"   Needed for user based requests but not registerUser
	var consumer_key = "YOUR_CONSUMER_KEY"
	var url = ""

	sig_content.Content = make(map[string]interface{})
	sig_content.Content["userId"] = user_id
	sig_content.Path = "/api/v1/snapTrade/registerUser"
	sig_content.Query = "clientId=" + client_id + "&timestamp="+ strconv.FormatInt(timestamp,10)
	sig_json, _ := JSONMarshal(sig_content)

	var signature = ComputeHmac256(string(sig_json), consumer_key)
	r, _ := json.Marshal(sig_content.Content)

	reqBody := bytes.NewBuffer(r)

	req, _ := http.NewRequest("POST", url, reqBody)
	req.URL.RawQuery = sig_content.Query

	req.Header.Add("accept", "application/json")
	req.Header.Add("content-type", "application/json")
	req.Header.Add("Signature", signature)

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)


func ComputeHmac256(message string, secret string) string {
    key := []byte(secret)
    h := hmac.New(sha256.New, key)
    return base64.StdEncoding.EncodeToString(h.Sum(nil))

func JSONMarshal(t interface{}) ([]byte, error) {
    buffer := &bytes.Buffer{}
    encoder := json.NewEncoder(buffer)
    err := encoder.Encode(t)
	json := buffer.Bytes()
	json = bytes.TrimRight(json, "\n")
    return json, err