🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Update API documentation for sending events
Bill Yange0fc6a917968
diff --git a/docs/content/docs/api/meta.json b/docs/content/docs/api/meta.jsonindex cdf71c674..b91715656 100644--- a/docs/content/docs/api/meta.json+++ b/docs/content/docs/api/meta.json@@ -5,8 +5,8 @@"root": true,"pages": ["getting-started",+ "---Endpoints---","sending-events",- "---Analytics---","overview","sessions","session-replay",diff --git a/docs/content/docs/api/sending-events.mdx b/docs/content/docs/api/sending-events.mdxindex 4f02479b3..1674743cb 100644--- a/docs/content/docs/api/sending-events.mdx+++ b/docs/content/docs/api/sending-events.mdx@@ -1,83 +1,23 @@---title: Sending Events-description: Track events from server-side applications, mobile apps, or any platform using the HTTP API+description: Track pageviews, custom events, performance, and errors from any platform using the HTTP API.+full: true+method: POST----import { Steps, Step } from 'fumadocs-ui/components/steps';-import { Callout } from 'fumadocs-ui/components/callout';-import { Tabs, Tab } from 'fumadocs-ui/components/tabs';import { TypeTable } from 'fumadocs-ui/components/type-table';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">+<div>-Track events from server-side applications, mobile apps, or any platform using the HTTP API.--## Overview--The `/api/track` endpoint accepts tracking requests for pageviews, custom events, and more. Using an API key is optional but recommended for server-side tracking as it bypasses bot detection and domain validation.--### Data Enrichment--- **Geolocation**: IP addresses are resolved to country, region, city, and coordinates using MaxMind GeoLite2 database-- **Device Info**: User agent strings are parsed to extract browser, operating system, and device type information--## Steps--<Steps>-<Step>-### Generate API Key (Optional)--API keys are recommended for server-side tracking to bypass bot detection.--1. Navigate to **Settings → Account** in your Rybbit dashboard-2. Scroll to the **API Keys** section-3. Enter a name for your API key-4. Click **Create**-5. Copy the key immediately (it won't be shown again)--<Callout type="info">-API keys are user-scoped and grant access to all sites in your organization(s).-</Callout>-</Step>--<Step>-### Send Tracking Requests--<Tabs items={['Pageview', 'Custom Event']}>-<Tab value="Pageview">-```bash-curl -X POST 'https://app.rybbit.io/api/track' \- -H 'Content-Type: application/json' \- -H 'Authorization: Bearer rb_your_api_key_here' \- -d '{- "site_id": "123",- "type": "pageview",- "pathname": "/api/users",- "hostname": "api.example.com",- "page_title": "User API Endpoint",- "user_agent": "MyApp/1.0 (Linux; x64)",- "ip_address": "192.168.1.1"- }'```-</Tab>-<Tab value="Custom Event">-```bash-curl -X POST 'https://app.rybbit.io/api/track' \- -H 'Content-Type: application/json' \- -H 'Authorization: Bearer rb_your_api_key_here' \- -d '{- "site_id": "123",- "type": "custom_event",- "pathname": "/checkout",- "event_name": "purchase",- "properties": "{\"amount\": 99.99, \"currency\": \"USD\", \"product_id\": \"abc123\"}"- }'+POST /api/track```-</Tab>-</Tabs>-</Step>-</Steps>-## Parameters+Track pageviews, custom events, performance, and errors from server-side applications, mobile apps, or any platform. An API key is optional but recommended for server-side tracking — it bypasses bot detection and domain validation. IP addresses are resolved to geolocation and user agents are parsed for browser/OS/device info.++### Request BodyAll parameters are sent in the request body as JSON.@@ -165,15 +105,14 @@ All parameters are sent in the request body as JSON.}}/>-### Event Types-#### Pageview+Standard page view tracking. Set `type: "pageview"` (default).#### Custom Event+Track custom events with optional properties. Set `type: "custom_event"`.-**Required fields:**<TypeTabletype={{event_name: {@@ -190,19 +129,10 @@ Track custom events with optional properties. Set `type: "custom_event"`.}}/>-**Example:**-```json-{- "type": "custom_event",- "event_name": "purchase",- "properties": "{\"amount\": 99.99, \"currency\": \"USD\"}"-}-```-#### Performance+Track Core Web Vitals. Set `type: "performance"`.-**Performance metrics:**<TypeTabletype={{lcp: {@@ -233,22 +163,10 @@ Track Core Web Vitals. Set `type: "performance"`.}}/>-**Example:**-```json-{- "type": "performance",- "lcp": 2500,- "cls": 0.1,- "inp": 200,- "fcp": 1800,- "ttfb": 600-}-```-#### Outbound-Track outbound link clicks. Set `type: "outbound"`.-**Properties format:**+Track outbound link clicks. Set `type: "outbound"`. Pass details in the `properties` JSON string.+<TypeTabletype={{url: {@@ -268,36 +186,10 @@ Track outbound link clicks. Set `type: "outbound"`.}}/>-**Example:**-```json-{- "type": "outbound",- "properties": "{\"url\": \"https://example.com\", \"text\": \"Click here\", \"target\": \"_blank\"}"-}-```-#### Error-Track JavaScript errors. Set `type: "error"`.-**Required fields:**-<TypeTable- type={{- event_name: {- description: 'Error type',- type: 'string',- typeDescription: 'e.g., "TypeError", "ReferenceError"',- required: true,- },- properties: {- description: 'Error details as JSON string',- type: 'string',- typeDescription: 'Valid JSON, max 4096 chars',- required: true,- },- }}-/>+Track JavaScript errors. Set `type: "error"`. `event_name` is the error type and `properties` carries the error details as a JSON string.-**Properties format:**<TypeTabletype={{message: {@@ -326,771 +218,230 @@ Track JavaScript errors. Set `type: "error"`.}}/>-**Example:**-```json-{- "type": "error",- "event_name": "TypeError",- "properties": "{\"message\": \"Cannot read property\", \"stack\": \"...\", \"fileName\": \"app.js\", \"lineNumber\": 42}"-}-```+### Response-## Language Examples--<Tabs items={['Node.js', 'Python', 'Go', 'Java', 'PHP', 'Ruby', 'C#/.NET', 'Rust', 'iOS (Swift)', 'Android (Kotlin)', 'Flutter']}>-<Tab value="Node.js">-```javascript-const trackEvent = async (eventData) => {- const response = await fetch('https://app.rybbit.io/api/track', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Authorization': `Bearer ${process.env.RYBBIT_API_KEY}`,+<TypeTable+ type={{+ success: {+ description: 'Whether the event was accepted',+ type: 'boolean',},- body: JSON.stringify({- site_id: process.env.RYBBIT_SITE_ID,- ...eventData- })- });-- return response.json();-};--// Track a pageview-await trackEvent({- type: 'pageview',- pathname: '/api/users',- hostname: 'api.example.com'-});--// Track a custom event-await trackEvent({- type: 'custom_event',- pathname: '/checkout',- event_name: 'purchase',- properties: JSON.stringify({ amount: 99.99, currency: 'USD' })-});-```-</Tab>+ }}+/>-<Tab value="Python">-```python-import requests-import json-import os+### Rate Limiting-def track_event(event_data):- response = requests.post(- 'https://app.rybbit.io/api/track',- headers={- 'Content-Type': 'application/json',- 'Authorization': f"Bearer {os.getenv('RYBBIT_API_KEY')}"- },- json={- 'site_id': os.getenv('RYBBIT_SITE_ID'),- **event_data- }- )- return response.json()+API keys are limited to **500 requests per 10 minutes**. Exceeding the limit returns a `429` status code.-# Track a pageview-track_event({- 'type': 'pageview',- 'pathname': '/api/users',- 'hostname': 'api.example.com'-})+</div>+<div className="flex flex-col gap-4">-# Track a custom event-track_event({- 'type': 'custom_event',- 'pathname': '/checkout',- 'event_name': 'purchase',- 'properties': json.dumps({'amount': 99.99, 'currency': 'USD'})-})+<Tabs items={['cURL', 'JavaScript', 'Python', 'PHP', 'Ruby', 'Go', 'Rust', 'Java', '.NET']}>+ <Tab value="cURL">+```bash title="Request"+curl -X POST "https://app.rybbit.io/api/track" \+ -H "Authorization: Bearer your_api_key_here" \+ -H "Content-Type: application/json" \+ -d '{+ "site_id": "1",+ "type": "custom_event",+ "pathname": "/checkout",+ "event_name": "purchase",+ "properties": "{\"amount\": 99.99, \"currency\": \"USD\"}"+ }'```-</Tab>--<Tab value="Go">-```go-package main--import (- "bytes"- "encoding/json"- "net/http"- "os"-)--type TrackingEvent struct {- SiteID string `json:"site_id"`- Type string `json:"type"`- Pathname string `json:"pathname"`- Hostname string `json:"hostname,omitempty"`- EventName string `json:"event_name,omitempty"`- Properties string `json:"properties,omitempty"`-}--func trackEvent(event TrackingEvent) error {- event.SiteID = os.Getenv("RYBBIT_SITE_ID")-- jsonData, err := json.Marshal(event)- if err != nil {- return err- }-- req, err := http.NewRequest(- "POST",- "https://app.rybbit.io/api/track",- bytes.NewBuffer(jsonData),- )- if err != nil {- return err- }-- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+os.Getenv("RYBBIT_API_KEY"))-- client := &http.Client{}- resp, err := client.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()-- return nil-}--func main() {- // Track a pageview- trackEvent(TrackingEvent{- Type: "pageview",- Pathname: "/api/users",- Hostname: "api.example.com",- })+ </Tab>+ <Tab value="JavaScript">+```javascript title="Request"+const response = await fetch('https://app.rybbit.io/api/track', {+ method: 'POST',+ headers: {+ 'Authorization': 'Bearer your_api_key_here',+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ site_id: '1',+ type: 'custom_event',+ pathname: '/checkout',+ event_name: 'purchase',+ properties: JSON.stringify({ amount: 99.99, currency: 'USD' })+ })+});- // Track a custom event- trackEvent(TrackingEvent{- Type: "custom_event",- Pathname: "/checkout",- EventName: "purchase",- Properties: `{"amount": 99.99, "currency": "USD"}`,- })-}+const data = await response.json();```-</Tab>--<Tab value="Java">-```java-import java.net.http.HttpClient;-import java.net.http.HttpRequest;-import java.net.http.HttpResponse;-import java.net.URI;-import com.fasterxml.jackson.databind.ObjectMapper;-import java.util.Map;-import java.util.HashMap;--public class RybbitTracker {- private static final String API_URL = "https://app.rybbit.io/api/track";- private static final String API_KEY = System.getenv("RYBBIT_API_KEY");- private static final String SITE_ID = System.getenv("RYBBIT_SITE_ID");-- private final HttpClient httpClient = HttpClient.newHttpClient();- private final ObjectMapper objectMapper = new ObjectMapper();-- public void trackEvent(Map<String, Object> eventData) throws Exception {- eventData.put("site_id", SITE_ID);-- String json = objectMapper.writeValueAsString(eventData);-- HttpRequest request = HttpRequest.newBuilder()- .uri(URI.create(API_URL))- .header("Content-Type", "application/json")- .header("Authorization", "Bearer " + API_KEY)- .POST(HttpRequest.BodyPublishers.ofString(json))- .build();-- HttpResponse<String> response = httpClient.send(request,- HttpResponse.BodyHandlers.ofString());+ </Tab>+ <Tab value="Python">+```python title="Request"+import requests+import json- if (response.statusCode() != 200) {- throw new Exception("Tracking failed: " + response.body());- }+response = requests.post(+ 'https://app.rybbit.io/api/track',+ json={+ 'site_id': '1',+ 'type': 'custom_event',+ 'pathname': '/checkout',+ 'event_name': 'purchase',+ 'properties': json.dumps({'amount': 99.99, 'currency': 'USD'})+ },+ headers={+ 'Authorization': 'Bearer your_api_key_here'}+)- public static void main(String[] args) throws Exception {- RybbitTracker tracker = new RybbitTracker();-- // Track a pageview- Map<String, Object> pageview = new HashMap<>();- pageview.put("type", "pageview");- pageview.put("pathname", "/api/users");- pageview.put("hostname", "api.example.com");- tracker.trackEvent(pageview);-- // Track a custom event- Map<String, Object> customEvent = new HashMap<>();- customEvent.put("type", "custom_event");- customEvent.put("pathname", "/checkout");- customEvent.put("event_name", "purchase");- customEvent.put("properties", "{\"amount\": 99.99, \"currency\": \"USD\"}");- tracker.trackEvent(customEvent);- }-}+data = response.json()```-</Tab>--<Tab value="PHP">-```php-<?php--class RybbitTracker {- private $apiUrl = 'https://app.rybbit.io/api/track';- private $apiKey;- private $siteId;-- public function __construct() {- $this->apiKey = getenv('RYBBIT_API_KEY');- $this->siteId = getenv('RYBBIT_SITE_ID');- }-- public function trackEvent($eventData) {- $eventData['site_id'] = $this->siteId;-- $ch = curl_init($this->apiUrl);- curl_setopt($ch, CURLOPT_POST, 1);- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($eventData));- curl_setopt($ch, CURLOPT_HTTPHEADER, [- 'Content-Type: application/json',- 'Authorization: Bearer ' . $this->apiKey- ]);- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);-- $response = curl_exec($ch);- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);- curl_close($ch);-- if ($httpCode !== 200) {- throw new Exception('Tracking failed: ' . $response);- }-- return json_decode($response, true);- }-}--// Usage-$tracker = new RybbitTracker();--// Track a pageview-$tracker->trackEvent([- 'type' => 'pageview',- 'pathname' => '/api/users',- 'hostname' => 'api.example.com'-]);--// Track a custom event-$tracker->trackEvent([+ </Tab>+ <Tab value="PHP">+```php title="Request"+$body = [+ 'site_id' => '1','type' => 'custom_event','pathname' => '/checkout','event_name' => 'purchase','properties' => json_encode(['amount' => 99.99, 'currency' => 'USD'])+];++$ch = curl_init();+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/track');+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+curl_setopt($ch, CURLOPT_POST, true);+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));+curl_setopt($ch, CURLOPT_HTTPHEADER, [+ 'Authorization: Bearer your_api_key_here',+ 'Content-Type: application/json']);-```-</Tab>-<Tab value="Ruby">-```ruby+$response = curl_exec($ch);+curl_close($ch);++$data = json_decode($response, true);+```+ </Tab>+ <Tab value="Ruby">+```ruby title="Request"require 'net/http'require 'json'-require 'uri'--class RybbitTracker- API_URL = 'https://app.rybbit.io/api/track'-- def initialize- @api_key = ENV['RYBBIT_API_KEY']- @site_id = ENV['RYBBIT_SITE_ID']- end-- def track_event(event_data)- event_data[:site_id] = @site_id-- uri = URI(API_URL)- http = Net::HTTP.new(uri.host, uri.port)- http.use_ssl = true-- request = Net::HTTP::Post.new(uri.path)- request['Content-Type'] = 'application/json'- request['Authorization'] = "Bearer #{@api_key}"- request.body = event_data.to_json- response = http.request(request)-- unless response.code == '200'- raise "Tracking failed: #{response.body}"- end-- JSON.parse(response.body)- end-end--# Usage-tracker = RybbitTracker.new--# Track a pageview-tracker.track_event({- type: 'pageview',- pathname: '/api/users',- hostname: 'api.example.com'-})--# Track a custom event-tracker.track_event({+uri = URI('https://app.rybbit.io/api/track')+request = Net::HTTP::Post.new(uri)+request['Authorization'] = 'Bearer your_api_key_here'+request['Content-Type'] = 'application/json'+request.body = {+ site_id: '1',type: 'custom_event',pathname: '/checkout',event_name: 'purchase',- properties: JSON.generate({ amount: 99.99, currency: 'USD' })-})-```-</Tab>--<Tab value="C#/.NET">-```csharp-using System;-using System.Net.Http;-using System.Net.Http.Headers;-using System.Text;-using System.Text.Json;-using System.Threading.Tasks;-using System.Collections.Generic;+ properties: { amount: 99.99, currency: 'USD' }.to_json+}.to_json-public class RybbitTracker-{- private readonly HttpClient _httpClient;- private readonly string _apiKey;- private readonly string _siteId;- private const string ApiUrl = "https://app.rybbit.io/api/track";-- public RybbitTracker()- {- _httpClient = new HttpClient();- _apiKey = Environment.GetEnvironmentVariable("RYBBIT_API_KEY");- _siteId = Environment.GetEnvironmentVariable("RYBBIT_SITE_ID");- _httpClient.DefaultRequestHeaders.Authorization =- new AuthenticationHeaderValue("Bearer", _apiKey);- }-- public async Task TrackEventAsync(Dictionary<string, object> eventData)- {- eventData["site_id"] = _siteId;-- var json = JsonSerializer.Serialize(eventData);- var content = new StringContent(json, Encoding.UTF8, "application/json");-- var response = await _httpClient.PostAsync(ApiUrl, content);-- if (!response.IsSuccessStatusCode)- {- var error = await response.Content.ReadAsStringAsync();- throw new Exception($"Tracking failed: {error}");- }- }-- static async Task Main(string[] args)- {- var tracker = new RybbitTracker();-- // Track a pageview- await tracker.TrackEventAsync(new Dictionary<string, object>- {- ["type"] = "pageview",- ["pathname"] = "/api/users",- ["hostname"] = "api.example.com"- });+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|+ http.request(request)+end- // Track a custom event- await tracker.TrackEventAsync(new Dictionary<string, object>- {- ["type"] = "custom_event",- ["pathname"] = "/checkout",- ["event_name"] = "purchase",- ["properties"] = JsonSerializer.Serialize(new { amount = 99.99, currency = "USD" })- });- }-}+data = JSON.parse(response.body)```-</Tab>--<Tab value="Rust">-```rust-use reqwest;-use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};-use serde_json::{json, Value};-use std::env;--#[derive(Clone)]-struct RybbitTracker {- client: reqwest::Client,- api_key: String,- site_id: String,- api_url: String,-}--impl RybbitTracker {- fn new() -> Self {- Self {- client: reqwest::Client::new(),- api_key: env::var("RYBBIT_API_KEY").expect("RYBBIT_API_KEY not set"),- site_id: env::var("RYBBIT_SITE_ID").expect("RYBBIT_SITE_ID not set"),- api_url: "https://app.rybbit.io/api/track".to_string(),- }- }-- async fn track_event(&self, mut event_data: Value) -> Result<(), Box<dyn std::error::Error>> {- event_data["site_id"] = json!(self.site_id);-- let mut headers = HeaderMap::new();- headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));- headers.insert(- AUTHORIZATION,- HeaderValue::from_str(&format!("Bearer {}", self.api_key))?,- );-- let response = self.client- .post(&self.api_url)- .headers(headers)- .json(&event_data)- .send()- .await?;-- if !response.status().is_success() {- let error_text = response.text().await?;- return Err(format!("Tracking failed: {}", error_text).into());- }-- Ok(())- }+ </Tab>+ <Tab value="Go">+```go title="Request"+body := map[string]interface{}{+ "site_id": "1",+ "type": "custom_event",+ "pathname": "/checkout",+ "event_name": "purchase",+ "properties": `{"amount": 99.99, "currency": "USD"}`,}+jsonBody, _ := json.Marshal(body)-#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error>> {- let tracker = RybbitTracker::new();+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/track", bytes.NewBuffer(jsonBody))+req.Header.Set("Authorization", "Bearer your_api_key_here")+req.Header.Set("Content-Type", "application/json")- // Track a pageview- tracker.track_event(json!({- "type": "pageview",- "pathname": "/api/users",- "hostname": "api.example.com"- })).await?;+client := &http.Client{}+resp, _ := client.Do(req)+defer resp.Body.Close()- // Track a custom event- tracker.track_event(json!({- "type": "custom_event",- "pathname": "/checkout",- "event_name": "purchase",- "properties": r#"{"amount": 99.99, "currency": "USD"}"#- })).await?;-- Ok(())-}+var data map[string]interface{}+json.NewDecoder(resp.Body).Decode(&data)```-</Tab>--<Tab value="iOS (Swift)">-```swift-import Foundation-import UIKit--class RybbitTracker {- static let shared = RybbitTracker()-- private let apiUrl = "https://app.rybbit.io/api/track"- private let apiKey: String- private let siteId: String-- init() {- // Ensure API key and site ID are available- guard let apiKey = ProcessInfo.processInfo.environment["RYBBIT_API_KEY"],- !apiKey.isEmpty,- let siteId = ProcessInfo.processInfo.environment["RYBBIT_SITE_ID"],- !siteId.isEmpty else {- fatalError("RYBBIT_API_KEY and RYBBIT_SITE_ID environment variables must be set")- }- self.apiKey = apiKey- self.siteId = siteId- }-- func trackEvent(_ eventData: [String: Any]) async throws {- var data = eventData- data["site_id"] = siteId-- // Add device info- data["user_agent"] = getUserAgent()-- // Get screen dimensions in logical pixels (points)- if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {- let bounds = windowScene.screen.bounds- data["screenWidth"] = Int(bounds.width)- data["screenHeight"] = Int(bounds.height)- } else {- // Fallback for older iOS versions- let bounds = UIScreen.main.bounds- data["screenWidth"] = Int(bounds.width)- data["screenHeight"] = Int(bounds.height)- }-- data["language"] = Locale.current.languageCode ?? "en"-- var request = URLRequest(url: URL(string: apiUrl)!)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")- request.httpBody = try JSONSerialization.data(withJSONObject: data)-- let (_, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse,- httpResponse.statusCode == 200 else {- throw NSError(domain: "RybbitTracker", code: 1, userInfo: [NSLocalizedDescriptionKey: "Tracking failed"])- }- }-- private func getUserAgent() -> String {- let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0"- let osVersion = UIDevice.current.systemVersion- let model = UIDevice.current.model- return "MyApp/\(appVersion) (iOS \(osVersion); \(model))"- }-}+ </Tab>+ <Tab value="Rust">+```rust title="Request"+let body = serde_json::json!({+ "site_id": "1",+ "type": "custom_event",+ "pathname": "/checkout",+ "event_name": "purchase",+ "properties": r#"{"amount": 99.99, "currency": "USD"}"#+});-// Usage-Task {- // Track a pageview- try await RybbitTracker.shared.trackEvent([- "type": "pageview",- "pathname": "/api/users",- "hostname": "api.example.com",- "page_title": "User API Endpoint"- ])+let client = reqwest::Client::new();+let res = client+ .post("https://app.rybbit.io/api/track")+ .header("Authorization", "Bearer your_api_key_here")+ .json(&body)+ .send()+ .await?;- // Track a custom event- try await RybbitTracker.shared.trackEvent([- "type": "custom_event",- "pathname": "/checkout",- "event_name": "purchase",- "properties": "{\"amount\": 99.99, \"currency\": \"USD\"}"- ])-}+let data: serde_json::Value = res.json().await?;```-</Tab>--<Tab value="Android (Kotlin)">-```kotlin-import kotlinx.coroutines.*-import okhttp3.*-import okhttp3.MediaType.Companion.toMediaType-import okhttp3.RequestBody.Companion.toRequestBody-import org.json.JSONObject-import android.content.Context-import android.os.Build-import java.util.Locale--class RybbitTracker(private val context: Context) {- companion object {- private const val API_URL = "https://app.rybbit.io/api/track"- private val JSON = "application/json; charset=utf-8".toMediaType()- }-- private val client = OkHttpClient()- private val apiKey = BuildConfig.RYBBIT_API_KEY // Set in build.gradle- private val siteId = BuildConfig.RYBBIT_SITE_ID-- suspend fun trackEvent(eventData: Map<String, Any>) = withContext(Dispatchers.IO) {- val data = eventData.toMutableMap().apply {- put("site_id", siteId)- put("user_agent", getUserAgent())-- // Get screen dimensions in logical pixels (density-independent pixels)- val displayMetrics = context.resources.displayMetrics- put("screenWidth", (displayMetrics.widthPixels / displayMetrics.density).toInt())- put("screenHeight", (displayMetrics.heightPixels / displayMetrics.density).toInt())- put("language", Locale.getDefault().language)- }-- val json = JSONObject(data).toString()- val body = json.toRequestBody(JSON)-- val request = Request.Builder()- .url(API_URL)- .addHeader("Authorization", "Bearer $apiKey")- .post(body)- .build()-- client.newCall(request).execute().use { response ->- if (!response.isSuccessful) {- throw Exception("Tracking failed: ${response.code}")- }- }- }-- private fun getUserAgent(): String {- val appVersion = context.packageManager- .getPackageInfo(context.packageName, 0).versionName- return "MyApp/$appVersion (Android ${Build.VERSION.RELEASE}; ${Build.MODEL})"- }+ </Tab>+ <Tab value="Java">+```java title="Request"+String json = """+{+ "site_id": "1",+ "type": "custom_event",+ "pathname": "/checkout",+ "event_name": "purchase",+ "properties": "{\"amount\": 99.99, \"currency\": \"USD\"}"}+""";-// Usage-class MainActivity : AppCompatActivity() {- private val tracker = RybbitTracker(this)-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)-- lifecycleScope.launch {- // Track a pageview- tracker.trackEvent(mapOf(- "type" to "pageview",- "pathname" to "/api/users",- "hostname" to "api.example.com",- "page_title" to "User API Endpoint"- ))+HttpClient client = HttpClient.newHttpClient();+HttpRequest request = HttpRequest.newBuilder()+ .uri(URI.create("https://app.rybbit.io/api/track"))+ .header("Authorization", "Bearer your_api_key_here")+ .header("Content-Type", "application/json")+ .POST(HttpRequest.BodyPublishers.ofString(json))+ .build();- // Track a custom event- tracker.trackEvent(mapOf(- "type" to "custom_event",- "pathname" to "/checkout",- "event_name" to "purchase",- "properties" to """{"amount": 99.99, "currency": "USD"}"""- ))- }- }-}+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());```-</Tab>--<Tab value="Flutter">-```dart-import 'package:http/http.dart' as http;-import 'dart:convert';-import 'dart:io';-import 'package:flutter/material.dart';-import 'package:device_info_plus/device_info_plus.dart';--class RybbitTracker {- static final RybbitTracker _instance = RybbitTracker._internal();- factory RybbitTracker() => _instance;- RybbitTracker._internal();-- static const String _apiUrl = 'https://app.rybbit.io/api/track';- static const String _apiKey = String.fromEnvironment('RYBBIT_API_KEY');- static const String _siteId = String.fromEnvironment('RYBBIT_SITE_ID');-- final _deviceInfoPlugin = DeviceInfoPlugin();-- Future<void> trackEvent(Map<String, dynamic> eventData) async {- final data = Map<String, dynamic>.from(eventData);- data['site_id'] = _siteId;-- // Add device info- data['user_agent'] = await _getUserAgent();-- // Get screen dimensions in logical pixels (density-independent pixels)- final view = WidgetsBinding.instance.platformDispatcher.views.first;- data['screenWidth'] = (view.physicalSize.width / view.devicePixelRatio).round();- data['screenHeight'] = (view.physicalSize.height / view.devicePixelRatio).round();- data['language'] = Platform.localeName.split('_')[0];-- final response = await http.post(- Uri.parse(_apiUrl),- headers: {- 'Content-Type': 'application/json',- 'Authorization': 'Bearer $_apiKey',- },- body: json.encode(data),- );-- if (response.statusCode != 200) {- throw Exception('Tracking failed: ${response.statusCode}');- }- }-- Future<String> _getUserAgent() async {- const appVersion = '1.0.0'; // Get from package_info_plus if needed-- if (Platform.isAndroid) {- final androidInfo = await _deviceInfoPlugin.androidInfo;- return 'MyApp/$appVersion (Android ${androidInfo.version.release}; ${androidInfo.model})';- } else if (Platform.isIOS) {- final iosInfo = await _deviceInfoPlugin.iosInfo;- return 'MyApp/$appVersion (iOS ${iosInfo.systemVersion}; ${iosInfo.model})';- }-- return 'MyApp/$appVersion (${Platform.operatingSystem})';- }-}--// Usage-void main() {- runApp(MyApp());-}--class MyApp extends StatefulWidget {- @override- _MyAppState createState() => _MyAppState();-}+ </Tab>+ <Tab value=".NET">+```csharp title="Request"+var body = new+{+ site_id = "1",+ type = "custom_event",+ pathname = "/checkout",+ event_name = "purchase",+ properties = JsonSerializer.Serialize(new { amount = 99.99, currency = "USD" })+};-class _MyAppState extends State<MyApp> {- final tracker = RybbitTracker();+using var client = new HttpClient();+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");- @override- void initState() {- super.initState();- // Track app launch once when the app initializes- tracker.trackEvent({- 'type': 'pageview',- 'pathname': '/api/users',- 'hostname': 'api.example.com',- 'page_title': 'User API Endpoint',- });- }+var content = new StringContent(+ JsonSerializer.Serialize(body),+ Encoding.UTF8,+ "application/json");- @override- Widget build(BuildContext context) {- return MaterialApp(- home: Scaffold(- body: Center(- child: ElevatedButton(- onPressed: () {- // Track custom event- tracker.trackEvent({- 'type': 'custom_event',- 'pathname': '/checkout',- 'event_name': 'purchase',- 'properties': json.encode({'amount': 99.99, 'currency': 'USD'}),- });- },- child: Text('Track Event'),- ),- ),- ),- );- }-}+var response = await client.PostAsync("https://app.rybbit.io/api/track", content);+var data = await response.Content.ReadAsStringAsync();```-</Tab>+ </Tab></Tabs>-## Response Format--### Success Response-```json+```json title="Success"{"success": true}```-### Error Response-```json+```json title="Error"{"success": false,"error": "Invalid payload",@@ -1101,45 +452,5 @@ class _MyAppState extends State<MyApp> {}```-## Rate Limiting--API keys have built-in rate limiting:-- **500 requests per 10 minutes** per API key-- When exceeded, you'll receive a `429` status code--```json-{- "success": false,- "error": "Rate limit exceeded. Maximum 500 requests per 10 minutes per API key."-}-```--## Best Practices--<Callout type="info">-**Environment Variables**: Store your API key and site ID as environment variables to keep them secure.-</Callout>--<Callout type="warn">-**API Key Security**: Never expose API keys in client-side code or public repositories. Use them only for server-side tracking.-</Callout>--<Callout type="info">-**Browser Tracking**: For standard browser-based tracking, use the [Rybbit Web SDK](/docs/sdks/web) instead. The HTTP API is designed for server-side applications, mobile apps, and custom integrations.-</Callout>--<Callout type="info">-**Organization Access**: API keys are user-scoped and grant access to all sites in your organization(s). Ensure the API key owner is a member of the organization that owns the site you're tracking.-</Callout>--## Error Handling--Common error scenarios:-- **Invalid payload**: Ensure required fields are present and data types match-- **Site not found**: Verify your site ID is correct-- **Invalid API key**: Check that your API key is valid and hasn't expired-- **Access denied**: Ensure the API key owner is a member of the site's organization-- **Rate limit exceeded**: Reduce request frequency or implement request queuing-- **JSON parsing errors**: For custom events, ensure properties field contains valid JSON-- **Bot detected**: Use an API key to bypass bot detection for server-side tracking-- **Over monthly limit**: Your site has exceeded its monthly pageview limit+</div>+</div>