### Install and Use Gin Analytics Middleware (Go) Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Provides instructions to fetch the Gin analytics package using go get and integrate the Analytics middleware into a Gin web server. This middleware facilitates API analytics. An API key must be provided during setup. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/gin ``` ```go 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()) // Add middleware r.GET("/", root) r.Run(":8080") } ``` -------------------------------- ### Install and Use Chi Analytics Middleware (Go) Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Details the process of fetching the Chi analytics package using go get and applying the Analytics middleware to a Chi router. This setup is for tracking API usage. An API key is needed for the middleware to function. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/chi ``` ```go package main import ( "net/http" analytics "github.com/tom-draper/api-analytics/analytics/go/chi" chi "github.com/go-chi/chi/v5" ) func root(w http.ResponseWriter, r *http.Request) { data := map[string]string{ "message": "Hello, World!", } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) err := json.NewEncoder(w).Encode(data) if err != nil { http.Error(w, "Failed to encode JSON", http.StatusInternalServerError) return } } func main() { r := chi.NewRouter() r.Use(analytics.Analytics()) // Add middleware r.GET("/", root) r.Run(":8080") } ``` -------------------------------- ### Start Svelte Development Server Source: https://github.com/tom-draper/api-analytics/blob/main/dashboard/README.md Explains how to start the development server for a Svelte project after installing dependencies. It includes options to open the app automatically in a new browser tab. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Install Echo Analytics Go Middleware Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/echo/README.md Command to install the Echo Analytics middleware for Go applications using go get. This makes the analytics package available for import. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/echo ``` -------------------------------- ### Install and Use Echo Analytics Middleware (Go) Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Details how to obtain the Echo analytics package using go get and incorporate the Analytics middleware into an Echo web application. This setup is for API request monitoring. An API key is required for the middleware. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/echo ``` ```go package main import ( "net/http" echo "github.com/labstack/echo/v4" analytics "github.com/tom-draper/api-analytics/analytics/go/echo" ) func root(c echo.Context) error { data := map[string]string{ "message": "Hello, World!", } return c.JSON(http.StatusOK, data) } func main() { e := echo.New() e.Use(analytics.Analytics()) // Add middleware e.GET("/", root) e.Start(":8080") } ``` -------------------------------- ### Start Development Server (Go) Source: https://github.com/tom-draper/api-analytics/blob/main/server/api/README.md Starts the Go backend service for development using 'go run main.go'. This command is used to run the application locally during the development phase. ```bash go run main.go ``` -------------------------------- ### Install api-analytics for Flask Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/python/README.md Installs the api-analytics package with Flask support. This prepares the environment for adding the analytics middleware to Flask applications. ```bash pip install api-analytics[flask] ``` -------------------------------- ### Install Fiber Analytics Go Middleware Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/fiber/README.md Installs the Fiber Analytics Go middleware package using go get. This is the first step to integrating analytics into your Go Fiber API. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/fiber ``` -------------------------------- ### Install and Use Fiber Analytics Middleware (Go) Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Explains how to get the Fiber analytics package via go get and add the Analytics middleware to a Fiber web server. This integration enables API analytics. The middleware requires an API key for its operation. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/fiber ``` ```go package main import ( "github.com/gofiber/fiber/v2" analytics "github.com/tom-draper/api-analytics/analytics/go/fiber" ) func root(c *fiber.Ctx) error { data := map[string]string{ "message": "Hello, World!", } return c.JSON(data) } func main() { app := fiber.New() app.Use(analytics.Analytics()) // Add middleware app.Get("/", root) app.Listen(":8080") } ``` -------------------------------- ### Install api-analytics for Tornado Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/python/README.md Installs the api-analytics package with Tornado support. This allows Tornado handlers to inherit from the Analytics class for integrated request tracking. ```bash pip install api-analytics[tornado] ``` -------------------------------- ### Install Tornado Analytics Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/tornado/README.md Installs the api-analytics package for Tornado applications using pip. This is the first step to integrate the analytics middleware into your project. ```bash pip install tornado-analytics ``` -------------------------------- ### Install and Use Hono Analytics Middleware (JavaScript) Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Shows how to install the node-api-analytics package using npm and apply the honoAnalytics middleware within a Hono application. This setup enables API request tracking. An API key is necessary for initialization. ```bash npm install node-api-analytics ``` ```javascript import { Hono } from 'hono'; import { serve } from '@hono/node-server'; import { honoAnalytics } from 'node-api-analytics'; const app = new Hono(); app.use('*', honoAnalytics()); app.get('/', (c) => c.text('Hello, world!')); serve(app, (info) => { console.log(`Server listening at http://localhost:${info.port}`); }); ``` -------------------------------- ### Install FastAPI Analytics Package Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/fastapi/README.md Installs the necessary `fastapi-analytics` library using pip. This is the first step to integrate analytics into your FastAPI project. ```Bash pip install fastapi-analytics ``` -------------------------------- ### Install api-analytics for FastAPI Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/python/README.md Installs the api-analytics package with FastAPI support. This enables the middleware to be added to FastAPI applications for request logging. ```bash pip install api-analytics[fastapi] ``` -------------------------------- ### Install Gin Analytics Middleware Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/gin/README.md Installs the Gin Analytics middleware for Go. This package adds lightweight analytics to your Gin API, with most processing handled server-side to minimize performance impact. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/gin ``` -------------------------------- ### Start All API Analytics Services Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Starts all necessary Docker services for API Analytics in detached mode. This brings the entire application online after configuration. ```bash docker compose up -d ``` -------------------------------- ### Navigate to Self-Hosting Directory Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Changes the current directory to the self-hosting server directory within the cloned repository. This is where configuration and setup commands will be executed. ```bash cd api-analytics/server/self-hosting ``` -------------------------------- ### Install api-analytics Gem Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/ruby/api_analytics/README.md Installs the Ruby gem required to add API analytics middleware to your application. This is the first step for Ruby-based projects. ```bash gem install api_analytics ``` -------------------------------- ### Install Node.js Middleware Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/nodejs/README.md Installs the node-api-analytics package using npm. This package provides middleware for integrating API analytics into Node.js applications. ```bash npm install node-api-analytics ``` -------------------------------- ### Add Chi Analytics Middleware to Go API Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/chi/README.md Integrates Chi Analytics middleware into a Go Chi router to automatically log API requests. Requires the 'go get' command to install the library and an API key for authentication. ```bash go get -u github.com/tom-draper/api-analytics/analytics/go/chi ``` ```go package main import ( "encoding/json" "net/http" analytics "github.com/tom-draper/api-analytics/analytics/go/chi" chi "github.com/go-chi/chi/v5" ) func root(w http.ResponseWriter, r *http.Request) { data := map[string]string{ "message": "Hello, World!", } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) err := json.NewEncoder(w).Encode(data) if err != nil { http.Error(w, "Failed to encode JSON", http.StatusInternalServerError) return } } func main() { r := chi.NewRouter() r.Use(analytics.Analytics()) // Add middleware r.GET("/", root) r.Run(":8080") } ``` -------------------------------- ### Start Certbot and Nginx Services Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Starts the Certbot and Nginx Docker services in detached mode. Certbot is used for obtaining SSL certificates, and Nginx serves as the web server. ```bash docker compose up certbot nginx -d ``` -------------------------------- ### Install and Use Koa Analytics Middleware (JavaScript) Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Demonstrates how to install the node-api-analytics package via npm and integrate the koaAnalytics middleware into a Koa application. This middleware helps track API requests. An API key is required for configuration. ```bash npm install node-api-analytics ``` ```javascript import Koa from "koa"; import { koaAnalytics } from 'node-api-analytics'; const app = new Koa(); app.use(koaAnalytics()); // Add middleware app.use((ctx) => { ctx.body = { message: 'Hello, World!' }; }); app.listen(8080, () => console.log('Server listening at http://localhost:8080'); ); ``` -------------------------------- ### Install APIAnalytics.AspNetCore NuGet Package Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/csharp/analytics/README.md Command to add the APIAnalytics.AspNetCore package to an ASP.NET Core project using the .NET CLI. ```sh dotnet add package APIAnalytics.AspNetCore ``` -------------------------------- ### API Analytics Monitoring Setup Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/echo/README.md Describes the process for setting up active API monitoring. Users can enter their API key at apianalytics.dev/monitoring to configure regular checks of chosen endpoints for uptime and response time. ```APIDOC Monitoring Setup: - Visit apianalytics.dev/monitoring. - Enter your API key. - Configure endpoints for regular uptime and response time checks. ``` -------------------------------- ### Run Backend Service (Development) Source: https://github.com/tom-draper/api-analytics/blob/main/server/logger/README.md Starts the backend service in development mode using the Go run command. This is typically used during the development phase to test functionality. ```bash go run main.go ``` -------------------------------- ### Install Actix Analytics Middleware Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/rust/actix/analytics/README.md Installs the actix-analytics crate using Cargo, the Rust package manager. This is the first step to integrating the analytics middleware into your Actix Web application. ```bash cargo add actix-analytics ``` -------------------------------- ### Add axum-analytics Dependency Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/rust/axum/analytics/README.md Installs the axum-analytics crate into your Rust project using Cargo. ```bash cargo add axum-analytics ``` -------------------------------- ### API Analytics Self-Hosting Guide Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/echo/README.md Provides information on self-hosting the API Analytics project. It notes that self-hosting is still under development and testing, and is not recommended for production use at this time. ```APIDOC Self-Hosting: - Guide available at ./server/self-hosting/README.md. - Status: Undergoing testing, development, and improvements. - Recommendation: Avoid for production use until further notice. ``` -------------------------------- ### Sinatra API Analytics Middleware Setup Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Integrates the api-analytics gem into a Sinatra application by using it as middleware. Requires the gem and an API key. ```bash gem install api_analytics ``` ```ruby require 'sinatra' require 'api_analytics' use Analytics::Sinatra, # Add middleware before do content_type 'application/json' end get '/' do {message: 'Hello, World!'}.to_json end ``` -------------------------------- ### Axum Analytics Middleware Setup Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Integrates API Analytics into an Axum web application by adding it as middleware. Requires the 'axum-analytics' crate and an API key. ```bash cargo add axum-analytics ``` ```rust use axum::{routing::get, Json, Router}; use axum_analytics::Analytics; use serde::Serialize; use std::net::SocketAddr; #[derive(Serialize)] struct JsonData { message: String, } async fn root() -> Json { let json_data = JsonData { message: String::from("Hello World!"), }; Json(json_data) } #[tokio::main] async fn main() { let app = Router::new() .route("/", get(root)) .layer(Analytics::new()); let addr = SocketAddr::from(([127, 0, 0, 1], 8080)); let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); println!("Server listening at: http://127.0.0.1:8080"); axum::serve(listener, app).await.unwrap(); } ``` -------------------------------- ### Rocket Analytics Middleware Setup Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Adds API Analytics middleware to a Rocket web application. This requires the 'rocket-analytics' crate and a valid API key. ```bash cargo add rocket-analytics ``` ```rust #[macro_use] extern crate rocket; use rocket::serde::json::Json; use serde::Serialize; use rocket_analytics::Analytics; #[derive(Serialize)] pub struct JsonData { message: String, } #[get("/")] fn root() -> Json { let data = JsonData { message: "Hello, World!".to_string(), }; Json(data) } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![root]) .attach(Analytics::new()) } ``` -------------------------------- ### List Running Docker Containers Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Displays a list of all currently running Docker containers. Useful for verifying that all API Analytics services have started correctly. ```bash docker ps ``` -------------------------------- ### Configure Privacy Level in Go Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/gin/README.md Example of how to initialize the analytics configuration and set the privacy level to 2, disabling IP storing and location inference. ```go config := analytics.NewConfig() config.PrivacyLevel = 2 // Disable IP storing and location inference ``` -------------------------------- ### Integrate Echo Analytics Go Middleware Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/echo/README.md Example of adding Echo Analytics middleware to an Echo Go web server. It initializes the analytics middleware with an API key and applies it to the Echo instance. ```go package main import ( "net/http" "github.com/labstack/echo/v4" analytics "github.com/tom-draper/api-analytics/analytics/go/echo" ) func root(c echo.Context) error { data := map[string]string{ "message": "Hello, World!", } return c.JSON(http.StatusOK, data) } func main() { e := echo.New() e.Use(analytics.Analytics()) e.GET("/", root) e.Start(":8080") } ``` -------------------------------- ### Fetch API Analytics Data with cURL Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/ruby/api_analytics/README.md Fetches logged API request data using the cURL command-line tool. This example demonstrates setting the `X-AUTH-TOKEN` header for authentication. ```bash curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data ``` -------------------------------- ### ASP.NET Core API Analytics Middleware Setup Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Adds API Analytics middleware to an ASP.NET Core application using the APIAnalytics.AspNetCore NuGet package. Requires an API key. ```bash dotnet add package APIAnalytics.AspNetCore ``` ```csharp using Analytics; using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseAnalytics(); // Add middleware app.MapGet("/", () => { return Results.Ok(new OkObjectResult(new { message = "Hello, World!" })); }); app.Run(); ``` -------------------------------- ### Rails API Analytics Middleware Setup Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Configures the api-analytics gem as middleware in a Rails application. This involves adding the gem and specifying the middleware in application.rb. ```bash gem install api_analytics ``` ```ruby require 'rails' require 'api_analytics' Bundler.require(*Rails.groups) module RailsMiddleware class Application < Rails::Application config.load_defaults 6.1 config.api_only = true config.middleware.use ::Analytics::Rails, # Add middleware end end ``` -------------------------------- ### Implement Custom User ID Function in Go Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/gin/README.md Example of how to set a custom user ID retrieval function using the gin.Context to extract an 'X-AUTH-TOKEN' header. ```go config := analytics.NewConfig() config.GetUserID = func(c *gin.Context) string { return c.Request.Header.Get("X-AUTH-TOKEN") } ``` -------------------------------- ### FastAPI Middleware Integration Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Integrates API Analytics middleware into a FastAPI application. Requires installation via pip and adding the middleware with an API key. ```Bash pip install api-analytics[fastapi] ``` ```Python import uvicorn from fastapi import FastAPI from api_analytics.fastapi import Analytics app = FastAPI() app.add_middleware(Analytics, api_key=) # Add middleware @app.get('/') async def root(): return {'message': 'Hello, World!'} if __name__ == "__main__": uvicorn.run("app:app", reload=True) ``` -------------------------------- ### Install and Use Actix Analytics Middleware (Rust) Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Explains how to add the actix-analytics crate using cargo and integrate the Analytics middleware into an Actix web application. This middleware is for monitoring API traffic. It requires an API key for initialization. ```bash cargo add actix-analytics ``` ```rust use actix_web::{get, web, App, HttpServer, Responder, Result}; use serde::Serialize; use actix_analytics::Analytics; #[derive(Serialize)] struct JsonData { message: String, } #[get("/")] async fn index() -> Result { let data = JsonData { message: "Hello, World!".to_string(), }; Ok(web::Json(data)) } #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .wrap(Analytics::new()) // Add middleware .service(index) }) .bind(("127.0.0.1", 8080))? .run() .await } ``` -------------------------------- ### Generate API Key (Internal Test) Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Makes a GET request to the internal API endpoint for generating an API key. This is a quick test to confirm internal service communication. ```bash curl -X GET http://localhost:3000/api/generate ``` -------------------------------- ### Customise Echo Analytics Go Middleware Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/echo/README.md Example of customising Echo Analytics middleware behaviour in Go. It shows how to create a configuration object and assign custom functions for extracting IP addresses and user agents. ```go package main import ( "github.com/labstack/echo/v4" analytics "github.com/tom-draper/api-analytics/analytics/go/echo" ) func main() { e := echo.New() config := analytics.NewConfig() config.GetIPAddress = func(c echo.Context) string { return c.Request().Header.Get("X-Forwarded-For") } config.GetUserAgent = func(c echo.Context) string { return c.Request().Header.Get("User-Agent") } e.Use(analytics.AnalyticsWithConfig(, config)) e.GET("/", root) e.Start(":8080") } ``` -------------------------------- ### Fetch Analytics Data with Query Parameters Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/echo/README.md Example of fetching analytics data with various query parameters to filter results. Parameters include pagination, date ranges, hostname, IP address, status codes, location, and user ID. ```curl curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data?page=3&dateFrom=2022-01-01&hostname=apianalytics.dev&status=200&user_id=b56cbd92-1168-4d7b-8d94-0418da207908 ``` -------------------------------- ### Generate API Key (External Test - Domain) Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Makes a GET request to the API generate endpoint using the configured domain name over HTTPS. This tests external accessibility and SSL configuration. ```bash curl -X GET https://your-domain.com/api/generate ``` -------------------------------- ### Generate API Key (External Test - IP) Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Makes a GET request to the API generate endpoint using the server's public IP address. This tests external accessibility over HTTP. ```bash curl -X GET http://:3000/api/generate ``` -------------------------------- ### Build and Run Production Binary (Go) Source: https://github.com/tom-draper/api-analytics/blob/main/server/api/README.md Builds the Go backend service into an executable binary and then runs it for production. This involves compiling the source code and executing the resulting binary. ```bash go build -o bin/main main.go ./bin/main ``` -------------------------------- ### Build and Run Go Production Application Source: https://github.com/tom-draper/api-analytics/blob/main/server/monitor/README.md Compiles the Go application into an executable binary for production deployment and then runs the compiled application. The build command creates an executable file named 'main' in the 'bin' directory. ```bash go build -o bin/main main.go ``` ```bash ./bin/main ``` -------------------------------- ### Create Svelte Project with sv CLI Source: https://github.com/tom-draper/api-analytics/blob/main/dashboard/README.md Demonstrates how to create a new Svelte project using the `sv` command-line interface. It shows commands for creating a project in the current directory or a specified directory. ```bash npx sv create npx sv create my-app ``` -------------------------------- ### Run Go Development Build Source: https://github.com/tom-draper/api-analytics/blob/main/server/monitor/README.md Executes the Go program directly from source files for development purposes. This command compiles and runs the main Go application, allowing for immediate testing of changes without a formal build step. ```bash go run main.go ``` -------------------------------- ### Filter API Data with cURL Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/rust/rocket/analytics/README.md Shows how to filter analytics data by appending query parameters to the GET request. This example filters by page number, date range, hostname, status code, and user ID. ```bash curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data?page=3&dateFrom=2022-01-01&hostname=apianalytics.dev&status=200&user_id=b56cbd92-1168-4d7b-8d94-0418da207908 ``` -------------------------------- ### Build Svelte Production Version Source: https://github.com/tom-draper/api-analytics/blob/main/dashboard/README.md Provides commands to create a production-ready build of the Svelte application. It also mentions the command to preview the production build. ```bash npm run build You can preview the production build with `npm run preview`. ``` -------------------------------- ### Build Production Binary Source: https://github.com/tom-draper/api-analytics/blob/main/server/logger/README.md Compiles the backend service into an executable binary for production deployment. This command creates an optimized executable file. ```bash go build -o bin/main main.go ``` -------------------------------- ### Run Production Binary Source: https://github.com/tom-draper/api-analytics/blob/main/server/logger/README.md Executes the compiled production binary of the backend service. This is the command used to launch the application in a production environment. ```bash ./bin/main ``` -------------------------------- ### Access API Analytics Data Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/fastapi/README.md Provides examples for accessing logged API request data via the REST API. All examples require an API key set in the `X-AUTH-TOKEN` header. ```APIDOC API Data Access: Endpoint: GET https://apianalytics-server.com/api/data Authentication: Header: X-AUTH-TOKEN: Parameters (URL Query Parameters): - page: Integer, the page number for pagination (max page size 50,000). Defaults to 1. - date: String (YYYY-MM-DD), filter by exact request date. - dateFrom: String (YYYY-MM-DD), filter by lower bound of date range. - dateTo: String (YYYY-MM-DD), filter by upper bound of date range. - hostname: String, filter by the hostname of your service. - ipAddress: String, filter by the IP address of the client. - status: Integer, filter by the HTTP response status code. - location: String (2-character country code), filter by client location. - user_id: String, filter by a custom user identifier (requires `get_user_id` mapper). Examples: Python: import requests headers = { "X-AUTH-TOKEN": "" } response = requests.get("https://apianalytics-server.com/api/data", headers=headers) print(response.json()) Node.js: fetch("https://apianalytics-server.com/api/data", { headers: { "X-AUTH-TOKEN": "" }, }) .then((response) => { return response.json(); }) .then((data) => { console.log(data); }); cURL (Basic): curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data cURL (Filtered): curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data?page=3&dateFrom=2022-01-01&hostname=apianalytics.dev&status=200&user_id=b56cbd92-1168-4d7b-8d94-0418da207908 ``` -------------------------------- ### Clone API Analytics Repository Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Clones the API Analytics project repository from GitHub to your local machine. This is the first step in setting up the self-hosted environment. ```bash git clone github.com/tom-draper/api-analytics ``` -------------------------------- ### Access Analytics Data via API Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/rust/axum/analytics/README.md Provides examples for accessing logged API request data using the REST API. Includes methods for Python, Node.js, and cURL. ```APIDOC API Analytics Data API: Endpoint: https://apianalytics-server.com/api/data Method: GET Authentication: Header: X-AUTH-TOKEN: Parameters (Query String): - page (integer): The page number for pagination. Max page size is 50,000. Defaults to 1. - date (string): The exact day for filtering requests (YYYY-MM-DD). - dateFrom (string): The lower bound of a date range for filtering (YYYY-MM-DD). - dateTo (string): The upper bound of a date range for filtering (YYYY-MM-DD). - hostname (string): Filter by the hostname of your service. - ipAddress (string): Filter by the IP address of the client. - status (integer): Filter by the HTTP status code of the response. - location (string): Filter by a two-character location code of the client. - user_id (string): Filter by a custom user identifier (requires `get_user_id` mapper function). Example Usage: Python: import requests headers = { "X-AUTH-TOKEN": } response = requests.get("https://apianalytics-server.com/api/data", headers=headers) print(response.json()) Node.js: fetch("https://apianalytics-server.com/api/data", { headers: { "X-AUTH-TOKEN": }, }) .then((response) => { return response.json(); }) .then((data) => { console.log(data); }); cURL (Basic): curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data cURL (With Filters): curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data?page=3&dateFrom=2022-01-01&hostname=apianalytics.dev&status=200&user_id=b56cbd92-1168-4d7b-8d94-0418da207908 Return Value: JSON object containing logged request data, paginated according to parameters. ``` -------------------------------- ### Express Middleware Integration Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Adds API Analytics middleware to an Express.js application. Installation is done via npm, and the middleware is applied using app.use(). ```Bash npm install node-api-analytics ``` ```JavaScript import express from 'express'; import { expressAnalytics } from 'node-api-analytics'; const app = express(); app.use(expressAnalytics()); // Add middleware app.get('/', (req, res) => { res.send({ message: 'Hello, World!' }); }); app.listen(8080, () => { console.log('Server listening at http://localhost:8080'); }) ``` -------------------------------- ### Fastify Middleware Integration Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Integrates API Analytics middleware into a Fastify application. Installation is via npm, and the middleware is registered using a specific function. ```Bash npm install node-api-analytics ``` ```JavaScript import fastify from 'Fastify'; import { useFastifyAnalytics } from 'node-api-analytics'; const fastify = Fastify(); useFastifyAnalytics(fastify, apiKey); fastify.get('/', function (request, reply) { reply.send({ message: 'Hello World!' }); }) fastify.listen({ port: 8080 }, function (err, address) { console.log('Server listening at https://localhost:8080'); if (err) { fastify.log.error(err); process.exit(1); } }) ``` -------------------------------- ### Git Contribution Workflow Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/nodejs/README.md This snippet demonstrates the standard Git commands used to contribute to the project. It covers creating a new branch, committing changes, and pushing them for a pull request. ```git git checkout -b my-new-feature ``` ```git git commit -am "Add some feature" ``` ```git git push origin my-new-feature ``` -------------------------------- ### Tornado Middleware Integration Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/tornado/README.md Demonstrates how to integrate the Tornado Analytics middleware into a Tornado web application. The handler must inherit from `api_analytics.tornado.Analytics` and pass the API key during initialization. ```python import asyncio from tornado.web import Application from tornado.ioloop import IOLoop from api_analytics.tornado import Analytics # Inherit from the Analytics middleware class class MainHandler(Analytics): def __init__(self, app, res): super().__init__(app, res, "") # Provide api key def get(self): self.write({'message': 'Hello World!'}) def make_app(): return Application([ (r"/", MainHandler), ]) if __name__ == "__main__": app = make_app() app.listen(8080) IOLoop.instance().start() ``` -------------------------------- ### Execute Custom SQL Command Source: https://github.com/tom-draper/api-analytics/blob/main/server/self-hosting/README.md Executes a specified SQL command against the PostgreSQL database container. This is used for database initialization or running custom queries. ```bash docker exec -it db psql -U postgres -d analytics -c "YOUR SQL COMMAND;" ``` -------------------------------- ### Flask Middleware Integration Source: https://github.com/tom-draper/api-analytics/blob/main/README.md Adds API Analytics middleware to a Flask application. Installation is done via pip, and the middleware is added using a dedicated function. ```Bash pip install api-analytics[flask] ``` ```Python from flask import Flask from api_analytics.flask import add_middleware app = Flask(__name__) add_middleware(app, ) # Add middleware @app.get('/') def root(): return {'message': 'Hello, World!'} if __name__ == "__main__": app.run() ``` -------------------------------- ### Implement Custom User ID Mapping Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/fastapi/README.md Provides a custom function to map requests to user IDs, for example, by extracting an API key from the `X-AUTH-TOKEN` header for user identification in analytics. ```python config = Config() config.get_user_id = lambda request: request.headers.get('X-AUTH-TOKEN', '') ``` -------------------------------- ### Customize API Analytics Middleware with Mappers Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/csharp/analytics/README.md Example of customizing the API analytics middleware by assigning a custom function to the GetUserID mapper. This allows for extracting specific user identifiers from the HttpContext. ```cs using analytics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); // Assuming Config() returns an AnalyticsConfig object var config = new AnalyticsConfig(); // Placeholder for actual config object creation config.GetUserID = (HttpContext context) => { if (context.User.Identity != null && context.User.Identity.IsAuthenticated) return context.User.Identity.Name; return ""; }; app.UseAnalytics(, config); // Add middleware with custom configuration app.MapGet("/", () => { return Results.Ok(new OkObjectResult(new { message = "Hello, World!" })); }); app.Run(); ``` -------------------------------- ### Integrate API Analytics Middleware in ASP.NET Core Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/csharp/analytics/README.md Example of adding the API analytics middleware to an ASP.NET Core application pipeline using the UseAnalytics method. Requires an API key. ```cs using analytics; using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseAnalytics(); // Add middleware app.MapGet("/", () => { return Results.Ok(new OkObjectResult(new { message = "Hello, World!" })); }); app.Run(); ``` -------------------------------- ### Axum Middleware Integration Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/rust/axum/analytics/README.md Demonstrates how to integrate the axum-analytics middleware into an Axum application. It sets up a basic Axum router and applies the analytics layer using an API key. ```rust use axum::{routing::get, Json, Router}; use axum_analytics::Analytics; use serde::Serialize; use std::net::SocketAddr; #[derive(Serialize)] struct JsonData { message: String, } async fn root() -> Json { let json_data = JsonData { message: String::from("Hello World!"), }; Json(json_data) } #[tokio::main] async fn main() { let app = Router::new() .route("/", get(root)) .layer(Analytics::new()); let addr = SocketAddr::from(([127, 0, 0, 1], 8080)); let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); println!("Server listening at: http://127.0.0.1:8080"); axum::serve(listener, app).await.unwrap(); } ``` -------------------------------- ### Define Custom User ID Mapper Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/chi/README.md Shows how to provide a custom function to the API analytics middleware in Go to map requests to user IDs. This example uses the 'X-AUTH-TOKEN' header for identification. ```go config := analytics.NewConfig() config.GetUserID = func(r *http.Request) string { return r.Header.Get("X-AUTH-TOKEN") } ``` -------------------------------- ### Fetch Analytics Data via API Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/go/echo/README.md Demonstrates how to fetch raw logged request data from the Echo Analytics server using different client languages. Requires an API key in the X-AUTH-TOKEN header. ```py import requests headers = { "X-AUTH-TOKEN": } response = requests.get("https://apianalytics-server.com/api/data", headers=headers) print(response.json()) ``` ```js fetch("https://apianalytics-server.com/api/data", { headers: { "X-AUTH-TOKEN": }, }) .then((response) => { return response.json(); }) .then((data) => { console.log(data); }); ``` ```curl curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data ``` -------------------------------- ### Integrate Actix Analytics Middleware in Rust Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/rust/actix/analytics/README.md Demonstrates how to add the Actix Analytics middleware to an Actix Web application. The middleware requires an API key and is applied using the `.wrap()` method on the App configuration. ```rust use actix_web::{get, web, App, HttpServer, Responder, Result}; use serde::Serialize; use actix_analytics::Analytics; #[derive(Serialize)] struct JsonData { message: String, } #[get("/")] async fn index() -> Result { let data = JsonData { message: "Hello, World!".to_string(), }; Ok(web::Json(data)) } #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .wrap(Analytics::new()) // Add middleware .service(index) }) .bind(("127.0.0.1", 8080))? .run() .await } ``` -------------------------------- ### Data API Filtering Parameters Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/python/tornado/README.md Shows an example of filtering analytics data retrieved from the API. This cURL command filters by page number, date range, hostname, status code, and user ID. ```bash curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data?page=3&dateFrom=2022-01-01&hostname=apianalytics.dev&status=200&user_id=b56cbd92-1168-4d7b-8d94-0418da207908 ``` -------------------------------- ### Fastify Middleware Integration Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/nodejs/README.md Integrates API analytics middleware into a Fastify application. It requires the Fastify instance and an API key. ```javascript import fastify from 'Fastify'; import { useFastifyAnalytics } from 'node-api-analytics'; const fastify = Fastify(); useFastifyAnalytics(fastify, apiKey); fastify.get('/', function (request, reply) { reply.send({ message: 'Hello World!' }); }) fastify.listen({ port: 8080 }, function (err, address) { console.log('Server listening at https://localhost:8080'); if (err) { fastify.log.error(err); process.exit(1); } }) ``` -------------------------------- ### Fetch API Analytics Data via REST API Source: https://github.com/tom-draper/api-analytics/blob/main/analytics/rust/actix/analytics/README.md Provides examples for accessing logged API request data using the REST API. It shows how to set the API key in the 'X-AUTH-TOKEN' header and retrieve data. ```python import requests headers = { "X-AUTH-TOKEN": } response = requests.get("https://apianalytics-server.com/api/data", headers=headers) print(response.json()) ``` ```javascript fetch("https://apianalytics-server.com/api/data", { headers: { "X-AUTH-TOKEN": }, }) .then((response) => { return response.json(); }) .then((data) => { console.log(data); }); ``` ```curl curl --header "X-AUTH-TOKEN: " https://apianalytics-server.com/api/data ```