Skip to content
Connect > Client Libraries

Quickstart: Query and Subscribe from a Client Program

This quickstart connects a Python script or a C++ program to a 3forge Enterprise instance, runs a SQL query, and receives a live update when a row changes.

The steps are shell commands and one program, in Python or C++. To publish from Java instead, start with the Java client.

Prerequisites

  • A running 3forge Enterprise instance with its default security settings, and access to its installation directory, to edit keys/3forge.auth and restart the instance.
  • A user that can log in to the instance. The program below uses the default demo login; replace it with a login of your own.
  • The openssl and ssh-keygen command-line tools. Git for Windows and Ubuntu include both.
  • For Python: Python 3.14 and the pyami-3forge package from the Python Package Index, installed with pip install pyami-3forge.
  • For C++: the client library, whose source 3forge provides as a download assigned to your account, built with a C++20 compiler, CMake 3.21 or later, and OpenSSL development files: OpenSSL 3 on Linux, OpenSSL 4.1 on Windows. See Building the library.

1. Create a client certificate

A default install accepts a client only if it presents a certificate whose public key is listed on the server.

  1. In an empty working directory, create a private key and a certificate:

    openssl req -x509 -newkey rsa:2048 -nodes -keyout client.key.pem -out client.crt.pem -days 365 -batch
    
  2. Write the certificate's public key as an ssh-rsa line:

    ssh-keygen -y -f client.key.pem > client.pub
    
  3. Confirm that the key was written: run cat client.pub, and the output is one line starting ssh-rsa AAAA.

The key must be RSA: the server accepts no other key type.

2. Authorize the certificate on the instance

The server reads its list of allowed client keys only when it starts.

  1. Append the line to the authorized-clients file, from the installation directory:

    cat /path/to/client.pub >> keys/3forge.auth
    
  2. Restart the instance.

  3. Copy the server's public key, keys/3forge.pub, into the working directory, so the program can check it is talking to this server.
  4. Confirm that the key was added: run tail -n 1 keys/3forge.auth, and the output is the ssh-rsa line from client.pub. Stage 4 confirms that the server accepts it.

A key added without a restart is still refused

Adding a key, or removing one, takes effect only after a restart. Until then, a newly added key is rejected and a removed key is still accepted.

3. Write the program

The program opens the SQL connection and the Center connection, runs a query, subscribes to a table, and changes a row in it.

  1. Save the program in the language you use:

    Save the following code as quickstart.py in the working directory:

    import time
    from pyami.rt.ami_client import (AmiClient, AmiCluster, AmiDatabaseConfig,
                                     AmiSslOptions, AmiSubscriptionConfig)
    
    HOST = "localhost"
    USERNAME = "demo"
    PASSWORD = "demo123"
    
    keys = AmiSslOptions(trusted_server_pub_file="3forge.pub",
                         client_cert_file="client.crt.pem",
                         client_key_file="client.key.pem")
    
    
    class Listener:
        def on_log(self, client, name, level, message):
            if level >= 3:
                print("error:", name, message)
    
        def on_update(self, client, name, update):
            print("update:", update.action, update.table_name,
                  dict(zip(update.field_names, update.row_data)))
    
    
    client = AmiClient()
    client.add_listener(Listener())
    
    sql_config = AmiDatabaseConfig("3280", True, USERNAME, PASSWORD)
    sql_config.shards[0].ssl = keys
    center_config = AmiSubscriptionConfig("3270", True)
    center_config.shards[0].ssl = keys
    
    cluster = AmiCluster("N1", HOST)
    cluster.database_config = sql_config
    cluster.subscription_config = center_config
    client.add_cluster(cluster, sync=True)
    
    print(client.sql("N1", "SELECT 1"))
    
    client.sql("N1", "CREATE PUBLIC TABLE Quotes (sym String, px Double)")
    client.subscribe("N1", ["Quotes"], sync=True)
    client.sql("N1", 'INSERT INTO Quotes VALUES ("IBM", 183.5)')
    client.sql("N1", 'UPDATE Quotes SET px = 184.0 WHERE sym == "IBM"')
    time.sleep(2)
    
    client.sql("N1", "DROP TABLE Quotes")
    client.remove_cluster("N1", sync=True)
    

    Save the following code as quickstart.cpp in the working directory:

    #include "ami_client.hpp"
    
    #include <chrono>
    #include <iostream>
    #include <memory>
    #include <thread>
    
    struct Listener : ami::ClientListener {
        void on_log(ami::Client &, std::string_view name, std::uint8_t level, std::string_view message) override
        {
            if (level >= 3)
                std::cout << "error: " << name << " " << message << std::endl;
        }
        void on_update(ami::Client &, std::string_view, const CenterIncrementalUpdate & update) override
        {
            std::cout << "update: " << update << std::endl;
        }
    };
    
    int main()
    {
        ami::SslOptions keys;
        keys.trusted_server_pub_file = "3forge.pub";
        keys.client_cert_file = "client.crt.pem";
        keys.client_key_file = "client.key.pem";
    
        ami::Client client;
        client.listener_add(std::make_shared<Listener>());
    
        ami::Cluster cluster("N1", "localhost");
        cluster.database_config() = ami::DatabaseConfig("3280", true, {}, "demo", "demo123");
        cluster.database_config().shards[0].ssl = keys;
        cluster.subscription_config() = ami::SubscriptionConfig("3270");
        cluster.subscription_config().shards[0].ssl = keys;
        client.add_cluster(cluster, true);
    
        client.sql("N1", "SELECT 1")->print(std::cout);
    
        client.sql("N1", "CREATE PUBLIC TABLE Quotes (sym String, px Double)");
        client.subscribe("N1", {"Quotes"}, true);
        client.sql("N1", "INSERT INTO Quotes VALUES (\"IBM\", 183.5)");
        client.sql("N1", "UPDATE Quotes SET px = 184.0 WHERE sym == \"IBM\"");
        std::this_thread::sleep_for(std::chrono::seconds(2));
    
        client.sql("N1", "DROP TABLE Quotes");
        client.remove_cluster("N1", true);
    }
    
  2. For C++, compile the program against the library, replacing the AMI_SRC path with the library's source directory:

    1
    2
    3
    AMI_SRC=/path/to/ami_client_common
    g++ -std=c++20 quickstart.cpp -I "$AMI_SRC" -L "$AMI_SRC/build/linux-release/src" \
        -lami_client_common -lssl -lcrypto -lpthread -o quickstart
    

    Compile from a 64-bit prompt: the "x64 Native Tools Command Prompt" for Visual Studio 2026, or a "Developer Command Prompt for VS 2026" set up with VsDevCmd.bat -arch=x64. The default prompt builds 32-bit programs, which fail to link against the 64-bit library with LNK4272 and LNK1120:

    1
    2
    3
    set AMI_SRC=C:\path\to\ami_client_common
    cl /std:c++20 /EHsc /O2 /I "%AMI_SRC%" quickstart.cpp /link "%AMI_SRC%\build\windows-msvc-x64\src\Release\ami_client_common.lib"
    copy "%AMI_SRC%\build\windows-msvc-x64\src\Release\ami_client_common.dll" .
    
  3. Confirm that the files are in place: run ls, and the output lists the program, client.crt.pem, client.key.pem, and 3forge.pub.

4. Run it

Running the program shows whether the server accepted the certificate, and the update arriving.

  1. Run the program:

    python quickstart.py
    
    LD_LIBRARY_PATH="$AMI_SRC/build/linux-release/src" ./quickstart
    
    set PATH=C:\Program Files\OpenSSL-Win64\bin;%PATH%
    quickstart.exe
    
  2. Check that the output shows the query result, then one update:

    {'1': array([1], dtype=int32)}
    update: 1 Quotes {'sym': 'IBM', 'px': 184.0}
    
    1
    2
    3
    4
    5
    6
    7
    8
    Table: _
    Rows: 1, Columns: 1
    +---+---+
    | # | 1 |
    +---+---+
    | 0 | 1 |
    +---+---+
    update: {seqnum: 111, action: 1, id: 1360, table: Quotes, object_id: , fields: {sym: IBM, px: 184, }}
    

    The seqnum and id values differ from run to run.

The insert and the update arrive as one update, action 1 (added), carrying the updated price, because the server combines changes made to a row within one refresh. A later change arrives as action 2 (updated) with only the changed columns.

A refused certificate looks like a successful connection

If the server does not accept the certificate, add_cluster still returns without an error. The signs are lines in the log, such as Synchronous operation failed: ..., and an empty query result: {} in Python, or no table in C++. Check the result of SELECT 1, not the connection. See The client connects but queries return nothing.

Result

The program connects over mutual TLS, runs a query, subscribes to Quotes, and receives the row as an update. Next: