Essentials
This article contains the description of flespi API usage. Key points:
There are 2 types of API: HTTP REST API and event based MQTT API
Flespi UI is built using API: everything you see in flespi UI can be embedded into your solution over API
API usage is authorized by tokens
REST API
HTTP REST API call consists of: method, headers, URL (with optional query variables) and body.
Header is used to authorize the request like
Authorization: FlespiToken XXXXXXXXX
According to the concepts of REST API, method is used for:
GET - receive information - items, messages, logs, etc. (in GET method request parameters are passed as URL query data variable)
POST - create new item
DELETE - remove item
PUT - modify existing item (PATCH - partly modify)
Body with the request configuration is always in JSON format, exact structure and schema varies for each request and specified in the documentation.
URL - consists of:
path - hierarchical specification of the request that may include highly customizable REST selectors of the target items
fields list to limit the amount of the info of each item be returned in the response
pagination options to reduce the number of items
REST selectors
REST selectors are used to specify the items to apply REST API call to.
There are several ways to select items using REST selectors. Following examples are based on GET gw/devices request to show the different options to filter devices list:
- “all” keyword to select all possible items.
IDs list: each flespi item has an internal flespi ID that can be used in a comma-separated list in the selector.
By item field value using syntax field_name=value. E.g. this request will return all devices that work over the wialon-ips protocol. Wildcard characters are: ? (single character, e.g. filter devices with model FMB640, FMC640 and FMM640) and * (multiple characters, e.g devices with IMEI that start with 86435) can be used in value.
- By assignment to a group.
- By {expression} which is a flespi-standard way to analyze messages, calculate counters or compile webhook payloads. The variables available for calculation are item fields. Expression must be enclosed in {curved brackets}.
For device selector also telemetry, plugin fields, metadata may be used.
Use-case: select devices that | Selector value |
belong to 2 different subaccounts | {cid=123 || cid=456} |
have can.vehicle.mileage parameter in telemetry | {exists("telemetry.can.vehicle.mileage")} |
have item-fields plugin field driver.name starts from "Andrew" substring | plugins.fields.driver.name=Andrew* |
has fleet_id with value 10 in its metadata property | metadata.fleet_id=10 |
belong to a group with ID 1234 | groups.id=1234 |
all Teltonika devices | protocol_name="teltonika" |
all devices of specified type Teltonika FMC640 | device_type_name="fmc640" |
all Concox devices in group with ID 1234 | groups.id=1234,protocol_name="concox" |
all Queclink GV500 devices with engine.ignition.status ON | device_type_name="gv500", telemetry.engine.ignition.status=true |
not delivered any data to flespi for more than 24 hours | {last_active < (now() - 86400)} |
located within 100 km from point with latitude 54.72 and longitude 25.26 | {distance(telemetry.position.latitude, telemetry.position.longitude, 54.72, 25.26) < 100} |
Fields and Pagination
Fields query variable is used to specify the exact number of fields of the items to be returned in response. If the item to be returned has non-plain structure, it is possible to specify comma separated path entries in the fields. E.g. to fetch devices list with ident and phone fields from configuration object and id field this request can be used.
Pagination query variables limit and offset can be used to fetch a limited number of items starting from a specific position. Offset is 0-based, so if you have 20 devices and you want to get them in 2 requests by chunks of 10 items then you should perform the request like
GET /gw/devices/all?limit=10&offset=0
GET /gw/devices/all?limit=10&offset=10
The response would be like:
{
"result": [{},{},...],
"pagination": {"limit": X, "offset": Y, "count": Z}
}
Where count is the total amount of items.
MQTT API
MQTT protocol is designed for secure and stable telemetry transport. In flespi it might be efficiently utilized to consume live events like device messages, calculated intervals or logs. Code snippets on different programming languages can be found on flespi Github page.
MQTT broker specification
Connection configuration | |
Host | mqtt.flespi.io |
Port | MQTT over TCP: 8883 (SSL) or 1883 (non-SSL) MQTT over WebSockets: 443 (SSL) or 80 (non-SSL) |
MQTT version | 3.1, 3.1.1, 5.0 |
QoS supported | QoS 0, QoS 1 |
Authorization | flespi token as username or password or username=token ID, password=at least 16 first bytes of the token key |
MQTT concepts:
- client id should be unique within your account space
- subscription topics may have wildcard masks: + for one level, # for rest till the end
- non-clean sessions store undelivered messages and deliver it upon session reconnect
- you can't publish to topic that starts from flespi/ - it is reserved for MQTT API
- message published with retained flag is stored in broker and delivered upon subscription
Standard flespi topics
All the events published via flespi MQTT API are covered by MQTT Topics Directory tool
Topic filtering
Subscription topic may contain special prefix that enables server side message filtering. It allows to reduce the number of messages received by the MQTT client. The common format of the topic is:
$filter/<filter-specification>/original-topic
Messages can be filtered by:
- subaccount ID. E.g. to get messages published by devices that belong to subaccount with ID=123 the subscription topic is: $filter/cid=123/flespi/message/gw/devices/+
- publication time. E.g. to receive only messages published after 11/14/2023 22:13:20 GMT subscription topic is $filter/modified_since=1700000000/flespi/message/gw/devices/+
- payload. When you filter by payload, the filter is executed as expression and must be url-encoded. E.g. if you subscribe for battery.voltage telemetry and want to receive only messages when voltage is higher than 14 volts, then subscription topic is $filter/payload=tonumber%28payload%29%3E14/flespi/state/gw/devices/+/telemetry/battery.voltage . Here the payload is number, filter value is tonumber(payload)>14
- complex message object expression. Message filter can be filtered by expression that may refer to:
- topic - a topic string
- topics - an array with topic words splited by '/'
- cid - publisher id
- timestamp - message timestamp
- user_properties - an object with list of user properties
- payload - a string with message payload
e.g. we have following topics: temperature/kitchen, temperature/bedroom, temperature/hall. Message payload is a temperature. So we want to receive temperature from kitchen and hall if it is below 20 degrees.
Message filter is: (topics[1]=="kitchen"||topics[1]=="hall")&&tonumber(payload)<20
Subscription with encoded filter is: $filter/message=(topics%5B1%5D%3D%3D%22kitchen%22%7C%7Ctopics%5B1%5D%3D%3D%22hall%22)%26%26tonumber(%22payload%22)%3C20/temperature/+
MQTT over REST
Publish to topic flespi/rest/{method}/{api-uri} to perform REST API call to the flespi platform. {method} should be lowercase and valid for the specified {api-uri}. Optional data parameter may be passed as MQTT message payload. MQTT v5.0 accepts "response topic" parameter with the indication of the topic to which to publish a response to API call. Otherwise, the response is published to the same topic.
Additional user property "response_cid" allows redirecting the response to another subaccount. This is a special feature helpful when you want to perform an API call on the top-level (from the master account) and redirect its result from the flespi broker directly to one of the subaccounts.
One more feature is the "response_chunked" user property. If it's "true", the response will be chunked in multiple MQTT messages. A message with the specified "http_code" user property is the indication of the last chunk (message).
Learn more in the corresponding blog article.