A command line client is available here -

https://github.com/binarylane/binarylane-cli

Introduction:

the BinaryLane API is accessed using JSON-wrapped commands over HTTPS. It facilitates a range of functionalities, from automating tasks and creating custom tools to provisioning resources via Infrastructure-as-Code (IaC). The API also offers the potential to replicate the full range of features available in BinaryLane's 'mPanel', providing a comprehensive code-level interface for advanced operations and integrations.


In this guide, we will introduce you to the BinaryLane API, highlighting its core functions and demonstrating practical applications through an example use case. 


For more information on our API, including a comprehensive reference guide on commands and utilisation, refer to our API documentation here: BinaryLane API




!  Warning


The BinaryLane API is still in active development, not all features may be available. Until this warning is removed, breaking changes are possible without the version changing. However, this API is relatively mature and we are actively developing a new website and other tools against this API so breaking changes should be rare at this point.





Prerequisites:

  • a BinaryLane account
  • Access to BinaryLane Control Panel (mPanel)
  • Some familiarity with programming
  • Some familiarity with RESTful APIs 
  • Some knowledge of JSON and HTTPS
  • Basic CLI (Command-line interface) usage


TABLE OF CONTENTS


Setting Up Your Environment


Accessing your API Token


To effectively utilise the BinaryLane API, the first step involves obtaining your unique API token. This token serves as your key to interfacing with the BinaryLane services programmatically. Here's how you can access it:


  1. Login to your Binarylane Account: Start by logging into your BinaryLane account: Login | BinaryLane Australia

  2. Navigate to the API Section: In the dashboard, head over to the 'Account' tab. Within this section, locate the Security segment:



  3. Manage your API Token: Here, you'll find an option labeled 'Manage' next to Nova API Key. Click on this.

  4. Create a New Token: In the next page, select '+ Create Token'. This is where you'll generate a new API token.  

  5. Token Creation and Security: Assign a name to your API token and click 'Create'. Post-creation, your API Key will be displayed.



    Important


    Make sure to copy this key immediately as it is shown only once. Treat this token like a password - it's crucial for your account's security.



Configuring Your API Client


With your newly generated BinaryLane API token, you can configure your API client for secure and authenticated interactions.

This guide primarily uses Python for demonstration due to Python being widely recognised for its simplicity and readability, making it an ideal choice for illustrating API interactions. Furthermore, Python's extensive libraries and community support simplify the process of working with APIs.


While Python is a popular choice, it's not the only way to interact with the BinaryLane API. Alternatives like command-line tools, such as 'curl', offer direct API communication pathways. These methods can be more suitable for quick tests, automated scripts, or environments where Python is not available or practical. We will explore these alternative methods later in this guide to provide a comprehensive understanding of the different approaches to interacting with the BinaryLane API.


  1. Create a Python Script File: Begin by creating a new file for your script. You can name it something descriptive, like 'binarylane_api_client.py'. This file will contain all the code necessary for interacting with the BinaryLane API.

  2. Import the Requests Module: At the top of your script file, you need to import the 'requests' module. This module is not included in the standard Python library, so you might need to install it separately using `pip install requests`. This module simplifies the process of making HTTP requests in Python.

    Add the following line at the top of your binarylane_api_client.py file:


    binarylane_api_client.py

    import requests


  3. Setting Up the API Token: To enhance security, it's advised to store your API token in an environment variable. This can be set in your operating system, and then accessed within your script. Use the `os` module to retrieve the API token from the environment variable named `BINARYLANE_API_TOKEN`. For details on how to set this environment variable, please see here.

    Instead of using an environment variable, you could store your API token in a configuration file and read it using the `configparser` module. For simplicity's sake, we'll use a standard environment variable retrieval technique in the following guide. If you'd like to use `configparser` instead, please jump to this section for details: Alternative Method Using a Configuration File

    Include the following in your binarylane_api_client.py file:

    binarylane_api_client.py

    import requests import os

    api_token = os.environ.get('BINARYLANE_API_TOKEN')



  4. Configuring Headers for Authentication: Next, configure the headers to include your API token for authenticating your requests. This is achieved by setting up a dictionary in Python with the necessary header fields. The 'Authorization' header carries the API token, and the 'Content-Type' header indicates that the request body is formatted as JSON.


    binarylane_api_client.py

    import requests import os

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }



  5. Making the API Request: Now, use the 'requests' module to make a `GET` request to the BinaryLane API. We're targeting the '/v2/servers' endpoint in this example and retrieving all headers. For a comprehensive reference guide on actions, commands and utilisation, refer to our API documentation here: BinaryLane API


    binarylane_api_client.py

    import requests import os

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }
    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)



  6. Handling the Response: After making the request, handle the response by converting the returned JSON data into a Python-readable format. The 'response.json()' method is used for this purpose.


    binarylane_api_client.py

    import requests
    import os

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }
    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)

    print(response.json())




Once your script is complete, test it to ensure it functions as expected. Run the script and check the output for any errors. Common issues include incorrect API tokens, network problems, or errors in the API endpoint URL.



Filtering API Responses with jq


Once your script successfully fetches data from the BinaryLane API, you might find that the response contains more information than needed. To refine the output and display only specific details you define, we can use 'jq', a powerful command-line JSON processor.


  1. Installing jq: Before you can use 'jq' to filter your API responses, you need to install it on your system.

    • Linux:
      • Most Linux distributions include 'jq' in their repositories. You can install it using your package manager, for example, `sudo apt-get install jq` for Ubuntu/Debian or `sudo yum install jq` for CentOS/Fedora. For other distributions, you may need to consult the relative distribution's package management documentation for exact installation commands.

    • Windows:
      • Download the executable from the official jq website and add it to your system path, or, use 'winget' to install it directly: `winget install jqlang.jq`. (Note: Installation via 'winget' will modify your environment to include a new variable path for 'jq'; restart your shell to use the new value.)

    • MacOS:
      • Install 'jq' using Homebrew by running `brew install jq` in the terminal. (Requires installation of Homebrew)

  2. Import Necessary Modules: To integrate 'jq' with the Python script, we will use the 'subprocess' module. This module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This is necessary for running the 'jq' command from within Python.


    binarylane_api_client.py

    import requests import os
    import subprocess

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }
    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)
    print(response.json())



  3. Convert Response to JSON: You should convert the response into a JSON string, as 'jq' works with JSON formatted strings. In Python, you can do this using the 'json' module. First, import the 'json' module and then convert the response to a JSON string.


    binarylane_api_client.py

    import requests
    import os
    import subprocess

    import json

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }
    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)

    print(response.json()) 
    json_response = json.dumps(response.json())
    print(json_response)



  4. Define the jq Filter: Now, define the 'jq' filter you wish to use. For example, if you want to extract only the names and status of servers, your filter might look like ...`'.servers[] | {name, status}'`. This filter uses 'jq' syntax to parse and structure the JSON output. We'll also omit the initial printing of the entire JSON response.


    binarylane_api_client.py

    import requests
    import os
    import subprocess
    import json

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }
    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)
    json_response = json.dumps(response.json())

    print(json_response) 
    jq_filter = '.servers[] | {name, status}'



  5. Apply the jq Filter: Use the 'subprocess' module to run the 'jq' command with your filter. You'll need to pass your JSON response as input to the 'jq' command.


    binarylane_api_client.py

    import requests
    import os
    import subprocess
    import json

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }
    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)
    json_response = json.dumps(response.json())
    jq_filter = '.servers[] | {name, status}'

    filtered_output = subprocess.run(['jq', jq_filter], input=json_response, text=True, capture_output=True)



  6. Print the Filtered Output: Finally, print the output from the subprocess, which is your filtered API response.


    binarylane_api_client.py

    import requests
    import os
    import subprocess
    import json

    api_token = os.environ.get('BINARYLANE_API_TOKEN')
    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }
    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)
    json_response = json.dumps(response.json())
    jq_filter = '.servers[] | {name, status}'

    filtered_output = subprocess.run(['jq', jq_filter], input=json_response, text=True, capture_output=True)


    print(filtered_output.stdout)




Once your script is updated with these changes, run it again to test the 'jq' filtering. You should now see a more refined output, showing only the information specified in your 'jq' filter.



Alternative Method Using a Configuration File


Instead of using an environment variable, you can store your API token in a configuration file and read it using the `configparser` module. This approach is particularly useful if you are managing multiple tokens or additional configuration settings. Here's an example of how you can implement this method:


  1. Install the `configparser` module (if not already available):

    • Linux:
      • `configparser` is included in the Python Standard Library for Python versions 3.0 and above. If you are using an older version of Python, you can install `configparser` via `pip`, Python's package manager. Use the following command: `pip install configparser`.

    • Windows:
      • For Windows, `configparser` is also included in the Python Standard Library for Python 3.0 and newer. If you're using an older Python version, install it with pip using the command: `pip install configparser`. Ensure that Python and pip are added to your system's PATH environment variable to run these commands from any command prompt.
    • MacOS:
      • On MacOS, `configparser` comes pre-installed with Python 3.0 and later. If you're using an earlier version of Python, you might need to install it separately. Open the terminal and use the command: `pip install configparser`. This command requires Python and pip to be installed and configured correctly on your system.

  2. Modify your script to use `configparser`:


    binarylane_api_client.py

    import requests import os import configparser
    import subprocess
    import json


    # Create a config parser

    config = configparser.ConfigParser()

    # Get the path to the user's home directory

    user_home = os.path.expanduser("~")

    # Append the rest of the path to the config.ini file

    config_path = os.path.join(user_home, 'AppData', 'Roaming', 'binarylane', 'config.ini')

    # Read the config file and get the token

    config.read(config_path)

    api_token = config.get('bl', 'api-token')

    headers = {

        'Authorization': f'Bearer {api_token}',

        'Content-Type': 'application/json',

    }

    response = requests.get('https://api.binarylane.com.au/v2/servers', headers=headers)

    print(response.json())


    jq_filter = '.servers[] | {name, status}'

    filtered_output = subprocess.run(['jq', jq_filter], input=json_response, text=True, capture_output=True)

    print(filtered_output.stdout)



    Note: The above script assumes that the `config.ini` file exists at the specified location and contains the necessary API token. You will need to create this file and populate it with the correct information.




Alternative methods for using the BinaryLane API


While the previous sections of this guide focused on leveraging a Python script to interact with the BinaryLane API, it's important to note that Python scripting is not the only way to engage with our API. Command-Line Interface (CLI) tools offer another viable approach for API interaction, allowing for quick and efficient management of resources. This section will cover how to use the BinaryLane API from the CLI on different operating systems: Linux, Windows, and MacOS.




Linux method for CLI-Level interaction with the API


Interacting with the BinaryLane API through the Linux command line is straightforward and efficient, especially when using 'curl'. In addition to basic 'curl' commands, managing your API token as a system variable can enhance both security and convenience.

First, we'll add a new environment variable called '$BINARYLANE_API_TOKEN'; this will be set with our actual BinaryLane API:


  1. Check if the API Token Variable Exists: Open your terminal and run the following command:

    echo $BINARYLANE_API_TOKEN

    If this returns nothing, the variable is not set.


  2. Setting the API Token Variable: To temporarily set your API token as an environment variable, use the following command:

    export BINARYLANE_API_TOKEN='your-api-token'

    Replace `your-api-token` with your actual BinaryLane API token.


    Important


    This variable will only last for the duration of the terminal session. Once the terminal session is terminated, this environment variable will be removed. 


  3. Unsetting the API Token Variable: If you need to unset this variable for any reason, simply run:

    unset BINARYLANE_API_TOKEN


After setting your API token as a system variable, you can incorporate it directly into your curl commands. Here's an example command to get a list of servers:

curl -X GET 'https://api.binarylane.com.au/v2/servers' \
-H "Authorization: Bearer $BINARYLANE_API_TOKEN" \
-H "Content-Type: application/json"


This command sends a `GET` request to the '/v2/servers' endpoint of the BinaryLane API and will return a JSON response containing details about your servers.



Filtering Responses 


Since the response from the API can be quite extensive, you might want to filter it to view only specific details. This is where `jq` comes in handy again. Here's how you can pipe the output of the `curl` command through `jq` to filter the response:


  1. Define the jq Filter: First, decide what information you want to extract. For example, to get only the names and statuses of your servers, you would use the following jq filter:

    .servers[] | {name, status}


  2. Combine `curl` and `jq`: Now, append the `jq` filter to the `curl` command using a pipe (` | `). The complete command looks like this:

    curl -X GET 'https://api.binarylane.com.au/v2/servers' \
    -H "Authorization: Bearer $BINARYLANE_API_TOKEN" \
    -H "Content-Type: application/json" | jq '.servers[] | {name, status}'

    This command will fetch the list of servers and then use `jq` to filter and display only the names and statuses.


  3. Running the Command: Execute the above command in your terminal. It will return a filtered list of server names and statuses in a clean, readable format. If no data is retrieved, ensure that your system variable is set correctly and that the authorisation bearer is pointing to the correct system variable.



Initiating a Time-Limited Shell Session with the API Token

When working with sensitive information like API tokens, it's often necessary to limit their accessibility. A practical solution is to set the environment variable for a fixed duration, ensuring it is automatically unset after this period. This can be achieved using the timeout command in combination with a script or command sequence.

The `timeout` command is part of the `coreutils` package, which should come pre-installed on most Linux distributions. If for some reason it's not installed, you can install it using your package manager, for example, `sudo apt-get install coreutils` for Ubuntu/Debian or `sudo yum install coreutils` for CentOS/Fedora. For other distributions, you may need to consult the relative distribution's package management documentation for exact installation commands.

To create a shell session where `BINARYLANE_API_TOKEN` is available only temporarily, use the following command:

timeout --foreground 3600 bash -c 'export BINARYLANE_API_TOKEN="your-api-token"; <your-commands-here>; unset BINARYLANE_API_TOKEN'


Make sure to replace `your-api-token` with your actual API token, `3600` with the number of seconds you want the token to be available and `<your-commands-here>` with the actual commands you want executed during this session, for example, suppose we just wanted to poll for server names and the status of the server (as we had done in our previous examples), we would execute the following command:

timeout --foreground 20 bash -c 'export BINARYLANE_API_TOKEN="your-api-token"; curl -X GET 'https://api.binarylane.com.au/v2/servers' \
-H "Authorization: Bearer $BINARYLANE_API_TOKEN" \
-H "Content-Type: application/json" | jq '.servers[] | {name, status}'; unset BINARYLANE_API_TOKEN'


The `--foreground` option ensures that the `timeout` command keeps the subshell active for the specified duration. In the above example, the duration for this session is 20 seconds, more than enough time to receive a response for this request type.

After the set duration, the timeout command terminates the subshell.

If you need to run multiple commands that rely on the API token, include them in place of `<your-commands-here>`.

The `unset BINARYLANE_API_TOKEN` command at the end is optional in this context because the subshell (and its environment variables) will terminate after the timeout. However, including it is a good practice, especially if you modify the script to run without a timeout later.




Windows method for CLI-Level interaction with the API


If you are familiar with or prefer using Windows Subsystem for Linux (WSL), you can follow the Linux guide mentioned earlier, as those instructions are fully compatible within the WSL environment. For those who prefer native Windows tools, PowerShell offers a flexible and robust solution for API interactions.


To interact with the BinaryLane API, you'll primarily be using PowerShell's web request cmdlets (please ensure that your system has the necessary modules for making web requests. PowerShell 5.1 and above comes with these modules pre-installed.):


  1. Setting the Environment Variable: In PowerShell, set the API token as an environment variable by executing:

    $Env:BINARYLANE_API_TOKEN = 'your-api-token'

    Replace `your-api-token` with the actual API token.


  2. Validating the Token: To ensure that the token is set correctly, you can display it using:

    Echo $Env:BINARYLANE_API_TOKEN


Making API Requests Using PowerShell


With your environment set up and API token configured, you're ready to make requests to the BinaryLane API:


  1. Forming the Request: Use `Invoke-RestMethod` or `Invoke-WebRequest`, PowerShell's native cmdlets, to make web requests. For example, to list all servers:

    $response = Invoke-RestMethod -Uri 'https://api.binarylane.com.au/v2/servers' -Method Get -Headers @{Authorization=("Bearer "+$Env:BINARYLANE_API_TOKEN)}


  2. Handling the Response: PowerShell automatically converts the JSON response into a PowerShell object, which you can then manipulate or display:

    $response | Select-Object -Property Name, Status


Filtering Responses


For filtering JSON responses, PowerShell's native capabilities can be used:


  1. Selecting Specific Fields: Use `Select-Object` to extract particular fields from the response. If your response contains an array of items, you might have to iterate over them using a loop or `ForEach-Object` cmdlet.

  2. Custom Filters: For more complex filtering, you can use PowerShell's scripting capabilities to process the data as required.




MacOS method for CLI-Level interaction with the API


Interacting with the BinaryLane API through the MacOS command line closely resembles the process used in Linux, thanks to MacOS's Unix-based architecture. This similarity means that tools like 'curl' and 'jq' are just as effective and can be utilised in much the same way.


MacOS users can interact with the BinaryLane API using the Terminal, which provides access to Unix command-line tools. The process begins with managing your API token as a system variable:


  1. Check if the API Token Variable Exists: Open the Terminal and run:

    echo $BINARYLANE_API_TOKEN

    If this returns nothing, the variable has not been set.


  2. Setting the API Token Variable: To set your API token as an environment variable, use:

    export BINARYLANE_API_TOKEN='your-api-token'

    Replace `your-api-token` with your actual BinaryLane API token. Note that this variable will only last for the duration of the terminal session.


  3. Unsetting the API Token Variable: If needed, unset this variable by running:

    unset BINARYLANE_API_TOKEN


Making API Requests with Curl


With the API token set, you can make API requests using 'curl':


  1. Basic Curl Request: To get a list of servers, for example, use:

    curl -X GET 'https://api.binarylane.com.au/v2/servers' \
    -H "Authorization: Bearer $BINARYLANE_API_TOKEN" \
    -H "Content-Type: application/json"

    This command sends a `GET` request to the BinaryLane API and returns a JSON response.



Filtering API Responses with jq


For more refined output, you can filter the API responses using `jq`:


  1. Define the jq Filter: Decide what information to extract. For instance, to get only the names and statuses of your servers:

    .servers[] | {name, status}


  2. Combine Curl and jq: Append the `jq` filter to the `curl` command:

    curl -X GET 'https://api.binarylane.com.au/v2/servers' \
    -H "Authorization: Bearer $BINARYLANE_API_TOKEN" \
    -H "Content-Type: application/json" | jq '.servers[] | {name, status}'

    This will return a filtered list of server names and statuses. Execute the command in the Terminal to see the filtered output. Ensure your API token (and associated variable ID) is correctly set and specified if no data is retrieved.