influxdb-client-swift
This repository contains the reference Swift client for the InfluxDB 2.0.
This section contains links to the client library documentation.
Features
InfluxDB 2.0 client consists of two packages
InfluxDBSwift
- Querying data using the Flux language
- Writing data
- batched in chunks on background
- automatic retries on write failures
InfluxDBSwiftApis
- provides all other InfluxDB 2.0 APIs for managing
- health check
- sources, buckets
- tasks
- authorizations
- …
- built on top of
InfluxDBSwift
- provides all other InfluxDB 2.0 APIs for managing
This package requires Swift 5 and Xcode 12.
- iOS 14.0+
- macOS 11.0+
- tvOS 14.0+
- watchOS 7.0+
- Linux
Installation
Add this line to your Package.swift
:
Creating a client
Specify url and token via parameters:
let client = InfluxDBClient(url: "http://localhost:8086", token: "my-token")
...
client.close()
Client Options
Configure default Bucket
, Organization
and Precision
let options: InfluxDBClient.InfluxDBOptions = InfluxDBClient.InfluxDBOptions(
bucket: "my-bucket",
org: "my-org",
precision: .ns)
let client = InfluxDBClient(url: "http://localhost:8086", token: "my-token", options: options)
...
client.close()
InfluxDB 1.8 API compatibility
client = InfluxDBClient(
url: "http://localhost:8086",
username: "user",
password: "pass",
database: "my-db",
retentionPolicy: "autogen")
...
client.close()
The WriteApi supports asynchronous writes into InfluxDB 2.0. The results of writes could be handled by (response, error)
, Swift.Result
or Combine
.
The data could be written as:
String
that is formatted as a InfluxDB’s Line Protocol- structure
- Tuple style mapping with keys:
measurement
,tags
,fields
andtime
- Array of above items
The following example demonstrates how to write data with Data Point structure. For further information see docs and examples.
import ArgumentParser
import Foundation
import InfluxDBSwift
struct WriteData: ParsableCommand {
@Option(name: .shortAndLong, help: "The name or id of the bucket destination.")
private var bucket: String
@Option(name: .shortAndLong, help: "The name or id of the organization destination.")
private var org: String
@Option(name: .shortAndLong, help: "Authentication token.")
private var token: String
@Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
private var url: String
public func run() {
// Initialize Client with default Bucket and Organization
let client = InfluxDBClient(
url: url,
token: token,
options: InfluxDBClient.InfluxDBOptions(bucket: self.bucket, org: self.org))
//
// Record defined as Data Point
//
let recordPoint = InfluxDBClient
.Point("demo")
.addTag(key: "type", value: "point")
.addField(key: "value", value: .int(2))
//
// Record defined as Data Point with Timestamp
//
let recordPointDate = InfluxDBClient
.Point("demo")
.addTag(key: "type", value: "point-timestamp")
.addField(key: "value", value: .int(2))
.time(time: .date(Date()))
client.makeWriteAPI().write(points: [recordPoint, recordPointDate]) { result, error in
// For handle error
if let error = error {
self.atExit(client: client, error: error)
}
// For Success write
if result != nil {
print("Written data:\n\n\([recordPoint, recordPointDate].map { "\t- \($0)" }.joined(separator: "\n"))")
print("\nSuccess!")
}
self.atExit(client: client)
}
// Wait to end of script
RunLoop.current.run()
}
private func atExit(client: InfluxDBClient, error: InfluxDBClient.InfluxDBError? = nil) {
// Dispose the Client
client.close()
// Exit script
Self.exit(withError: error)
}
}
WriteData.main()
- sources -
Queries
- Lazy sequence of FluxRecord
- Raw query response as a
Data
.
Query to FluxRecord
import ArgumentParser
import Foundation
import InfluxDBSwift
struct QueryCpu: ParsableCommand {
@Option(name: .shortAndLong, help: "The bucket to query. The name or id of the bucket destination.")
private var bucket: String
@Option(name: .shortAndLong,
help: "The organization executing the query. Takes either the `ID` or `Name` interchangeably.")
private var org: String
@Option(name: .shortAndLong, help: "Authentication token.")
private var token: String
@Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
private var url: String
public func run() {
// Initialize Client with default Organization
url: url,
token: token,
options: InfluxDBClient.InfluxDBOptions(org: self.org))
// Flux query
let query = """
from(bucket: "\(self.bucket)")
|> range(start: -10m)
|> filter(fn: (r) => r["_measurement"] == "cpu")
|> filter(fn: (r) => r["cpu"] == "cpu-total")
|> filter(fn: (r) => r["_field"] == "usage_user" or r["_field"] == "usage_system")
|> last()
"""
print("\nQuery to execute:\n\n\(query)")
client.queryAPI.query(query: query) { response, error in
// For handle error
if let error = error {
self.atExit(client: client, error: error)
}
// For Success response
if let response = response {
print("\nSuccess response...\n")
print("CPU usage:")
do {
try response.forEach { record in
print("\t\(record.values["_field"]!): \(record.values["_value"]!)")
}
} catch {
self.atExit(client: client, error: InfluxDBClient.InfluxDBError.cause(error))
}
}
}
// Wait to end of script
RunLoop.current.run()
}
private func atExit(client: InfluxDBClient, error: InfluxDBClient.InfluxDBError? = nil) {
// Dispose the Client
client.close()
// Exit script
Self.exit(withError: error)
}
}
QueryCpu.main()
- sources -
Query to Data
Parameterized queries
InfluxDB Cloud supports Parameterized Queries that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more reusable and can also be used to help prevent injection attacks.
InfluxDB Cloud inserts the params object into the Flux query as a Flux record named params
. Use dot or bracket notation to access parameters in the params
record in your Flux query. Parameterized Flux queries support only int
, float
, and string
data types. To convert the supported data types into other .
Parameterized query example:
import ArgumentParser
import Foundation
import InfluxDBSwift
struct ParameterizedQuery: ParsableCommand {
@Option(name: .shortAndLong, help: "The bucket to query. The name or id of the bucket destination.")
private var bucket: String
@Option(name: .shortAndLong,
help: "The organization executing the query. Takes either the `ID` or `Name` interchangeably.")
private var org: String
@Option(name: .shortAndLong, help: "Authentication token.")
private var token: String
@Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
private var url: String
public func run() {
// Initialize Client with default Organization
let client = InfluxDBClient(
url: url,
token: token,
options: InfluxDBClient.InfluxDBOptions(org: self.org))
// Flux query
let query = """
from(bucket: params.bucketParam)
|> range(start: duration(v: params.startParam))
|> filter(fn: (r) => r["_measurement"] == "cpu")
|> filter(fn: (r) => r["cpu"] == "cpu-total")
|> filter(fn: (r) => r["_field"] == "usage_user" or r["_field"] == "usage_system")
|> last()
"""
// Query parameters [String:String]
let queryParams = [ "bucketParam":"\(self.bucket)", "startParam":"-10m" ]
print("\nQuery to execute:\n\n\(query)\n\n\(queryParams)")
client.queryAPI.query(query: query, params: queryParams) { response, error in
// For handle error
if let error = error {
self.atExit(client: client, error: error)
}
// For Success response
if let response = response {
print("\nSuccess response...\n")
print("CPU usage:")
do {
try response.forEach { record in
print("\t\(record.values["_field"]!): \(record.values["_value"]!)")
}
} catch {
self.atExit(client: client, error: InfluxDBClient.InfluxDBError.cause(error))
}
}
self.atExit(client: client)
}
// Wait to end of script
RunLoop.current.run()
}
private func atExit(client: InfluxDBClient, error: InfluxDBClient.InfluxDBError? = nil) {
// Dispose the Client
client.close()
// Exit script
Self.exit(withError: error)
}
}
ParameterizedQuery.main()
- sources - ParameterizedQuery/main.swift
The supports deletes points from an InfluxDB bucket. Use the identifies which points to delete.
import ArgumentParser
import Foundation
import InfluxDBSwift
struct DeleteData: ParsableCommand {
@Option(name: .shortAndLong, help: "Specifies the bucket name to delete data from.")
private var bucket: String
@Option(name: .shortAndLong,
help: "Specifies the organization name to delete data from.")
private var org: String
@Option(name: .shortAndLong, help: "Authentication token.")
private var token: String
@Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
private var url: String
@Option(name: .shortAndLong, help: "InfluxQL-like delete predicate statement.")
private var predicate: String
public func run() {
// Initialize Client with default Organization
let client = InfluxDBClient(
url: url,
token: token,
options: InfluxDBClient.InfluxDBOptions(org: self.org))
// Create DeletePredicateRequest
let predicateRequest = DeletePredicateRequest(
start: Date(timeIntervalSince1970: 0),
stop: Date(),
predicate: predicate)
client.deleteAPI.delete(predicate: predicateRequest, bucket: bucket, org: org) { result, error in
// For handle error
if let error = error {
self.atExit(client: client, error: error)
}
// For Success Delete
if result != nil {
print("\nDeleted data by predicate:\n\n\t\(predicateRequest)")
// Print date after Delete
queryData(client: client)
}
}
// Wait to end of script
RunLoop.current.run()
}
private func queryData(client: InfluxDBClient) {
from(bucket: "\(self.bucket)")
|> range(start: 0)
|> filter(fn: (r) => r["_measurement"] == "server")
|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
"""
client.queryAPI.query(query: query) { response, error in
// For handle error
if let error = error {
self.atExit(client: client, error: error)
}
// For Success response
if let response = response {
print("\nRemaining data after delete:\n")
do {
try response.forEach { record in
let provider = record.values["provider"]!
let production = record.values["production"]
let app = record.values["app"]
}
} catch {
self.atExit(client: client, error: InfluxDBClient.InfluxDBError.cause(error))
}
}
self.atExit(client: client)
}
}
private func atExit(client: InfluxDBClient, error: InfluxDBClient.InfluxDBError? = nil) {
// Dispose the Client
client.close()
// Exit script
Self.exit(withError: error)
}
}
DeleteData.main()
- sources - DeleteData/main.swift
Management API
The client supports following management API:
The following example demonstrates how to use a InfluxDB 2.0 Management API to create new bucket. For further information see docs and .
import ArgumentParser
import Foundation
import InfluxDBSwift
import InfluxDBSwiftApis
struct CreateNewBucket: ParsableCommand {
@Option(name: .shortAndLong, help: "New bucket name.")
private var name: String
@Option(name: .shortAndLong, help: "Duration bucket will retain data.")
private var retention: Int = 3600
@Option(name: .shortAndLong, help: "The ID of the organization.")
private var orgId: String
@Option(name: .shortAndLong, help: "Authentication token.")
private var token: String
@Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
private var url: String
public func run() {
// Initialize Client and API
let client = InfluxDBClient(url: url, token: token)
let api = InfluxDB2API(client: client)
// Bucket configuration
let request = PostBucketRequest(
orgID: self.orgId,
name: self.name,
retentionRules: [RetentionRule(type: RetentionRule.ModelType.expire, everySeconds: self.retention)])
// Create Bucket
api.bucketsAPI.postBuckets(postBucketRequest: request) { bucket, error in
// For error exit
if let error = error {
self.atExit(client: client, error: error)
}
if let bucket = bucket {
// Create Authorization with permission to read/write created bucket
let bucketResource = Resource(
type: Resource.ModelType.buckets,
id: bucket.id!,
orgID: self.orgId
)
// Authorization configuration
let request = Authorization(
description: "Authorization to read/write bucket: \(self.name)",
orgID: self.orgId,
permissions: [
Permission(action: Permission.Action.read, resource: bucketResource),
Permission(action: Permission.Action.write, resource: bucketResource)
])
// Create Authorization
api.authorizationsAPI.postAuthorizations(authorization: request) { authorization, error in
// For error exit
if let error = error {
atExit(client: client, error: error)
}
// Print token
if let authorization = authorization {
let token = authorization.token!
print("The token: '\(token)' is authorized to read/write from/to bucket: '\(bucket.id!)'.")
atExit(client: client)
}
}
}
}
// Wait to end of script
RunLoop.current.run()
}
private func atExit(client: InfluxDBClient, error: InfluxDBError? = nil) {
// Dispose the Client
client.close()
// Exit script
Self.exit(withError: error)
}
}
CreateNewBucket.main()
- sources - CreateNewBucket/main.swift
Advanced Usage
Sometimes is useful to store same information in every measurement e.g. hostname
, location
, customer
. The client is able to use static value or env variable as a tag value.
The expressions:
California Miner
- static value${env.HOST_NAME}
- environment property
Example
client = InfluxDBClient(
url: "http://localhost:8086",
token: "my-token",
options: InfluxDBClient.InfluxDBOptions(bucket: "my-bucket", org: "my-org"))
let tuple: InfluxDBClient.Point.Tuple
= (measurement: "mem", tags: ["tag": "a"], fields: ["value": .int(3)], time: nil)
let records: [Any] = [
InfluxDBClient.Point("mining")
.addTag(key: "sensor_state", value: "normal")
.addField(key: "depth", value: .int(2)),
tuple
]
let defaultTags = InfluxDBClient.PointSettings()
.addDefaultTag(key: "customer", value: "California Miner")
.addDefaultTag(key: "sensor_id", value: "${env.SENSOR_ID}")
let writeAPI = client.makeWriteAPI(pointSettings: defaultTags)
writeAPI.writeRecords(records: records) { _, error in
if let error = error {
print("Error: \(error)")
return
}
print("Successfully written default tags")
}
Example Output
mining,customer=California\ Miner,sensor_id=123-456-789,sensor_state=normal depth=2i
mining,customer=California\ Miner,sensor_id=123-456-789,sensor_state=normal pressure=3i
Proxy and redirects
For more info see - , Global Proxy Settings Constants.
Redirects
Client automatically follows HTTP redirects. You can disable redirects by an urlSessionDelegate
configuration:
class DisableRedirect: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(nil)
}
}
let options = InfluxDBClient.InfluxDBOptions(
bucket: "my-bucket",
org: "my-org",
urlSessionDelegate: DisableRedirect())
client = InfluxDBClient(url: "http://localhost:8086", token: "my-token", options: options)
For more info see - .
If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master
branch.
Build Requirements:
- swift 5.3 or higher
Build source and test targets:
swift build --build-tests
Run tests:
./Scripts/influxdb-restart.sh
swift test
Check code coverage:
./Scripts/influxdb-restart.sh
swift test --enable-code-coverage
You could also use a docker-cli
without installing the Swift SDK:
make docker-cli
License
The client is available as open source under the terms of the MIT License.