API Analytics: A Lightweight, Zero-Config API Monitoring Solution for Any Language

•1065 words•6 min read•
open-sourceAPImonitoringanalyticsDevOpssoftware
API Analytics dashboard

API Analytics

A simple, easy-to-use API analytics solution for monitoring requests, responses, errors, and other metrics in your project, with a visual dashboard on top.

Currently compatible with the following frameworks:

  • Python: FastAPI, Flask, Django, and Tornado
  • Node.js: Express, Fastify, Koa, and Hono
  • Go: Gin, Echo, Fiber, and Chi
  • Rust: Actix, Axum, and Rocket
  • Ruby: Rails and Sinatra
  • C#: ASP.NET Core

Project: API Analytics

Quick Start

1. Generate an API Key

Data collection, analysis, and the dashboard are all hosted on the author's server. You can also self-host if you prefer (see below).

If you cannot be bothered to deploy it yourself, or just want a quick look, visit apianalytics.dev/generate to generate a dedicated API key with one click. You will need it to access the API Analytics dashboard and log data later.

2. Add Middleware to Your API

Add lightweight middleware to your project's API. Since most of the data processing happens on the API Analytics server, the impact on your API's performance is minimal.

FastAPI

pip install api-analytics[fastapi]
import uvicorn
from fastapi import FastAPI
from api_analytics.fastapi import Analytics

app = FastAPI()
app.add_middleware(Analytics, api_key=<API-KEY>)  # Add middleware

@app.get('/')
async def root():
    return {'message': 'Hello, World!'}

if __name__ == "__main__":
    uvicorn.run("app:app", reload=True)

Hono

npm install node-api-analytics
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { honoAnalytics } from 'node-api-analytics';

const app = new Hono();

app.use('*', honoAnalytics(<API-KEY>));

app.get('/', (c) => c.text('Hello, world!'));

serve(app, (info) => {
    console.log(`Server listening at http://localhost:${info.port}`);
});

Gin

go get -u github.com/tom-draper/api-analytics/analytics/go/gin
package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
    analytics "github.com/tom-draper/api-analytics/analytics/go/gin"
)

func root(c * gin.Context) {
    data := map[string]string{
        "message": "Hello, World!",
    }
    c.JSON(http.StatusOK, data)
}

func main() {
    r := gin.Default()

    r.Use(analytics.Analytics(<API-KEY>)) // Add middleware

    r.GET("/", root)
    r.Run(":8080")
}

For other frameworks, see the official documentation.

3. View Your Analytics

Your API will now log and store incoming request data for every route. There are two ways to view the recorded data:

  1. Through visual charts and statistics on the dashboard
  2. Directly through the data API

The same API key can be used for multiple APIs, but all requests will show up in the same dashboard. Generating a new API key for each API server is recommended.

Dashboard

Visit apianalytics.dev/dashboard and paste your API key to access the dashboard.

Demo: apianalytics.dev/dashboard/demo

Dashboard

Data API

You can fetch raw recorded request data from the data API. Just send a GET request to https://apianalytics-server.com/api/data with your API key set in the X-AUTH-TOKEN: <API-KEY> request header.

Python

import requests

response = requests.get("https://apianalytics-server.com/api/data", headers={
    "X-AUTH-TOKEN": <API-KEY>
})
print(response.json())

Node.js

fetch("https://apianalytics-server.com/api/data", {
    headers: { "X-AUTH-TOKEN": <API-KEY> },
})
    .then((response) => {
        return response.json();
    })
    .then((data) => {
        console.log(data);
    });

cURL

curl --header "X-AUTH-TOKEN: <API-KEY>" https://apianalytics-server.com/api/data

Parameters

You can filter the data by providing URL parameters in your request.

  • page - page number, with a maximum page size of 50,000 (default is 1)
  • date - the date the request occurred (YYYY-MM-DD)
  • dateFrom - lower bound of the date range (YYYY-MM-DD)
  • dateTo - upper bound of the date range (YYYY-MM-DD)
  • hostname - hostname of your service
  • ipAddress - IP address of the client
  • status - status code of the response
  • location - two-character location code of the client
  • user_id - custom user identifier (only relevant if a get_user_id mapping function is set in the config)

Example:

curl --header "X-AUTH-TOKEN: <API-KEY>" https://apianalytics-server.com/api/data?page=3&dateFrom=2022-01-01&hostname=apianalytics.dev&status=200&user_id=b56cbd92-1168-4d7b-8d94-0418da207908

Client ID and Privacy

By default, API Analytics logs and stores the client IP address of every incoming request to your API, and infers a location (country) from each IP where possible. In the dashboard, IP addresses serve as a form of client identification to estimate the number of users accessing your API.

This behavior is controlled by the privacy level defined in the API middleware config. There are three privacy levels, from 0 to 2. Privacy level 1 disables IP address storage, and level 2 also disables location inference. The default is 0.

Privacy levels:

  • 0 - The client IP address is used to infer location, then stored for user identification.
  • 1 - The client IP address is used to infer location, then discarded.
  • 2 - The client IP address is never accessed, and location is never inferred.
from fastapi import FastAPI
from api_analytics.fastapi import Analytics, Config

config = Config(privacy_level=2)  # Disable IP storing and location inference

app = FastAPI()
app.add_middleware(Analytics, api_key=<API-KEY>, config=config)  # Add middleware

Regardless of the privacy level, you can optionally define a user ID as a function of the request by providing a mapping function in the API middleware config. For example, your service may store an API key in the X-AUTH-TOKEN header to identify your users. In the dashboard, this custom user ID will identify users alongside the IP address, or as an alternative, depending on the privacy level you set.

from fastapi import FastAPI
from api_analytics.fastapi import Analytics, Config

config = Config(
    get_user_id=lambda request: request.headers.get('X-AUTH-TOKEN', '')
)

app = FastAPI()
app.add_middleware(Analytics, api_key=<API-KEY>, config=config)  # Add middleware

Data Deletion

You can delete all stored data associated with an API key at any time by visiting apianalytics.dev/delete and entering the key.

If an API key is inactive for 6 months, or logs no requests for 3 months, the key and its associated recorded request data are automatically deleted.

Active Monitoring

Visit apianalytics.dev/monitoring and enter your API key to set up active endpoint monitoring. The server will periodically ping the selected endpoints to monitor uptime and response time.

Monitoring

Limits

To keep the service free, each API key can store at most 1 million requests. Beyond that, older requests are rolled over and replaced by newer ones in chronological order. If your project handles a particularly high volume of requests, you may want to try another solution or look into self-hosting.

Self-Hosting

As mentioned above, if you have privacy or security concerns, you can self-host the project by following the guide.

Note that self-hosting is still being tested, developed, and improved. It may not be fully stable yet, and avoiding it in production is recommended for now.

Share: