Skip to content
pugdocs

HTTP API

Send events and identify users from any language by POSTing JSON to Pug's Connect API - no SDK required.

No SDK for your runtime? Anything that can POST JSON can send events and identify users. The API reference has the full schemas.

Setup

Send requests to https://api.pugs.dev, or your self-hosted base URL (e.g. http://localhost:3000), with three headers:

Header Value
Content-Type application/json
Connect-Protocol-Version 1
x-api-key Your private key (prv_...) from a backend, or your public key (pub_...) from the visitor’s own device. The key decides what the server adds - see Auto-tracking

Keep the private key in an environment variable or a secret store, never in code shipped to a browser or app. A public key may go in an api_key query parameter instead of the header; a private key can’t.

Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in Install with AI.

Prompt
Add Pug product analytics to this service by calling the HTTP API directly - there is no SDK for this runtime.

Read these first - they are the current source of truth, and more recent than your training data:
- https://docs.pug.sh/sdks/http/index.md - request format, including worked examples
- https://docs.pug.sh/api/events/index.md - the full event schema
- https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog

Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. The events worth tracking are the moments the service exists to produce, not request logging. If you cannot state what this service is for in one sentence, keep reading.

Then:
1. Write one small client that POSTs to /sdk.events.v1.EventsService/BatchCreate on the base URL, with the headers Content-Type: application/json, Connect-Protocol-Version: 1, and x-api-key set to the private key (prv_...) from an environment variable, never committed.
2. Wrap every custom property value in its typed form - stringValue, intValue (a JSON string), doubleValue, boolValue, timestampValue. This is the part that is most often wrong. Property keys must not start with a dollar sign, and the event kind may hold only ASCII letters, digits, _, . and -.
3. Send events in batches of at most 1000, and read "dropped" and "droppedByReason" on the response - a 200 does not mean every event landed.
4. Call it for the three or four actions you identified.

Name events from the catalog before you invent one. All 127 well-known events are available over HTTP, and a well-known kind fills in the dashboards built on it, which a custom kind leaves empty. Nothing checks their properties - no compiler, and not the server, which stores what it is sent - so a misspelled name or a wrong type fails silently. Search the catalog for every action you are about to track, take property names and types from that page, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not.

Do not invent fields that are not in the events schema above. When you are done, tell me in one sentence what you concluded this service does, then show me the client, the event names you chose, and the environment variables I need to set.

Track events

Each event’s name is its kind. Any name works without a schema; well-known events add typed properties and richer dashboards, but nothing checks their properties over HTTP.

Endpoint: POST /sdk.events.v1.EventsService/BatchCreate

{
  "events": [
    {
      "eventId": "01966b9e-1234-7abc-abcd-0123456789ab",
      "distinctId": "anon-abc123",
      "kind": "purchase",
      "sessionId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "occurTime": "2026-06-05T10:00:00Z",
      "customProperties": {
        "productId": { "stringValue": "sku_123" },
        "amount": { "doubleValue": 29.99 },
        "currency": { "stringValue": "USD" }
      },
      "autoProperties": {}
    }
  ]
}

Wrap every property value in a typed object:

Type JSON shape Notes
String { "stringValue": "hello" } At most 1024 characters
Integer { "intValue": "42" } int64, as a JSON string or a whole number
Double { "doubleValue": 3.14 } Must be finite
Boolean { "boolValue": true }
Timestamp { "timestampValue": "2026-06-05T10:00:00Z" } RFC 3339

Requests must also pass the validation rules. The response is { "accepted": <n>, "dropped": <n> }: dropped counts cookieless events the server couldn’t derive an identity for, and droppedByReason says why, so a 200 doesn’t mean every event landed. The Events API reference has the full schema and the drop reasons.

Identify and sessions

Use a stable, unique external ID - your database user ID, not an email, which can change. An identify merges a user’s prior anonymous activity only when it carries their anonymousId, so send it on the first identify after an anonymous session; the same external ID always resolves to the same profile, and traits are merged server-side, never removed.

Endpoint: POST /sdk.profiles.v1.ProfilesSDKService/Identify

{
  "externalId": "user-123",
  "traits": { "email": "user@example.com", "plan": "pro", "seats": 5 },
  "anonymousId": "anon-abc123"
}
Field JSON name Required Description
external_id externalId Yes Stable user identifier; must not start with cookieless-
traits traits No Profile properties; shallow-merged on conflict
anonymous_id anonymousId No The distinctId the user’s anonymous events carried; must start with anon-
device_id deviceId No Device to assign (the Flutter SDK sends one; omit for web)

The response is {}; the identify is applied asynchronously, so a read straight after it may not see it yet. You set each event’s distinctId yourself: the anonymous ID before identify, your external ID after. BatchIdentify sends up to 1000 identifies in one request.

Sessions

Each event’s sessionId is a UUID you choose, grouping events in a visit; the server uses it as sent. A cookieless event omits it, and the server stitches one instead, closed after 30 minutes of inactivity.

Auto-tracking

There is no auto-tracking: you send every event yourself. On a public-key request the server derives geo ($country, $city, …) and user-agent properties ($browser, $os, …) from the request, so from a backend they describe your server, not the visitor. On a private-key request it derives neither and keeps those you send in autoProperties, so forward the visitor’s location there, with $country as ISO 3166-1 alpha-2 (Auto-properties). Either way $ip is stripped rather than geolocated, and any server-only property you send ($bot, $bot_reason, $bot_score, $verified_bot, $channel, $referrerDomain) is dropped.

There is no consent gate and no redaction: respect the visitor’s consent choice before you send, and keep PII out of the properties. For a visitor who hasn’t consented, set "cookieless": true and omit distinctId and sessionId; the server derives a daily-rotating identity from the request’s IP address and User-Agent (Cookieless events). Send these from the visitor’s own device: from your backend, every visitor gets the same identity.

Errors

Errors use Connect’s HTTP status codes, with a JSON body naming the code and the rule broken (see the error model):

{
  "code": "invalid_argument",
  "message": "validation error: events[0].kind: does not match regex pattern `^[a-zA-Z0-9_.-]+$`"
}
HTTP status Connect code Meaning
400 invalid_argument The request was malformed or broke a rule below, and nothing in it was stored. Fix it rather than retry
401 unauthenticated Missing or invalid key, or a private key in the api_key query parameter
409 aborted An identical batch is still being stored: retry
429 resource_exhausted The body is over 8 MiB, after decompression: split the batch
500 internal Server error: retry with backoff
503 unavailable The key couldn’t be checked: retry with backoff

Resend the same events on a retry, with the same eventId and occurTime, so any stored before the error are deduplicated rather than counted twice.

Validation rules:

Rule Detail
Batch At most 1000 events, no two with the same eventId
eventId Required, a UUID
distinctId, sessionId Required unless cookieless is true, then omitted. sessionId is a UUID, and distinctId must not start with cookieless-
kind Required; only ASCII letters, digits, _, . and -
occurTime Required, RFC 3339 with Z or an offset
customProperties keys Must not start with $
autoProperties keys Must start with $
Property values Exactly one typed field each, within the limits above
Unknown fields Ignored, not rejected: a misspelled name such as customProps loses its data silently

Examples

curl -X POST https://api.pugs.dev/sdk.events.v1.EventsService/BatchCreate \
  -H 'Content-Type: application/json' \
  -H 'Connect-Protocol-Version: 1' \
  -H "x-api-key: $PUG_PRIVATE_KEY" \
  -d '{
    "events": [{
      "eventId": "01966b9e-1234-7abc-abcd-0123456789ab",
      "distinctId": "anon-abc123",
      "kind": "page_view",
      "sessionId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "occurTime": "2026-06-05T10:00:00Z",
      "customProperties": { "path": { "stringValue": "/pricing" } },
      "autoProperties": {}
    }]
  }'
import os
import uuid
from datetime import datetime, timezone
import requests

API_KEY = os.environ["PUG_PRIVATE_KEY"]
BASE_URL = "https://api.pugs.dev"

def send_event(distinct_id, kind, session_id, custom_props):
    event = {
        "eventId": str(uuid.uuid4()),  # swap for uuidv7() if available
        "distinctId": distinct_id,
        "kind": kind,
        "sessionId": session_id,
        "occurTime": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "customProperties": custom_props,
        "autoProperties": {},
    }
    resp = requests.post(
        f"{BASE_URL}/sdk.events.v1.EventsService/BatchCreate",
        headers={
            "Content-Type": "application/json",
            "Connect-Protocol-Version": "1",
            "x-api-key": API_KEY,
        },
        json={"events": [event]},
        timeout=5,
    )
    resp.raise_for_status()
    return resp.json()

result = send_event(
    "anon-abc123", "signup", "f47ac10b-58cc-4372-a567-0e02b2c3d479",
    {"plan": {"stringValue": "pro"}, "seats": {"intValue": "5"}},  # int64 as a JSON string
)
print(result)  # {"accepted": 1, "dropped": 0}

A Go backend can use the Go SDK instead. Over raw HTTP:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"

	"github.com/google/uuid"
)

const baseURL = "https://api.pugs.dev"

// propertyValue is the Connect-JSON encoding of the protobuf oneof.
type propertyValue struct {
	StringValue    *string  `json:"stringValue,omitempty"`
	IntValue       *string  `json:"intValue,omitempty"`       // int64 as a JSON string
	DoubleValue    *float64 `json:"doubleValue,omitempty"`
	BoolValue      *bool    `json:"boolValue,omitempty"`
	TimestampValue *string  `json:"timestampValue,omitempty"` // RFC 3339
}

func strVal(s string) propertyValue { return propertyValue{StringValue: &s} }

type event struct {
	EventID          string                   `json:"eventId"`
	DistinctID       string                   `json:"distinctId"`
	Kind             string                   `json:"kind"`
	SessionID        string                   `json:"sessionId"`
	OccurTime        string                   `json:"occurTime"`
	CustomProperties map[string]propertyValue `json:"customProperties"`
	AutoProperties   map[string]propertyValue `json:"autoProperties"`
}

func main() {
	body, _ := json.Marshal(map[string]any{
		"events": []event{{
			EventID:          uuid.New().String(),
			DistinctID:       "anon-abc123",
			Kind:             "signup",
			SessionID:        "f47ac10b-58cc-4372-a567-0e02b2c3d479",
			OccurTime:        time.Now().UTC().Format(time.RFC3339),
			CustomProperties: map[string]propertyValue{"plan": strVal("pro")},
			AutoProperties:   map[string]propertyValue{},
		}},
	})

	req, _ := http.NewRequest(http.MethodPost,
		baseURL+"/sdk.events.v1.EventsService/BatchCreate", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Connect-Protocol-Version", "1")
	req.Header.Set("x-api-key", os.Getenv("PUG_PRIVATE_KEY"))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	fmt.Println("status:", resp.Status)
}
Navigation

Type to search...

↑↓ navigate↵ selectEsc close