Get Started with InfluxDB's JavaScript API

Navigate to:

Time series databases are designed to store and analyze data collected at specified points in time. They’re essential for applications that handle huge amounts of continuously generated data, such as Internet of Things (IoT) devices, system monitors, and financial systems.

InfluxDB, an open source time series database known for its outstanding performance and scalability, has gained popularity due to its capacity to manage large amounts of time-stamped data. The InfluxDB API provides a programmatic interface for interacting with the database, allowing developers to do a variety of tasks, such as create databases and write and query data.

This article will provide a complete understanding of the InfluxDB API, guiding you through the process of setting up InfluxDB and using a client library to interact with it effectively. By the end of this article, you should have a strong grasp of how to use the InfluxDB API for time series data management.

Prerequisites

To follow along with this tutorial, you must have the following requirements: 

Basic Knowledge

  1. Basic knowledge of both JavaScript and Node.js, as this tutorial uses Node.js to write server-side code.
  2. Basic knowledge of Express, including how to set up a server, make requests, and manage routes.
  3. A basic knowledge of time series data, its characteristics, and common use cases so you can understand the data in context.

Software Requirements

  1. Node.js installed. You can verify the installation by running node -v and npm -v in your terminal. Otherwise, download it from nodejs.org.
  2. Install Express using npm by running npm install express in your terminal. Express is a flexible Node.js framework.
  3. Postman for testing API requests.

A pink and blue text
Description automatically generated

An overview of InfluxDB API

The InfluxDB API provides a programmatic way to interact with the InfluxDB database. It’s a set of rules and protocols that enable applications to communicate with InfluxDB and perform various tasks.

The InfluxDB API offers the following essential functionalities:

  • Writing data: sending time-stamped data to a database.
  • Reading data: retrieving data based on specified queries and time ranges.
  • Managing databases: creating, removing, and updating databases.
  • Managing users and organizations: controlling database access.
  • Performing administrative tasks: managing retention policies, continuous queries, and various database configurations.

The API typically uses HTTP requests to interact with InfluxDB with responses formatted in JSON, making it compatible with a range of programming languages and platforms. InfluxDB 3.0 offers advanced capabilities, including robust APIs and client libraries, making it easy to integrate and manage time series data efficiently.

Setting up InfluxDB 3.0

To begin using InfluxDB 3.0, you must install, configure, and start the service. This section will guide you through the steps to ensure your InfluxDB setup is running smoothly.

  1. Visit the InfluxDB Cloud website to set up an account. If you already have an account, log in using your existing credentials.

Signup 2. Once you’re logged in, create an organization if you don’t already have one.

Organization 3. After that, you’ll be taken to the Resource Center.

4. Create a bucket where your time series data will be stored. A bucket in InfluxDB is similar to a database in traditional RDBMS systems. To do this, first click “Manage Database & Security” on the dashboard.

5. Then, click the “Go to Buckets” button in the dropdown menu. This will take you to the buckets menu. Once there, click the “Create Bucket” button on the right side of your screen.

6. In the dialog box, provide a suitable name for your bucket and click “Create.” 7. Next, a new API token will be generated. This token will be used to authenticate API requests. Store this token securely, as it provides access to your InfluxDB instance. To do this, navigate back to the “Manage Database & Security” on the “Resource Center” dashboard and click “Go to Tokens” to access the token menu. 8. In the Token menu, click “Generate API Token.”

Make sure you save your API token because you’ll need it in the next section.

Hands-On Tutorial Using the InfluxDB 3.0 Node.js Client Library

This hands-on tutorial will teach you how to use the InfluxDB 3.0 Node.js client library. This involves configuring your development environment, writing data to InfluxDB, and querying data from it. By the end of this section, you’ll have a solid understanding of how to integrate InfluxDB into Node.js applications.

  1. Initialize a new Node.js project by running these commands in the terminal:
    mkdir influx-app-node
    cd influx-node-app
    npm init -y
  2. Install TypeScript and type definitions for Node.js.
    npm install -g typescript
    npm install --save-dev @types/node
  3. Initialize a TypeScript configuration.
    npx tsc --init
  4. Install the JavaScript client library for querying and writing data.
    npm install --save @influxdata/influxdb3-client dotenv
  5. Create an .env file in the root folder of your project and add the following variables:
    INFLUX_HOST=https://us-east-1-1.aws.cloud2.influxdata.com
    INFLUX_TOKEN="add your API token here"
    INFLUX_BUCKET="add your bucket name here"
    INFLUX_ORG="add your organization name here"
  6. Create an app.ts file and import dotenv and the InfluxDB client by using the following lines of code:
    import * as dotenv from "dotenv";
    import { InfluxDBClient, Point} from '@influxdata/influxdb3-client'
  7. Configure the dotenv package.
    dotenv.config();
  8. Read all the env variables.
    const host = process.env.INFLUX_HOST as string;
    const token = process.env.INFLUX_TOKEN as string;
    const database = process.env.INFLUX_BUCKET as string;
    const organization = process.env.INFLUX_ORG as string;
  9. Initialize the InfluxDB client and pass the required host, token, and database.
    const client = new InfluxDBClient({host, token, database})
  10. Write to the database.
    const line = `stat,unit=temperature avg=20.5,max=45.0`
    await client.write(line, database, organization)
  11. Query the database and console the query result.
    const query = `
    SELECT *
    FROM "stat"
    WHERE
    time >= now() - interval '5 minute'
    AND
    "unit" IN ('temperature')
    `
    const queryResult = await client.query(query, database)
    
    for await (const row of queryResult) {
      console.log(`avg is ${row.avg}`)
      console.log(`max is ${row.max}`)
    }
  12. Close the client and all its resources.
    client.close()

Here is the complete code:

import * as dotenv from "dotenv";
import { InfluxDBClient, Point} from '@influxdata/influxdb3-client'
dotenv.config();

const host = process.env.INFLUX_HOST as string;
const token = process.env.INFLUX_TOKEN as string;
const database = process.env.INFLUX_BUCKET as string;
const organization = process.env.INFLUX_ORG as string;

async function main() {
  const client = new InfluxDBClient(
      {host, token, database})

  //writing data
  const line = `stat,unit=temperature avg=20.5,max=45.0`
  await client.write(line, database, organization)

 // Execute query
  const query = `
  SELECT *
  FROM "stat"
  WHERE
  time >= now() - interval '5 minute'
  AND
  "unit" IN ('temperature')
  `
  const queryResult = await client.query(query, database)

  for await (const row of queryResult) {
  console.log(`avg is ${row.avg}`)
  console.log(`max is ${row.max}`)
  }

  client.close()
}

main()

How to run the project

  1. Add a start script to your package.json file.
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
    },
  2. Run the following commands:
    npx tsc 
    npm start

After running these commands, you should see the query result.

avg is 20.5
max is 45

A close-up of a sign Description automatically generated

Best practices for using InfluxDB API

Adhering to best practices will help you optimize the performance and efficiency of your InfluxDB implementation.

Data Modeling

Effective data modeling is necessary for optimal InfluxDB performance. Understanding the nuances of measurements, tags, and fields is important. To achieve efficient data retrieval, consider query patterns when designing your data model. In addition, establish suitable retention policies to control the data life cycle and storage.

Writing Data

Optimizing data ingestion is essential for maximizing InfluxDB’s potential. Sending several data points in a single request (batch writes) greatly increases efficiency. Consider compression to reduce network traffic and storage needs. Robust error-handling methods should be prioritized to avoid data loss during the writing process.

Reading Data

Efficient data retrieval is critical for extracting value from your time series data. Use InfluxQL to create effective queries. Creating appropriate indexes can significantly improve query performance and caching methods can minimize database load and improve response times.

API Usage

The InfluxDB API prioritizes security and performance. Use strong authentication and permission techniques to protect your database. Implementing rate-limiting prevents API misuse. Appropriate error management helps in developing resilient applications.

Conclusion

InfluxDB is a powerful tool for handling time-series data, and its API allows for customizable database interaction. Understanding the fundamentals of data modeling, writing efficient queries, and adhering to best practices will allow you to utilize InfluxDB fully.

Remember, effective data management is essential for extracting valuable insights from your time series data. With careful planning and optimization, you can create strong and scalable applications that take advantage of InfluxDB’s capabilities.

This post was written by Vincent Chosen. Vincent is a web developer and technical writer. He has proficient knowledge in JavaScript, ReactJS, NextJS, React Native, Nodejs and Database. Aside from coding, Vincent loves playing chess and discussing tech related topics with other developers.