Developers

Documentation

Zanibal APIs provide a rich set of services that can be used to customize and extend the platform. These APIs can be used to develop and integrate third-party applications such as mobile and web portals, direct market access for counterparties and many other use cases. It supports an extensive set of capabilities including opening new client accounts, cash deposit and withdrawal, securities research and trading, asset management and many more. These APIs are delivered using REST, SOAP, FIX and Web Sockets protocols and are managed with Kubernetes. 

Below are some sample apps that can help you get started and we would love to see what you build.

import json
import requests
import urllib3
urllib3.disable_warnings()

#Global variable that will store the token used in the samples
token = ''

#REST endpoint base url
api_url = "https://api-demo.zanibal.com/api"

#API username for accessing the REST services
api_user = "apiuser"

#API password or key for accessing the REST services
api_key = "xxxxxxxxx"


#Getting an access token. This will use the configured username and password to retrieve an bearer token
def get_access_token():
    global token
    url =   api_url + "/v1/security/request/access-token"
    file = dict(username = api_user, password = api_key)
    response = requests.post(url, files=file, verify=False)
    response = response.json()

    #Save the token
    token = response['access_token']

    #Optionall print out the access token
    #print(token)


# Login and retrieve a clients request passcode.
# The passcode will then be used to authenticate and retrieve the client's details
def login_customer():
    url = api_url + "/v1/security/login/customer"
    username = "john"
    password = "********"
    file = dict(username=username, password=password)

    Headers = {'Authorization': 'Bearer ' + token}
    response = requests.post(url, verify=False, headers=Headers, files=file)
    response = response.json()
    loginToken = response['msgCode']
    loginResult = response['success']
    print("Login success ->[" + str(loginResult) + "] & Private Key ->[" + loginToken + "]")

    #retrieve the client details using the private token from the login step
    url = api_url + "/v1/security/customer/username/" + username
    Headers = {'Authorization': 'Bearer ' + token, 'X-Auth-Token': loginToken}
    response = requests.get(url, verify=False, headers=Headers, files=file)
    print("\n\n" + json.dumps(response.json(), indent=4, sort_keys=True))

#Creating a customer
def create_customer():
    url = api_url + "/v1/partner/customer/create"
    payload = json.dumps({
        "active": True,
        "channel": "WEB",
        "firstName": "John",
        "lastName": "Smith",
        "cellPhone": "08037355772",
        "emailAddress1": "john.smith@mail.com",
        "partnerType": "INDIVIDUAL",
        # "customerGroupName": "RETAIL",  # The default value configured in application will be used if not specified
        # "businessOfficeName": "HQ" # The default value configured in application will be used if not specified
    })
    Headers = {'Authorization': 'Bearer ' + token, 'Content-Type':'application/json'}
    response = requests.post(url, verify=False, headers=Headers, data=payload)
    response = response.json()
    customerId = response['msgCode']

    print("Created new client with ID ->[" + response['msgCode'] + "] & Request Status ->[" + str(response['success']) + "]")

    #Use the ID returned by this API to get details of the created record
    find_customer_by_id(customerId)

# Find a customer using an ID
def find_customer_by_id(customerId):
    url = api_url + "/v1/partner/customer/id/" + customerId
    Headers = {'Authorization': 'Bearer ' + token}
    response = requests.get(url, verify=False, headers=Headers)
    print("\n\n" + json.dumps(response.json(), indent=4, sort_keys=True))


get_access_token()
login_customer()
create_customer()




import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Objects;

public class ZanibalAPIDemo {

    //Rest endpoint base url
    private String apiUrl;

    //Client credentials that will be used for the test.
    private String apiUser;
    private String apiPassword;

    //Global variable that will store the token used in the samples
    private String apiToken;

    /**
     * Create the object
     *
     * @param apiUrl      - API server
     * @param apiUser     - API username
     * @param apiPassword - API password
     */
    public ZanibalAPIDemo(String apiUrl, String apiUser, String apiPassword) {
        this.apiUrl = apiUrl;
        this.apiUser = apiUser;
        this.apiPassword = apiPassword;
    }

    /**
     * This method will generate an access token using the provided API keys.
     * The generated bearer token is then stored in a global variable and used for all the other API requests
     **/
    public void getAccessToken() {

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", apiUser)
                .addFormDataPart("password", apiPassword)
                .build();
        Request request = new Request.Builder()
                .url(String.format("%s/v1/security/request/access-token", apiUrl))
                .post(requestBody)
                .build();


        try {
            Response response = getOkHttpClientThatAcceptsAllCerts().build().newCall(request).execute();
            LinkedHashMap<String, Object> map = new com.fasterxml.jackson.databind.ObjectMapper().
                    readValue(response.body().string(), LinkedHashMap.class);
            if (map.containsKey("access_token")) {
                apiToken = (String) map.get("access_token");
            }
            System.out.println(MessageFormat.format("Retrieved response -> {0}", apiToken));
        } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * Here a new client record is created using the client_username and client_password specified above.
     * The application will return an ID for the new client record and this can be used to retrieve the details of the record
     *
     * @param req - Customer Object
     */
    public void createCustomer(JSONObject req) {

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, req.toString());

        Request request = new Request.Builder()
                .url(String.format("%s/v1/partner/customer/create", apiUrl))
                .addHeader("Authorization", "Bearer " + apiToken)
                .addHeader("Content-Type", "application/json")
                .post(requestBody)
                .build();

        try {
            Response response = getOkHttpClientThatAcceptsAllCerts().build().newCall(request).execute();
            CreateCustomerResponse createCustomerResponse = new com.fasterxml.jackson.databind.ObjectMapper().
                    readValue(Objects.requireNonNull(response.body()).string(), CreateCustomerResponse.class);

            String customerId = createCustomerResponse.getMsgCode();
            System.out.println(MessageFormat.format("Created new client with ID -> {0} " +
                    "and Request Status -> {1}", customerId, createCustomerResponse.getSuccess()));

            //Use the ID returned by this API to get details of the created record
            findCustomerById(Long.valueOf(customerId));

        } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * @param customerId - The customer ID
     */
    public void findCustomerById(Long customerId) {
        Request request = new Request.Builder()
                .url(String.format("%s/v1/partner/customer/id/%d", apiUrl, customerId))
                .addHeader("Authorization", "Bearer " + apiToken)
                .get()
                .build();
        try {
            Response response = getOkHttpClientThatAcceptsAllCerts().build().newCall(request).execute();

            //You can deserialize the body of the response into an object
            System.out.println(MessageFormat.format("Retrieved response -> {0}",
                    Objects.requireNonNull(response.body()).string()));

        } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * After the client record is created, the username and password specified during the setup can be used to login
     * If the login is successful, the application returns a token.
     * This token has to be included in the 'X-Auth-Token' header when retrieving the client's details.
     *
     * @param username - The client's username
     * @param password - The client's password
     */
    public void loginCustomer(String username, String password) {
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", username)
                .addFormDataPart("password", password)
                .build();

        Request request = new Request.Builder()
                .url(MessageFormat.format("{0}/v1/security/login/customer", apiUrl))
                .addHeader("Authorization", "Bearer " + apiToken)
                .post(requestBody)
                .build();


        try {
            Response response = getOkHttpClientThatAcceptsAllCerts().build().newCall(request).execute();
            LoginResponse loginResponse = new com.fasterxml.jackson.databind.ObjectMapper().readValue(response.body().
                    string(), LoginResponse.class);
            String authToken = loginResponse.getMsgCode();
            Boolean loginResult = loginResponse.getSuccess();
            System.out.println(MessageFormat.format("Login success -> {0} & Private key -> {1}",
                    loginResult, authToken));

            // retrieve the client details using the private token from the login step
            retrieveClientDetails(username, authToken);
        } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Retrieve a clients credentials using the username and a login token
     *
     * @param username  -  The client's username
     * @param authToken - Authorization Token
     */
    public void retrieveClientDetails(String username, String authToken) {
        Request request = new Request.Builder()
                .url(MessageFormat.format("{0}/v1/security/customer/username/{1}", apiUrl, username))
                .addHeader("Authorization", "Bearer " + apiToken)
                .addHeader("X-Auth-Token", authToken)
                .get()
                .build();
        try {
            Response response = getOkHttpClientThatAcceptsAllCerts().build().newCall(request).execute();
            //You can deserialize the body of the response into an object
            System.out.println(MessageFormat.format("Retrieved response -> {0}",
                    Objects.requireNonNull(response.body()).string()));
        } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * Helper method to handle SSL communication
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public OkHttpClient.Builder getOkHttpClientThatAcceptsAllCerts() throws NoSuchAlgorithmException, KeyManagementException {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        TrustManager TRUST_ALL_CERTS = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
        };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{TRUST_ALL_CERTS}, new java.security.SecureRandom());
        builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) TRUST_ALL_CERTS);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    }

    public static void main(String[] args) {

        //API username for accessing the REST services
        String username = "apiuser";

        //API password or key for accessing the REST services
        String password = "********";

        //API base url
        String apiServer = "https://api-demo.zanibal.com/api";

        ZanibalAPIDemo demo = new ZanibalAPIDemo(apiServer, username, password);

        //Retrieve the access token
        demo.getAccessToken();


        //Build a new client objecgt
        JSONObject req = new JSONObject();
        String clientUsername = "john.smith";
        String clientPassword = "********";
        try {
            req.put("active", true);
            req.put("channel", "WEB");
            req.put("firstName", "John");
            req.put("lastName", "Smith");
            req.put("cellPhone", "08012345678");
            req.put("emailAddress1", "john.smith@domaiin.com");
            req.put("portalUserName", clientUsername);
            req.put("portalPassword", clientPassword);
            req.put("partnerType", "INDIVIDUAL");
//            req.put("customerGroupName", "RETAIL");//The default value configured in application will be used if not specified
//            req.put("businessOfficeName", "0000000001");//The default value configured in application will be used if not specified

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //Create the client record
        demo.createCustomer(req);

        //Login using the clients credentials
        demo.loginCustomer(clientUsername, clientPassword);

    }

}

/**
 * Bean for deserializing the login JSON response
 */
class LoginResponse {
    private String msgCode;
    private String msgArgs;
    private Boolean success;

    public String getMsgCode() {
        return msgCode;
    }

    public void setMsgCode(String msgCode) {
        this.msgCode = msgCode;
    }

    public String getMsgArgs() {
        return msgArgs;
    }

    public void setMsgArgs(String msgArgs) {
        this.msgArgs = msgArgs;
    }

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    @Override
    public String toString() {
        return "LoginResponse{" +
                "msgCode='" + msgCode + '\'' +
                ", msgArgs='" + msgArgs + '\'' +
                ", success=" + success +
                '}';
    }
}

/**
 * Bean for deserializing the customer JSON response
 */
class CreateCustomerResponse {
    private String msgCode;
    private String[] msgArgs;
    private Boolean success;

    public String getMsgCode() {
        return msgCode;
    }

    public void setMsgCode(String msgCode) {
        this.msgCode = msgCode;
    }

    public String[] getMsgArgs() {
        return msgArgs;
    }

    public void setMsgArgs(String[] msgArgs) {
        this.msgArgs = msgArgs;
    }

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    @Override
    public String toString() {
        return "LoginResponse{" +
                "msgCode='" + msgCode + '\'' +
                ", msgArgs='" + msgArgs + '\'' +
                ", success=" + success +
                '}';
    }
}

//Global imports
const axios = require('axios');
const FormData = require('form-data');

//Disable SSL certificate chain verification
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

//Global variable that will store the token used in the samples
let token = '';

//API username for accessing the REST services
let api_user = "apiuser";

//API password or key for accessing the REST services
let api_key = "********";

//private token to access client details
let loginToken = '';

//REST endpoint base url
let api_url = "http://localhost:8888";

let client_username = '';

/**
 This function will generate an access token using the provided API keys.
 The generated bearer token is then stored in a global variable and used for all the other API requests
 * @returns {Promise<void>}
 */
async function getAccessToken() {
    let data = new FormData();
    data.append('username', api_user);
    data.append('password', api_key);

    let config = {
        method: 'post',
        url: api_url + '/api/v1/security/request/access-token',
        headers: {...data.getHeaders()},
        data: data
    };

    await axios(config)
        .then(function (response) {
            token = response.data.access_token;
            console.log("Generated token ->", token);
            return token;
        })
        .catch(function (error) {
            console.log(error);
        })
}


/**
 Here a new client record is created using the client_username and client_password specified above.
 The application will return an ID for the new client record and this can be used to retrieve the details of the record
 * @returns {Promise<void>}
 */
async function createCustomer() {

    client_username = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
    console.log("Creating client with username => ", client_username)

    let data = {
        "active": true,
        "channel": "WEB",
        "firstName": "John",
        "lastName": "Smith",
        "cellPhone": "08012345678",
        "emailAddress1": "john.smith@mail.com",
        "portalUserName": client_username,
        "portalPassword": '********',
        "partnerType": "INDIVIDUAL",
        // "customerGroupName": "PLATINUM",//# The default value configured in application will be used if not specified
        // "businessOfficeName": "LAGOS"//The default value configured in application will be used if not specified
    };

    let config = {
        method: 'post',
        url: api_url + '/api/v1/partner/customer/create',
        headers: {'Authorization': 'Bearer ' + token},
        data: data
    };

    let customerId =
        await axios(config)
            .then(function (response) {
                console.log(response.data)
                let customerId = response.data['msgCode'];
                console.log("Created new client with ID ->[", response.data['msgCode'], "] & Request Status ->[",
                    response.data['success'], "]");
                return customerId;
            })
            .catch(function (error) {
                console.log(error);
            });
    return customerId;
}


/**
 After the client record is created, the username and password specified during the setup can be used to login
 If the login is successful, the application returns a token.
 This token has to be included in the 'X-Auth-Token' header when retrieving the client's details.
 * @returns {Promise<void>}
 */
async  function loginCustomer() {
    let data = new FormData();
    data.append('username', client_username);
    data.append('password', '********');

    let config = {
        method: 'post',
        url: api_url + '/api/v1/security/login/customer',
        headers: {...data.getHeaders(), 'Authorization': 'Bearer ' + token},
        data: data
    };

    await axios(config)
        .then(function (response) {
            console.log(response.data);

            //retrieve the client details using the private token from the login step
            let loginToken = response.data['msgCode'];
            let loginResult = response.data['success'];
            console.log("Login success ->[" , loginResult , "] & Private Key ->[" , loginToken , "]")

            retrieveCustomerDetails(loginToken);

        })
        .catch(function (error) {
            console.log(error);
        });
}


/**
 * This function accepts an integer value for the client identifier and retrieves the record.
 * @param customerId
 * @returns {Promise<void>}
 */
async function findCustomerById(customerId) {
    let data = ''
    config = {
        method: 'get',
        url: api_url + '/api/v1/partner/customer/id/' + customerId,
        headers: {'Authorization': 'Bearer ' + token},
        data: data
    };

    await axios(config)
        .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            console.log(error);
        });
}

/**
 *
 * @param username
 * @returns {Promise<void>}
 */
async function retrieveCustomerDetails(loginToken) {
    let data = ''
    config = {
        method: 'get',
        url: api_url + "/api/v1/security/customer/username/" + client_username,
        headers: {'Authorization': 'Bearer ' + token, 'X-Auth-Token': loginToken},
        data: data
    };

    await axios(config)
        .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            console.log(error);
        });
}


/**
 Retrieve an access token
 Create a new client
 Login with the client's credentials.
 * @returns {Promise<void>}
 */
const runApiSamples = async () => {
    console.log("Starting execution ... ");
    //Get the access token
    await getAccessToken();

    //Create a client record
    let customerId = await createCustomer();

    //Retrieve the client record with the ID returned by the API
    await findCustomerById(customerId);

    //Login the client with the generated token
    await loginCustomer();


    console.log("Finished execution ... ");
}

runApiSamples();

To learn more about the Zanibal platform and how we can help you scale your services please download our 8.0 technical architecture document. .