add: Develop with the API.

* Copied API intro and clients docs to /api.
* Added bootstrapping info.
pull/2853/head
Jason Stirnaman 2021-06-09 17:35:07 -05:00
parent 4f3d267166
commit 80acfc79fd
16 changed files with 749 additions and 1 deletions

2
.gitignore vendored
View File

@ -5,4 +5,4 @@ public
node_modules
*.log
/resources
/content/influxdb/*/api/**
/content/influxdb/*/api/*.html

View File

@ -0,0 +1,11 @@
---
title: Develop with the InfluxDB API
seotitle: Use the InfluxDB API
description: Interact with InfluxDB Cloud using a rich API for writing and querying data and more.
weight: 3
menu:
influxdb_cloud:
name: Develop with the API
---
{{< duplicate-oss >}}

View File

@ -0,0 +1,17 @@
---
title: Use InfluxDB client libraries
description: >
InfluxDB client libraries are language-specific tools that integrate with the InfluxDB v2 API.
View the list of available client libraries.
weight: 101
aliases:
- /influxdb/cloud/reference/client-libraries/
- /influxdb/cloud/reference/api/client-libraries/
menu:
influxdb_cloud:
name: Use client libraries
parent: Develop with the API
influxdb/cloud/tags: [client libraries]
---
{{< duplicate-oss >}}

View File

@ -0,0 +1,39 @@
---
title: Develop with the InfluxDB API
seotitle: Use the InfluxDB API
description: Interact with InfluxDB 2.0 using a rich API for writing and querying data and more.
weight: 3
menu:
influxdb_2_0:
name: Develop with the API
---
InfluxDB offers a rich API that you can integrate into your applications.
This section will guide you through the most commonly used API methods.
For detailed documentation on the entire API, see [InfluxDBv2 API Documentation](/influxdb/v2.0/reference/api/#influxdb-v2-api-documentation).
{{% note %}}
If you are interacting with InfluxDB 1.x, see the [1.x compatibility API](/influxdb/v2.0/reference/api/influxdb-1x/).
{{% /note %}}
## Bootstrap your application
Prerequisites:
1. [Install](/influxdb/v2.0/install/) and run InfluxDB OSS v2.x,
2. [Install Influx CLI](influxdb/v2.0/get-started/)
With most API requests, you'll need to provide a minimum of your InfluxDB URL,
Organization, and Authorization Token.
### Create an authorization token
Before diving into the API, use the InfluxDB UI to
[create your initial authorization token](/influxdb/v2.0/security/tokens/create-token/).
## Write API
[Write data to InfluxDB](/influxdb/v2.0/write-data/developer-tools/api/) using an HTTP request to the InfluxDB API `/write` endpoint.
## Query API
[Query from InfluxDB](/influxdb/v2.0/query-data/execute-queries/influx-api/) using an HTTP request to the `/query` endpoint.

View File

@ -0,0 +1,25 @@
---
title: Use InfluxDB client libraries
description: >
InfluxDB client libraries are language-specific tools that integrate with the InfluxDB v2 API.
View the list of available client libraries.
weight: 101
aliases:
- /influxdb/v2.0/reference/client-libraries/
- /influxdb/v2.0/reference/api/client-libraries/
menu:
influxdb_2_0:
name: Use client libraries
parent: Develop with the API
influxdb/v2.0/tags: [client libraries]
---
InfluxDB client libraries are language-specific packages that integrate with the InfluxDB v2 API.
The following **InfluxDB v2** client libraries are available:
{{% note %}}
These client libraries are in active development and may not be feature-complete.
This list will continue to grow as more client libraries are released.
{{% /note %}}
{{< children type="list" >}}

View File

@ -0,0 +1,13 @@
---
title: InfluxDB Arduino client library
list_title: Arduino
description: Use the Arduino client library to interact with InfluxDB.
external_url: https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino
list_note: _ contributed by [tobiasschuerg](https://github.com/tobiasschuerg)_
menu:
influxdb_2_0:
name: Arduino
parent: Use client libraries
url: https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino
weight: 201
---

View File

@ -0,0 +1,12 @@
---
title: InfluxDB C# client library
list_title: C#
description: Use the C# client library to interact with InfluxDB.
external_url: https://github.com/influxdata/influxdb-client-csharp
menu:
influxdb_2_0:
name: C#
parent: Use client libraries
url: https://github.com/influxdata/influxdb-client-csharp
weight: 201
---

View File

@ -0,0 +1,205 @@
---
title: Go client library
seotitle: InfluxDB Go client library
list_title: Go
description: >
Use the Go client library to interact with InfluxDB.
menu:
influxdb_2_0:
name: Go
parent: Use client libraries
influxdb/v2.0/tags: [client libraries, Go]
weight: 201
aliases:
- /influxdb/v2.0/reference/api/client-libraries/go/
---
Use the [InfluxDB Go client library](https://github.com/influxdata/influxdb-client-go) to integrate InfluxDB into Go scripts and applications.
This guide presumes some familiarity with Go and InfluxDB.
If just getting started, see [Get started with InfluxDB](/influxdb/v2.0/get-started/).
## Before you begin
1. [Install Go 1.13 or later](https://golang.org/doc/install).
2. Add the client package your to your project dependencies.
```sh
# Add InfluxDB Go client package to your project go.mod
go get github.com/influxdata/influxdb-client-go
```
3. Ensure that InfluxDB is running and you can connect to it.
For information about what URL to use to connect to InfluxDB OSS or InfluxDB Cloud, see [InfluxDB URLs](/influxdb/v2.0/reference/urls/).
## Boilerplate for the InfluxDB Go Client Library
Use the Go library to write and query data from InfluxDB.
1. In your Go program, import the necessary packages and specify the entry point of your executable program.
```go
package main
import (
"context"
"fmt"
"time"
"github.com/influxdata/influxdb-client-go/v2"
)
```
2. Define variables for your InfluxDB [bucket](/influxdb/v2.0/organizations/buckets/), [organization](/influxdb/v2.0/organizations/), and [token](/influxdb/v2.0/security/tokens/).
```go
bucket := "example-bucket"
org := "example-org"
token := "example-token"
// Store the URL of your InfluxDB instance
url := "http://localhost:8086"
```
3. Create the the InfluxDB Go client and pass in the `url` and `token` parameters.
```go
client := influxdb2.NewClient(url, token)
```
4. Create a **write client** with the `WriteAPIBlocking` method and pass in the `org` and `bucket` parameters.
```go
writeAPI := client.WriteAPIBlocking(org, bucket)
```
5. To query data, create an InfluxDB **query client** and pass in your InfluxDB `org`.
```go
queryAPI := client.QueryAPI(org)
```
## Write data to InfluxDB with Go
Use the Go library to write data to InfluxDB.
1. Create a [point](/influxdb/v2.0/reference/glossary/#point) and write it to InfluxDB using the `WritePoint` method of the API writer struct.
2. Close the client to flush all pending writes and finish.
```go
p := influxdb2.NewPoint("stat",
map[string]string{"unit": "temperature"},
map[string]interface{}{"avg": 24.5, "max": 45},
time.Now())
writeAPI.WritePoint(context.Background(), p)
client.Close()
```
### Complete example write script
```go
func main() {
bucket := "example-bucket"
org := "example-org"
token := "example-token"
// Store the URL of your InfluxDB instance
url := "http://localhost:8086"
// Create new client with default option for server url authenticate by token
client := influxdb2.NewClient(url, token)
// User blocking write client for writes to desired bucket
writeAPI := client.WriteAPIBlocking(org, bucket)
// Create point using full params constructor
p := influxdb2.NewPoint("stat",
map[string]string{"unit": "temperature"},
map[string]interface{}{"avg": 24.5, "max": 45},
time.Now())
// Write point immediately
writeAPI.WritePoint(context.Background(), p)
// Ensures background processes finishes
client.Close()
}
```
## Query data from InfluxDB with Go
Use the Go library to query data to InfluxDB.
1. Create a Flux query and supply your `bucket` parameter.
```js
from(bucket:"<bucket>")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "stat")
```
The query client sends the Flux query to InfluxDB and returns the results as a FluxRecord object with a table structure.
**The query client includes the following methods:**
- `Query`: Sends the Flux query to InfluxDB.
- `Next`: Iterates over the query response.
- `TableChanged`: Identifies when the group key changes.
- `Record`: Returns the last parsed FluxRecord and gives access to value and row properties.
- `Value`: Returns the actual field value.
```go
result, err := queryAPI.Query(context.Background(), `from(bucket:"<bucket>")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "stat")`)
if err == nil {
for result.Next() {
if result.TableChanged() {
fmt.Printf("table: %s\n", result.TableMetadata().String())
}
fmt.Printf("value: %v\n", result.Record().Value())
}
if result.Err() != nil {
fmt.Printf("query parsing error: %s\n", result.Err().Error())
}
} else {
panic(err)
}
```
**The FluxRecord object includes the following methods for accessing your data:**
- `Table()`: Returns the index of the table the record belongs to.
- `Start()`: Returns the inclusive lower time bound of all records in the current table.
- `Stop()`: Returns the exclusive upper time bound of all records in the current table.
- `Time()`: Returns the time of the record.
- `Value() `: Returns the actual field value.
- `Field()`: Returns the field name.
- `Measurement()`: Returns the measurement name of the record.
- `Values()`: Returns a map of column values.
- `ValueByKey(<your_tags>)`: Returns a value from the record for given column key.
### Complete example query script
```go
func main() {
// Create client
client := influxdb2.NewClient(url, token)
// Get query client
queryAPI := client.QueryAPI(org)
// Get QueryTableResult
result, err := queryAPI.Query(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`)
if err == nil {
// Iterate over query response
for result.Next() {
// Notice when group key has changed
if result.TableChanged() {
fmt.Printf("table: %s\n", result.TableMetadata().String())
}
// Access data
fmt.Printf("value: %v\n", result.Record().Value())
}
// Check for an error
if result.Err() != nil {
fmt.Printf("query parsing error: %s\n", result.Err().Error())
}
} else {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
```
For more information, see the [Go client README on GitHub](https://github.com/influxdata/influxdb-client-go).

View File

@ -0,0 +1,12 @@
---
title: InfluxDB Java client library
list_title: Java
description: Use the Java client library to interact with InfluxDB.
external_url: https://github.com/influxdata/influxdb-client-java
menu:
influxdb_2_0:
name: Java
parent: Use client libraries
url: https://github.com/influxdata/influxdb-client-java
weight: 201
---

View File

@ -0,0 +1,180 @@
---
title: JavaScript client library
seotitle: InfluxDB JavaScript client library
list_title: JavaScript
description: >
Use the JavaScript client library to interact with InfluxDB.
menu:
influxdb_2_0:
name: JavaScript
parent: Use client libraries
influxdb/v2.0/tags: [client libraries, JavaScript]
weight: 201
aliases:
- /influxdb/v2.0/reference/api/client-libraries/js/
---
Use the [InfluxDB JavaScript client library](https://github.com/influxdata/influxdb-client-js) to integrate InfluxDB into JavaScript scripts and applications. This client supports both client-side (browser) and server-side (NodeJS) environments.
This guide presumes some familiarity with JavaScript, browser environments, and InfluxDB.
If just getting started, see [Get started with InfluxDB](/influxdb/v2.0/get-started/).
## Before you begin
1. Install [NodeJS](https://nodejs.org/en/download/package-manager/).
2. Ensure that InfluxDB is running and you can connect to it.
For information about what URL to use to connect to InfluxDB OSS or InfluxDB Cloud, see [InfluxDB URLs](/influxdb/v2.0/reference/urls/).
## Easiest way to get started
1. Clone the [examples directory](https://github.com/influxdata/influxdb-client-js/tree/master/examples) in the [influxdb-client-js](https://github.com/influxdata/influxdb-client-js) repo.
2. Navigate to the `examples` directory:
```js
cd examples
```
3. Install `yarn` or `npm` dependencies as needed:
```js
yarn install
npm install
```
3. Update your `./env` and `index.html` with the name of your InfluxDB [bucket](/influxdb/v2.0/organizations/buckets/), [organization](/influxdb/v2.0/organizations/), [token](/influxdb/v2.0/security/tokens/), and `proxy` which relies upon proxy to forward requests to the target InfluxDB.
4. Run the following command to run the application at [http://localhost:3001/examples/index.html]()
```sh
npm run browser
```
## Boilerplate for the InfluxDB Javascript client library
Use the Javascript library to write data to and query data from InfluxDB in a browser.
1. To write a data point to InfluxDB using the JavaScript library, import the latest InfluxDB Javascript library in your script.
```js
import {InfluxDB, Point} from 'https://unpkg.com/@influxdata/influxdb-client/dist/index.browser.mjs'
```
2. Define constants for your InfluxDB [bucket](/influxdb/v2.0/organizations/buckets/), [organization](/influxdb/v2.0/organizations/), [token](/influxdb/v2.0/security/tokens/), and `proxy` which relies on a proxy to forward requests to the target InfluxDB instance.
```js
const proxy = '/influx'
const token = 'example-token'
const org = 'example-org'
const bucket = 'example-bucket'
```
3. Instantiate the InfluxDB JavaScript client and pass in the `proxy` and `token` parameters.
```js
const influxDB = new InfluxDB({proxy, token})
```
## Write data to InfluxDB with JavaScript
Use the Javascript library to write data to InfluxDB in a Node.js environment.
1. Instantiate an `InfluxDB` client. Provide your InfluxDB `url` and `token`.
2. Use the `getWriteApi` method of the instantiated InfluxDB client to create a **write client**. Provide your InfluxDB `org` and `bucket`.
```js
import {InfluxDB, Point} from '@influxdata/influxdb-client'
const influxDB = new InfluxDB({url, token})
const writeApi = influxDB.getWriteApi(org, bucket)
```
The `useDefaultTags` method instructs the write api to use default tags when writing points. Create a [point](/influxdb/v2.0/reference/glossary/#point) and write it to InfluxDB using the `writePoint` method. The `tag` and `floatField` methods add key value pairs for the tags and fields, respectively. Close the client to flush all pending writes and finish.
```js
writeApi.useDefaultTags({location: 'browser'})
const point1 = new Point('temperature')
.tag('example', 'index.html')
.floatField('value', 24)
console.log(`${point1}`)
writeApi.writePoint(point1)
writeApi.close()
```
### Complete example write script
```js
const influxDB = new InfluxDB({proxy, token})
const writeApi = influxDB.getWriteApi(org, bucket)
// setup default tags for all writes through this API
writeApi.useDefaultTags({location: 'browser'})
const point1 = new Point('temperature')
.tag('example', 'index.html')
.floatField('value', 24)
console.log(` ${point1}`)
writeApi.writePoint(point1)
// flush pending writes and close writeApi
writeApi
.close()
.then(() => {
console.log('WRITE FINISHED')
})
```
## Query data from InfluxDB with JavaScript
Use the Javascript library to query data from InfluxDB.
1. Use the `getQueryApi` method of the `InfluxDB` client to create a new **query client**. Provide your InfluxDB `org`.
```js
const queryApi = influxDB.getQueryApi(org)
```
2. Create a Flux query (including your `bucket` parameter).
```js
const fluxQuery =
'from(bucket:"<my-bucket>")
|> range(start: 0)
|> filter(fn: (r) => r._measurement == "temperature")'
```
The **query client** sends the Flux query to InfluxDB and returns line table metadata and rows.
3. Use the `next` method to iterate over the rows.
```js
queryApi.queryRows(fluxQuery, {
next(row: string[], tableMeta: FluxTableMetaData) {
const o = tableMeta.toObject(row)
// console.log(JSON.stringify(o, null, 2))
console.log(
`${o._time} ${o._measurement} in '${o.location}' (${o.example}): ${o._field}=${o._value}`
)
}
}
```
### Complete example query script
```js
// performs query and receive line table metadata and rows
// https://v2.docs.influxdata.com/v2.0/reference/syntax/annotated-csv/
queryApi.queryRows(fluxQuery, {
next(row: string[], tableMeta: FluxTableMetaData) {
const o = tableMeta.toObject(row)
// console.log(JSON.stringify(o, null, 2))
console.log(
'${o._time} ${o._measurement} in '${o.location}' (${o.example}): ${o._field}=${o._value}`
)
},
error(error: Error) {
console.error(error)
console.log('\nFinished ERROR')
},
complete() {
console.log('\nFinished SUCCESS')
},
})
```
For more information, see the [JavaScript client README on GitHub](https://github.com/influxdata/influxdb-client-js).

View File

@ -0,0 +1,12 @@
---
title: InfluxDB Kotlin client library
list_title: Kotlin
description: Use the Kotlin client library to interact with InfluxDB.
external_url: https://github.com/influxdata/influxdb-client-java/tree/master/client-kotlin
menu:
influxdb_2_0:
name: Kotlin
parent: Use client libraries
url: https://github.com/influxdata/influxdb-client-java/tree/master/client-kotlin
weight: 201
---

View File

@ -0,0 +1,12 @@
---
title: InfluxDB PHP client library
list_title: PHP
description: Use the PHP client library to interact with InfluxDB.
external_url: https://github.com/influxdata/influxdb-client-php
menu:
influxdb_2_0:
name: PHP
parent: Use client libraries
url: https://github.com/influxdata/influxdb-client-php
weight: 201
---

View File

@ -0,0 +1,174 @@
---
title: Python client library
list_title: Python
description: >
Use the Python client library to interact with InfluxDB.
menu:
influxdb_2_0:
name: Python
parent: Use client libraries
influxdb/v2.0/tags: [client libraries, python]
aliases:
- /influxdb/v2.0/reference/api/client-libraries/python/
- /influxdb/v2.0/reference/api/client-libraries/python-cl-guide/
weight: 201
---
Use the [InfluxDB Python client library](https://github.com/influxdata/influxdb-client-python) to integrate InfluxDB into Python scripts and applications.
This guide presumes some familiarity with Python and InfluxDB.
If just getting started, see [Get started with InfluxDB](/influxdb/v2.0/get-started/).
## Before you begin
1. Install the InfluxDB Python library:
```sh
pip install influxdb-client
```
2. Ensure that InfluxDB is running.
If running InfluxDB locally, visit http://localhost:8086.
(If using InfluxDB Cloud, visit the URL of your InfluxDB Cloud UI.
For example: https://us-west-2-1.aws.cloud2.influxdata.com.)
## Write data to InfluxDB with Python
We are going to write some data in [line protocol](/influxdb/v2.0/reference/syntax/line-protocol/) using the Python library.
1. In your Python program, import the InfluxDB client library and use it to write data to InfluxDB.
```python
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
```
2. Define a few variables with the name of your [bucket](/influxdb/v2.0/organizations/buckets/), [organization](/influxdb/v2.0/organizations/), and [token](/influxdb/v2.0/security/tokens/).
```python
bucket = "<my-bucket>"
org = "<my-org>"
token = "<my-token>"
# Store the URL of your InfluxDB instance
url="http://localhost:8086"
```
3. Instantiate the client. The `InfluxDBClient` object takes three named parameters: `url`, `org`, and `token`. Pass in the named parameters.
```python
client = influxdb_client.InfluxDBClient(
url=url,
token=token,
org=org
)
```
The `InfluxDBClient` object has a `write_api` method used for configuration.
4. Instantiate a **write client** using the `client` object and the `write_api` method. Use the `write_api` method to configure the writer object.
```python
write_api = client.write_api(write_options=SYNCHRONOUS)
```
5. Create a [point](/influxdb/v2.0/reference/glossary/#point) object and write it to InfluxDB using the `write` method of the API writer object. The write method requires three parameters: `bucket`, `org`, and `record`.
```python
p = influxdb_client.Point("my_measurement").tag("location", "Prague").field("temperature", 25.3)
write_api.write(bucket=bucket, org=org, record=p)
```
### Complete example write script
```python
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
bucket = "<my-bucket>"
org = "<my-org>"
token = "<my-token>"
# Store the URL of your InfluxDB instance
url="http://localhost:8086"
client = influxdb_client.InfluxDBClient(
url=url,
token=token,
org=org
)
write_api = client.write_api(write_options=SYNCHRONOUS)
p = influxdb_client.Point("my_measurement").tag("location", "Prague").field("temperature", 25.3)
write_api.write(bucket=bucket, org=org, record=p)
```
## Query data from InfluxDB with Python
1. Instantiate the **query client**.
```python
query_api = client.query_api()
```
2. Create a Flux query.
```python
query = from(bucket:"my-bucket")\
|> range(start: -10m)\
|> filter(fn:(r) => r._measurement == "my_measurement")\
|> filter(fn: (r) => r.location == "Prague")\
|> filter(fn:(r) => r._field == "temperature" )
```
The query client sends the Flux query to InfluxDB and returns a Flux object with a table structure.
3. Pass the `query()` method two named parameters:`org` and `query`.
```python
result = client.query_api().query(org=org, query=query)
```
4. Iterate through the tables and records in the Flux object.
- Use the `get_value()` method to return values.
- Use the `get_field()` method to return fields.
```python
results = []
for table in result:
for record in table.records:
results.append((record.get_field(), record.get_value()))
print(results)
[(temperature, 25.3)]
```
**The Flux object provides the following methods for accessing your data:**
- `get_measurement()`: Returns the measurement name of the record.
- `get_field()`: Returns the field name.
- `get_value()`: Returns the actual field value.
- `values()`: Returns a map of column values.
- `values.get("<your tag>")`: Returns a value from the record for given column.
- `get_time()`: Returns the time of the record.
- `get_start()`: Returns the inclusive lower time bound of all records in the current table.
- `get_stop()`: Returns the exclusive upper time bound of all records in the current table.
### Complete example query script
```python
query_api = client.query_api()
query = from(bucket:"my-bucket")\
|> range(start: -10m)\
|> filter(fn:(r) => r._measurement == "my_measurement")\
|> filter(fn: (r) => r.location == "Prague")\
|> filter(fn:(r) => r._field == "temperature" )
result = client.query_api().query(org=org, query=query)
results = []
for table in result:
for record in table.records:
results.append((record.get_field(), record.get_value()))
print(results)
[(temperature, 25.3)]
```
For more information, see the [Python client README on GitHub](https://github.com/influxdata/influxdb-client-python).

View File

@ -0,0 +1,12 @@
---
title: InfluxDB Ruby client library
list_title: Ruby
description: Use the Ruby client library to interact with InfluxDB.
external_url: https://github.com/influxdata/influxdb-client-ruby
menu:
influxdb_2_0:
name: Ruby
parent: Use client libraries
url: https://github.com/influxdata/influxdb-client-ruby
weight: 201
---

View File

@ -0,0 +1,12 @@
---
title: InfluxDB Scala client library
list_title: Scala
description: Use the Scala client library to interact with InfluxDB.
external_url: https://github.com/influxdata/influxdb-client-java/tree/master/client-scala
menu:
influxdb_2_0:
name: Scala
parent: Use client libraries
url: https://github.com/influxdata/influxdb-client-java/tree/master/client-scala
weight: 201
---

View File

@ -0,0 +1,12 @@
---
title: InfluxDB Swift client library
list_title: Swift
description: Use the Swift client library to interact with InfluxDB.
external_url: https://github.com/influxdata/influxdb-client-swift
menu:
influxdb_2_0:
name: Swift
parent: Use client libraries
url: https://github.com/influxdata/influxdb-client-swift
weight: 201
---