Skip to content

Python example applications

These examples require Python 3.7 and the httpx library which can be installed using pip.

Getting a sessionId

Copy this code and put it in a file called login.py. Run it with python login.py you@example.com, and it will ask for your password. If everything goes well it should then print out a sessionId that can be used to talk to the api.

import httpx, sys

def login(username):
    r = httpx.post(
        f'https://{host}/login',
        json={'username': username, 'password': getpass.getpass()}
    )
    return r.json()['sessionId']

if __name__ == '__main__':
    try:
        _, username = sys.argv
    except:
        print('Usage: python login.py mattias@yanzi.se')

    print(login(username))

Getting a list of groups

Copy the code below into a file called groups.py and run it by passing a cirrus host and sessionId. It should then make a request and print out all the groups which you are a member of. For legacy reasons groups are still called accounts in the API.

import httpx, sys

accounts_query = """
query {
  accounts {
    accountName
    accountNumber
  }
}
"""

def graphql(query, variables={}):
    r = httpx.post(
        f'https://{host}/graphql',
        headers={'Authorization': f'bearer {sessionId}'},
        json={'query': query, 'variables': variables}
    )
    return r.json()

if __name__ == '__main__':
    try:
        _, host, sessionId = sys.argv
    except:
        print("usage: python groups.py devshrek.yanzi.nu YW5kcmVhcy5tYXJ0ZW5...")
        sys.exit(1)

    print(graphql(accounts_query))

Making a simple CLI

Copy the below code into another file and run it. As you might notice, this program handles input of host, username, and password in three different ways. As the first three arguments on the command line, as environment variables, and by asking after launch. This is still just a very quick example, and as some comments say, it is probably a good idea look at some more libraries to help.

import httpx, getpass, pprint, sys, os, urllib.parse

accounts_query = """
query {
  accounts {
    accountName
    accountNumber
  }
}
"""

locations_query = """
query($after: String, $search: String) {
    locations(first: 10, after: $after, search: $search) {
        cursor
        list {
            name
            locationId
        }
    }
}
"""

devices_query = """
query($locationId: String!, $after: String) {
    location(locationId: $locationId) {
        units(first: 10, after: $after) {
            cursor
            list {
                name
                unitAddress {
                    did
                }
            }
        }
    }
}
"""

datasources_query = """
query($locationId: String!, $did: String!) {
    location(locationId: $locationId) {
        unit(did: $did) {
            dataSources {
                variableName
                siUnit
            }
        }
    }
}
"""

def login(host, username, password):
    r = httpx.post(
        f'https://{host}/login',
        json={'username': username, 'password': password}
    )
    return r.json()['sessionId']


def graphql(host, sessionId, query, variables={}):
    r = httpx.post(
        f'https://{host}/graphql',
        headers={'Authorization': f'bearer {sessionId}'},
        json={'query': query, 'variables': variables}
    )
    return r.json()

# This could be replaced with the argparse lib https://docs.python.org/3/library/argparse.html
def argv(index): return sys.argv[index] if len(sys.argv) > index else None

def get_host():
    return argv(1) or os.getenv('CIRRUS_HOST') or input('Host: ')

def get_session(host):
    username = argv(2) or os.getenv('CIRRUS_USER') or input('Username: ')
    password = argv(3) or os.getenv('CIRRUS_PASS') or getpass.getpass()

    return login(host, username, password)

def print_help():
    print("""
        exit
        help
        accounts
        locations [after=<cursor>&search=<name>]
        devices <locationId> [cursor]
        datasources <locationId> <did>

        """)

def main():
    host = os.getenv('CIRRUS_HOST') or get_host()
    sessionId = os.getenv('CIRRUS_SESSIONID') or get_session(host)

    # this could be replaced with the cmd lib https://docs.python.org/3/library/cmd.html
    while True:
        try:
            command, *args = input('>>> ').split(' ')
        except KeyboardInterrupt:
            break

        if command == 'exit':
            break
        elif command == 'help':
            print_help()
        elif command == 'accounts':
            pprint.pprint(graphql(host, sessionId, accounts_query))
        elif command == 'locations':
            variables = dict(urllib.parse.parse_qsl(args[0])) if len(args) else {}
            pprint.pprint(graphql(host, sessionId, locations_query, variables))
        elif command == 'devices':
            pprint.pprint(graphql(host, sessionId, devices_query, {'locationId': args[0], 'after': args[1] if len(args) > 1 else None}))
        elif command == 'datasources':
            pprint.pprint(graphql(host, sessionId, datasources_query, {'locationId': args[0], 'did': args[1]}))
        else:
            print('Unknown command', command)
            print_help()


if __name__ == '__main__':
    main()
Back to top