Get started
REST authentication

REST authentication#

Make requests#

All private REST requests must contain the following headers:

  • OK-ACCESS-KEY The API key as a string (follow this guide to generate an API key)
  • OK-ACCESS-SIGN The Base64-encoded signature (go to the Signature subsection for details)
  • OK-ACCESS-TIMESTAMP The UTC timestamp of your request, e.g., 2020-12-08T09:08:57.715Z
  • OK-ACCESS-PASSPHRASE The passphrase you specified when creating the API key

Some endpoints, such as WaaS, require an additional header:

  • OK-ACCESS-PROJECT The project ID of your project (can be found under project details)

Request bodies should have content type application/json and be in valid JSON format.

Signature#

The OK-ACCESS-SIGN header is generated as follows:

  • Create a prehash string of timestamp + method + requestPath + body (where + represents string concatenation)
  • Prepare the secret key (generated when you create an API key)
  • Sign the prehash string with the secret key using the HMAC SHA256
  • Encode the signature in the Base64 format

Example: sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(timestamp + 'GET' + '/api/v5/account/balance?ccy=BTC', SecretKey))

  • The timestamp value is the same as the OK-ACCESS-TIMESTAMP header with millisecond ISO format
    • Example: 2020-12-08T09:08:57.715Z
  • The method should be in UPPERCASE
    • Example: GET and POST
  • The requestPath is the path for requesting an endpoint
    • Example: /api/v5/account/balance
  • The body refers to the string of the request body. It can be omitted if there is no request body (frequently the case for GET requests).
    • Example: {"instId":"BTC-USDT","lever":"5","mgnMode":"isolated"}
    • Note: GET request parameters are counted as requestpath, not body

Postman example#

Postman is a popular API development and testing tool that allows developers to design, test, and document APIs. It provides a user-friendly graphical interface for making HTTP requests to APIs.

If you have not installed Postman, you can download it for free from the Postman website: https://www.postman.com/

Note
This example requires you to have a basic understanding of Postman.

Add parameters#

  • This typically applies to GET requests.
  • If your request requires query parameters, you can add them under the Params tab. Here, you can add key-value pairs for your query parameters.

img

Set headers#

Under the Headers tab, add the following key-value pairs:

  • OK-ACCESS-KEY
  • OK-ACCESS-PASSPHRASE
  • OK-ACCESS-PROJECT (if required)

img

Add body#

  • This typically applies to POST requests.
  • If your request requires a request body, you can add them under the Body tab.
  • Select raw and JSON under the dropdown menu.
  • Input your request body in JSON format.

img

Set pre-request script#

  • This is used to generate the necessary signature (OK-ACCESS-SIGN) and timestamp (OK-ACCESS-TIMESTAMP)
  • Under the Pre-request Script tab, insert the script which corresponds to the request type.
  • Exclude the request body when generating the prehash string for GET requests.
  • Edit the secret key accordingly.

GET requests:

var method = pm.request.method;
var now = new Date();
var isoString = now.toISOString();
var path = pm.request.url.getPathWithQuery();
var sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(isoString + method + path, pm.variables.replaceIn('{{secret_key}}')));

pm.request.headers.add({
    key: 'OK-ACCESS-SIGN',
    value: sign
});

pm.request.headers.add({
    key: 'OK-ACCESS-TIMESTAMP',
    value: isoString
});

POST requests:

var method = pm.request.method;
var now = new Date();
var isoString = now.toISOString();
var path = pm.request.url.getPathWithQuery();
var bodyStr = pm.request.body.raw;
var sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(isoString + method + path + bodyStr, pm.variables.replaceIn('{{secret_key}}')))

pm.request.headers.add({
    key: 'OK-ACCESS-SIGN',
    value: sign
});

pm.request.headers.add({
    key: 'OK-ACCESS-TIMESTAMP',
    value: isoString
});

Python example#

To call our APIs via a Python script, you can follow this code template:

import http.client
import hmac
import hashlib
import base64
from datetime import datetime
from urllib.parse import urlencode, quote_plus
import json

# Define the credentials and project ID for the API
api_config = {
  "api_key": '',
  "secret_key": '',
  "passphrase": '',
  "project": '' # Only required for WaaS APIs
}

def pre_hash(timestamp, method, request_path, params):
    # Create a pre-signature based on the string and parameters
    query_string = ''
    if method == 'GET' and params:
        query_string = '?' + urlencode(params)
    if method == 'POST' and params:
        query_string = json.dumps(params)
    return timestamp + method + request_path + query_string

def sign(message, secret_key):
    # Sign the pre-signed string using HMAC-SHA256
    mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), hashlib.sha256)
    d = mac.digest()
    return base64.b64encode(d).decode('utf-8') 

def create_signature(method, request_path, params):
    # Obtain a ISO 8601 format timestamp
    timestamp = datetime.utcnow().isoformat()[:-3] + 'Z'
    # Generate signature
    message = pre_hash(timestamp, method, request_path, params)
    signature = sign(message, api_config['secret_key'])
    
    return signature, timestamp

def send_get_request(request_path, params):
    # Generate signature
    signature, timestamp = create_signature("GET", request_path, params)

    # Generate headers
    headers = {
        'OK-ACCESS-KEY': api_config['api_key'],
        'OK-ACCESS-SIGN': signature,
        'OK-ACCESS-TIMESTAMP': timestamp,
        'OK-ACCESS-PASSPHRASE': api_config['passphrase'],
        'OK-ACCESS-PROJECT': api_config['project'] # Only for WaaS APIs
    }

    # Send a GET request using the http.client library
    conn = http.client.HTTPSConnection("www.okx.com")
    params_encoded = urlencode(params, quote_via=quote_plus) if params else None
    conn.request("GET", request_path + f'?{params_encoded}' if params_encoded else request_path, headers=headers)

    # Receive the response
    response = conn.getresponse()
    data = response.read()

    return data.decode("utf-8")

def send_post_request(request_path, params):
    # Generate signature
    signature, timestamp = create_signature("POST", request_path, params)

    # Generate headers
    headers = {
        'OK-ACCESS-KEY': api_config['api_key'],
        'OK-ACCESS-SIGN': signature,
        'OK-ACCESS-TIMESTAMP': timestamp,
        'OK-ACCESS-PASSPHRASE': api_config['passphrase'],
        'OK-ACCESS-PROJECT': api_config['project'], # Only for WaaS APIs
        'Content-Type': 'application/json'  # Required for POST requests
    }

    # Send a POST request using the http.client library
    conn = http.client.HTTPSConnection("www.okx.com")
    params_encoded = json.dumps(params) if params else ''
    conn.request("POST", request_path, body=params_encoded, headers=headers)

    # Receive the response
    response = conn.getresponse()
    data = response.read()

    return data.decode("utf-8")

# GET request example
request_path = '/api/v5/dex/aggregator/quote'
params = {'chainId': 42161, 
          'amount': 1000000000000, 
          'toTokenAddress': '0xff970a61a04b1ca14834a43f5de4533ebddb5cc8', 
          'fromTokenAddress': '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1'}
req = send_get_request(request_path, params)
req
print(req)

# POST request example
request_path = '/api/v5/mktplace/nft/ordinals/listings'
params = {'slug': 'sats'}
req = send_post_request(request_path, params)
req
print(req)

Javascript example#

To call our APIs via a Javascript script, you can follow this code template:

const https = require('https');
const crypto = require('crypto');
const querystring = require('querystring');

// Define the credentials and project ID for the API
const api_config = {
  "api_key": '',
  "secret_key": '',
  "passphrase": '',
  "project": '' // Only required for WaaS APIs
};

function preHash(timestamp, method, request_path, params) {
  // Create a pre-signature based on the string and parameters
  let query_string = '';
  if (method === 'GET' && params) {
    query_string = '?' + querystring.stringify(params);
  }
  if (method === 'POST' && params) {
    query_string = JSON.stringify(params);
  }
  return timestamp + method + request_path + query_string;
}

function sign(message, secret_key) {
  // Sign the pre-signed string using HMAC-SHA256
  const hmac = crypto.createHmac('sha256', secret_key);
  hmac.update(message);
  return hmac.digest('base64');
}

function createSignature(method, request_path, params) {
  // Obtain a ISO 8601 format timestamp
  const timestamp = new Date().toISOString().slice(0, -5) + 'Z';
  // Generate signature
  const message = preHash(timestamp, method, request_path, params);
  const signature = sign(message, api_config['secret_key']);
  return { signature, timestamp };
}

function sendGetRequest(request_path, params) {
  // Generate signature
  const { signature, timestamp } = createSignature("GET", request_path, params);

  // Generate headers
  const headers = {
    'OK-ACCESS-KEY': api_config['api_key'],
    'OK-ACCESS-SIGN': signature,
    'OK-ACCESS-TIMESTAMP': timestamp,
    'OK-ACCESS-PASSPHRASE': api_config['passphrase'],
    'OK-ACCESS-PROJECT': api_config['project'] // Only for WaaS APIs
  };

  const options = {
    hostname: 'www.okx.com',
    path: request_path + (params ? `?${querystring.stringify(params)}` : ''),
    method: 'GET',
    headers: headers
  };

  const req = https.request(options, (res) => {
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });
    res.on('end', () => {
      console.log(data);
    });
  });

  req.end();
}

function sendPostRequest(request_path, params) {
  // Generate signature
  const { signature, timestamp } = createSignature("POST", request_path, params);

  // Generate headers
  const headers = {
    'OK-ACCESS-KEY': api_config['api_key'],
    'OK-ACCESS-SIGN': signature,
    'OK-ACCESS-TIMESTAMP': timestamp,
    'OK-ACCESS-PASSPHRASE': api_config['passphrase'],
    'OK-ACCESS-PROJECT': api_config['project'], // Only for WaaS APIs
    'Content-Type': 'application/json' // Required for POST requests
  };

  const options = {
    hostname: 'www.okx.com',
    path: request_path,
    method: 'POST',
    headers: headers
  };

  const req = https.request(options, (res) => {
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });
    res.on('end', () => {
      console.log(data);
    });
  });

  if (params) {
    req.write(JSON.stringify(params));
  }

  req.end();
}

// GET request example
const getRequestPath = '/api/v5/dex/aggregator/quote';
const getParams = {
  'chainId': 42161,
  'amount': 1000000000000,
  'toTokenAddress': '0xff970a61a04b1ca14834a43f5de4533ebddb5cc8',
  'fromTokenAddress': '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1'
};
sendGetRequest(getRequestPath, getParams);

// POST request example
const postRequestPath = '/api/v5/mktplace/nft/ordinals/listings';
const postParams = {
  'slug': 'sats'
};
sendPostRequest(postRequestPath, postParams);