Skip to main content

Manual of sending a request

There is an example of how to generate the X-Api-Signature parameter and send a request with Node.js:

  1. Find a module that supports generating an RSA signature using the SHA256 hashing algorithm.
note

For Node.js, it is a crypto module. If you use another programming language in your project, you should find a similar module supported by your language.

  1. Find a module that allows sending HTTP requests.
note

For Node.js, it is a node-fetch module.

  1. Install the needed modules in any convenient way. For example, with npm:
npm install crypto
npm install node-fetch
  1. Import the modules to your code:
const crypto = require('crypto');
const fetch = require('node-fetch');
  1. Define the variables for your private and public keys:
const API_PUBLIC_KEY = '<Your public API key>';
const API_PRIVATE_KEY = '<Your private API key>';
  1. Create a private key object with the following type, format and encoding:
const privateKeyObject = crypto.createPrivateKey({
key: API_PRIVATE_KEY,
type: 'pkcs1',
format: 'pem',
encoding: 'base64',
});
  1. Define the variables for the URL and body message of the API method you want to request. For example:
const path = 'https://fiat-api.changelly.com/v1/validate-address';
const message = {
"currency": "XRP",
"walletAddress": "rwpMvfxoodXggJ1g4qv6MWAPQqWDwQyHUW",
"walletExtraId": "1234hg"
};

To provide path or query request parameters, specify them in the path variable, for example:

const path = 'https://fiat-api.changelly.com/v1/currencies?type=crypto';

Important! This message example is applied to the POST request. If you want to send GET request, you should make the message empty:

const message = {};

If you delete the message variable, you will get an error.

  1. Concatenate the path and the message object into one string:
const payload = path + JSON.stringify(message);
  1. Create a signature that will be used as X-Api-Signature header:
const signature = crypto.sign('sha256', Buffer.from(payload), privateKeyObject).toString('base64');

crypto.sign takes as input 3 parameters:

  • hashing algorithm – sha256.
  • request data – Buffer.from(payload).
  • private key object in the desired format – privateKeyObject.

crypto.sign returns signature in a buffer. You need to convert it to base64 format.

  1. Create an options object which contains info for API request – HTTP method, headers and body:
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': API_PUBLIC_KEY,
'X-Api-Signature': signature,
},
body: JSON.stringify(message),
};
  1. Send a request:
fetch(path, options).then(response => {
if (response.ok) {
return response.json();
}
throw new Error(`Request error: ${response.status} ${response.statusText}`);
}).then((response) => {
console.log('Successful response: ', response);
}).catch(error => {
console.error(error);
});