Python examples
Introduction
This guide shows how to read and write data with the Factry Historian API using Python. For a full overview of the Factry Historian API requests is available in the Swagger specification.
Target Audience
This guide is written for technical users who are comfortable working with a REST API and basics commands on a CLI.
Prerequisites
- Python 3.9 or newer
- An API TokenAPI Token of a Factry Historian user with the according privileges
- The UUID of the OrganizationOrganization in Factry Historian
Line 1 creates a virtual Python environment (choose the package manager pip or uv). Line 2 activates the virtual environment:
- For Linux or Mac: replace with command source .venv/bin/activate
python -m venv .venv
.venv/bin/activate
pip install --upgrade pip
pip install requestsLines 3 and 4 upgrade the package manager and install the requests package.
Import packages and create API session
In your environment, set the following variables:
- Replace BASE_URLwith your Factry Historian wepage url + /api
- Replace ORG_UUID with your Factry Historian Organization UUID
- Replace TOKEN with your Factry Historian API token
It is recommended to keep sensitive values out of your code by using environment variables.
This code imports the necessary Python packages and sets the BASE_URL, ORG_UUID and TOKEN from the environment variables. It creates an API session and sets the request headers in the session to be able to re-use them over multiple requests.
import os
import json
import requests
from typing import List, Dict, Any, Optional
BASE_URL = os.environ.get("HISTORIAN_BASE_URL", "https://historian.mycompany.com:18000/api")
ORG_UUID = os.environ["HISTORIAN_ORG_UUID"]
TOKEN = os.environ["HISTORIAN_API_TOKEN"]
session = requests.Session()
session.headers.update({
"Content-Type": "application/json",
"Accept": "application/json",
"x-organization-uuid": ORG_UUID,
"Authorization": f"Bearer {TOKEN}"
})API Interaction
The code above serves as a prerequisite for the following examples:
- Manage Time Series Databases: listing existing databases
- Manage Collectors: creating a collector and listing existing collectors
- Manage Measurements: creating, updating and deleting measurements
- Query Time Series Data: read data from measurements
- Write Time Series Data: write data to measurements
- Query Event Data: read data from events
- Write Event Property Data: create or update event data
The examples list https://historian.mycompany.com:18000/api as the base url (replace with your own) and use a request timeout of 30 seconds.