{
  "openapi": "3.1.0",
  "info": {
    "title": "Retain API",
    "description": "Retain is a churn prevention and customer analytics platform. Use the API to identify users and track events from your application.",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "https://api.retain.so",
      "description": "Production"
    }
  ],
  "security": [
    {
      "writeKey": []
    }
  ],
  "paths": {
    "/identify": {
      "post": {
        "summary": "Identify a user",
        "description": "Registers or updates a user (customer) in your organization. Call this when a user signs up or when their profile changes. You must identify a user before tracking events for them.",
        "tags": [
          "identify"
        ],
        "operationId": "identify",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/IdentifyBody"
              },
              "example": {
                "userId": "user_123",
                "email": "jane@example.com",
                "properties": {
                  "name": "Jane Doe",
                  "avatar": "https://example.com/avatar.jpg"
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "User identified successfully. Response body: `{ \"success\": true }`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SuccessResponse"
                }
              }
            }
          },
          "400": {
            "description": "**`validation_error`** (HTTP 400) — Message varies; describes which field failed validation and why. Common causes: missing `userId` or `email`, invalid email format, invalid URL in `avatar`, or related payload issues. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ValidationErrorResponse"
                }
              }
            }
          },
          "401": {
            "description": "**`invalid_write_key`** (HTTP 401) — Missing or invalid Project Token. Send `Authorization: Basic rk-…` with a valid token. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvalidWriteKeyErrorResponse"
                }
              }
            }
          },
          "429": {
            "description": "**`rate_limit_exceeded`** (HTTP 429) — Too many requests; slow down or batch traffic. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RateLimitErrorResponse"
                }
              }
            }
          },
          "500": {
            "description": "**`application_error`** (HTTP 500) — Unexpected server error; retry later. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApplicationErrorResponse"
                }
              }
            }
          }
        },
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -X POST https://api.retain.so/identify \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Basic $RETAIN_WRITE_KEY\" \\\n  -d '{\n    \"userId\": \"user_123\",\n    \"email\": \"jane@example.com\",\n    \"properties\": {\n      \"name\": \"Jane Doe\",\n      \"avatar\": \"https://example.com/avatar.jpg\"\n    }\n  }'"
          },
          {
            "lang": "javascript",
            "label": "Node.js",
            "source": "import { Retain } from '@retain-so/sdk';\n\nconst retain = new Retain(process.env.RETAIN_WRITE_KEY);\n\nretain.identify({\n  userId: 'user_123',\n  email: 'jane@example.com',\n  properties: {\n    name: 'Jane Doe',\n    avatar: 'https://example.com/avatar.jpg',\n    // Add anything else about the user here\n  },\n});"
          },
          {
            "lang": "python",
            "label": "Python",
            "source": "import os\nimport requests\n\nrequests.post(\n    'https://api.retain.so/identify',\n    headers={\n        'Content-Type': 'application/json',\n        'Authorization': f'Basic {os.environ[\"RETAIN_WRITE_KEY\"]}',\n    },\n    json={\n        'userId': 'user_123',\n        'email': 'jane@example.com',\n        'properties': {\n            'name': 'Jane Doe',\n            'avatar': 'https://example.com/avatar.jpg',\n        },\n    },\n)"
          },
          {
            "lang": "php",
            "label": "PHP",
            "source": "<?php\n$payload = json_encode([\n    'userId' => 'user_123',\n    'email' => 'jane@example.com',\n    'properties' => [\n        'name' => 'Jane Doe',\n        'avatar' => 'https://example.com/avatar.jpg',\n    ],\n]);\n$ch = curl_init('https://api.retain.so/identify');\ncurl_setopt_array($ch, [\n    CURLOPT_POST => true,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_HTTPHEADER => [\n        'Content-Type: application/json',\n        'Authorization: Basic ' . getenv('RETAIN_WRITE_KEY'),\n    ],\n    CURLOPT_POSTFIELDS => $payload,\n]);\ncurl_exec($ch);\ncurl_close($ch);"
          },
          {
            "lang": "ruby",
            "label": "Ruby",
            "source": "require 'net/http'\nrequire 'json'\n\nuri = URI('https://api.retain.so/identify')\nreq = Net::HTTP::Post.new(uri)\nreq['Content-Type'] = 'application/json'\nreq['Authorization'] = \"Basic #{ENV.fetch('RETAIN_WRITE_KEY')}\"\nreq.body = {\n  userId: 'user_123',\n  email: 'jane@example.com',\n  properties: {\n    name: 'Jane Doe',\n    avatar: 'https://example.com/avatar.jpg',\n  },\n}.to_json\n\nNet::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }"
          },
          {
            "lang": "java",
            "label": "Java",
            "source": "import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\n\nString json = \"\"\"\n  {\n    \"userId\": \"user_123\",\n    \"email\": \"jane@example.com\",\n    \"properties\": {\n      \"name\": \"Jane Doe\",\n      \"avatar\": \"https://example.com/avatar.jpg\"\n    }\n  }\n  \"\"\";\n\nHttpRequest request = HttpRequest.newBuilder()\n    .uri(URI.create(\"https://api.retain.so/identify\"))\n    .header(\"Content-Type\", \"application/json\")\n    .header(\"Authorization\", \"Basic \" + System.getenv(\"RETAIN_WRITE_KEY\"))\n    .POST(HttpRequest.BodyPublishers.ofString(json))\n    .build();\n\nHttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());"
          }
        ]
      }
    },
    "/track": {
      "post": {
        "summary": "Track an event",
        "description": "Records an event for a user. The user must have been identified first using the /identify endpoint. Events are used to calculate engagement, health scores, and churn risk.",
        "tags": [
          "track"
        ],
        "operationId": "track",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TrackBody"
              },
              "example": {
                "userId": "user_123",
                "event": "report_exported",
                "properties": {
                  "format": "csv"
                },
                "timestamp": "2024-01-01T00:00:00Z"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Event tracked successfully. Response body: `{ \"success\": true }`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SuccessResponse"
                }
              }
            }
          },
          "400": {
            "description": "**`validation_error`** (HTTP 400) — Message varies; describes which field failed validation and why. Common causes: missing `userId` or `event`, invalid event name (e.g. spaces), or invalid payload. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TrackValidationErrorResponse"
                }
              }
            }
          },
          "401": {
            "description": "**`invalid_write_key`** (HTTP 401) — Missing or invalid Project Token. Send `Authorization: Basic rk-…` with a valid token. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvalidWriteKeyErrorResponse"
                }
              }
            }
          },
          "404": {
            "description": "**`not_found`** (HTTP 404) — User not found; the `userId` was never identified. Call [POST /identify](/api-reference/identify/identify-a-user) before tracking. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NotFoundErrorResponse"
                }
              }
            }
          },
          "429": {
            "description": "**`rate_limit_exceeded`** (HTTP 429) — Too many requests; slow down or batch traffic. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RateLimitErrorResponse"
                }
              }
            }
          },
          "500": {
            "description": "**`application_error`** (HTTP 500) — Unexpected server error; retry later. See [Error codes](/api-reference/errors#error-codes).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApplicationErrorResponse"
                }
              }
            }
          }
        },
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -X POST https://api.retain.so/track \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Basic $RETAIN_WRITE_KEY\" \\\n  -d '{\n    \"userId\": \"user_123\",\n    \"event\": \"report_exported\",\n    \"properties\": { \"format\": \"csv\" }\n  }'"
          },
          {
            "lang": "javascript",
            "label": "Node.js",
            "source": "import { Retain } from '@retain-so/sdk';\n\nconst retain = new Retain(process.env.RETAIN_WRITE_KEY);\n\nretain.track({\n  userId: 'user_123',\n  event: 'report_exported',\n  properties: { format: 'csv' },\n});"
          },
          {
            "lang": "python",
            "label": "Python",
            "source": "import os\nimport requests\n\nrequests.post(\n    'https://api.retain.so/track',\n    headers={\n        'Content-Type': 'application/json',\n        'Authorization': f'Basic {os.environ[\"RETAIN_WRITE_KEY\"]}',\n    },\n    json={\n        'userId': 'user_123',\n        'event': 'report_exported',\n        'properties': {'format': 'csv'},\n    },\n)"
          },
          {
            "lang": "php",
            "label": "PHP",
            "source": "<?php\n$payload = json_encode([\n    'userId' => 'user_123',\n    'event' => 'report_exported',\n    'properties' => ['format' => 'csv'],\n]);\n$ch = curl_init('https://api.retain.so/track');\ncurl_setopt_array($ch, [\n    CURLOPT_POST => true,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_HTTPHEADER => [\n        'Content-Type: application/json',\n        'Authorization: Basic ' . getenv('RETAIN_WRITE_KEY'),\n    ],\n    CURLOPT_POSTFIELDS => $payload,\n]);\ncurl_exec($ch);\ncurl_close($ch);"
          },
          {
            "lang": "ruby",
            "label": "Ruby",
            "source": "require 'net/http'\nrequire 'json'\n\nuri = URI('https://api.retain.so/track')\nreq = Net::HTTP::Post.new(uri)\nreq['Content-Type'] = 'application/json'\nreq['Authorization'] = \"Basic #{ENV.fetch('RETAIN_WRITE_KEY')}\"\nreq.body = {\n  userId: 'user_123',\n  event: 'report_exported',\n  properties: { format: 'csv' },\n}.to_json\n\nNet::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }"
          },
          {
            "lang": "java",
            "label": "Java",
            "source": "import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\n\nString json = \"\"\"\n  {\n    \"userId\": \"user_123\",\n    \"event\": \"report_exported\",\n    \"properties\": { \"format\": \"csv\" }\n  }\n  \"\"\";\n\nHttpRequest request = HttpRequest.newBuilder()\n    .uri(URI.create(\"https://api.retain.so/track\"))\n    .header(\"Content-Type\", \"application/json\")\n    .header(\"Authorization\", \"Basic \" + System.getenv(\"RETAIN_WRITE_KEY\"))\n    .POST(HttpRequest.BodyPublishers.ofString(json))\n    .build();\n\nHttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());"
          }
        ]
      }
    }
  },
  "components": {
    "schemas": {
      "IdentifyBody": {
        "type": "object",
        "required": [
          "userId",
          "email"
        ],
        "properties": {
          "userId": {
            "type": "string",
            "description": "Unique identifier for the user in your system (string or number)"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "User's email address"
          },
          "properties": {
            "type": "object",
            "additionalProperties": true,
            "description": "Customer traits, shallow-merged into existing ones. Reserved keys power dashboard features; any other key is stored as a custom trait.",
            "properties": {
              "name": {
                "type": "string",
                "description": "User's display name"
              },
              "avatar": {
                "type": "string",
                "format": "uri",
                "description": "URL to the user's avatar image"
              },
              "plan": {
                "type": "string",
                "description": "Pricing plan (e.g. 'starter', 'pro'). Enables retention cohorts by plan"
              },
              "acquisitionChannel": {
                "type": "string",
                "description": "Where the customer came from (e.g. 'organic', 'referral'). Enables retention cohorts by channel"
              },
              "companySize": {
                "type": "string",
                "description": "Company size bucket (e.g. '1-10', '11-50'). Enables retention cohorts by company size"
              },
              "segment": {
                "type": "string",
                "description": "ICP segment of the company (e.g. 'agency', 'creator'). Enables retention cohorts by segment"
              }
            }
          },
          "isAccountOwner": {
            "type": "boolean",
            "description": "Whether this user is the account owner"
          },
          "account": {
            "type": "object",
            "description": "Account/workspace this user belongs to",
            "required": [
              "id",
              "name"
            ],
            "properties": {
              "id": {
                "type": "string",
                "description": "Unique identifier for the account"
              },
              "name": {
                "type": "string",
                "description": "Account display name"
              },
              "avatar": {
                "type": "string",
                "format": "uri",
                "description": "URL to the account avatar image"
              }
            }
          }
        }
      },
      "TrackBody": {
        "type": "object",
        "required": [
          "userId",
          "event"
        ],
        "properties": {
          "userId": {
            "type": "string",
            "description": "User ID (must match the userId used in /identify)"
          },
          "event": {
            "type": "string",
            "description": "Event name (e.g. report_exported, video_watched, meeting_scheduled, post_created, etc)"
          },
          "properties": {
            "type": "object",
            "additionalProperties": true,
            "description": "Optional event metadata"
          },
          "timestamp": {
            "type": "string",
            "format": "date-time",
            "description": "Optional. When to record the event in ISO 8601 format (e.g., 2024-01-01T00:00:00Z or 2024-01-01). Use for backfilling past events. Defaults to now in the organizion timezone when omitted."
          }
        }
      },
      "SuccessResponse": {
        "type": "object",
        "required": [
          "success"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "const": true,
            "description": "Indicates the request was successful"
          }
        },
        "example": {
          "success": true
        }
      },
      "ValidationErrorResponse": {
        "type": "object",
        "required": [
          "message",
          "statusCode",
          "name"
        ],
        "properties": {
          "message": {
            "type": "string",
            "description": "Describes which field failed validation and why (varies per request)."
          },
          "statusCode": {
            "type": "integer",
            "const": 400
          },
          "name": {
            "type": "string",
            "const": "validation_error",
            "description": "Always `validation_error` for HTTP 400."
          }
        },
        "example": {
          "message": "email must be a valid email address",
          "statusCode": 400,
          "name": "validation_error"
        }
      },
      "TrackValidationErrorResponse": {
        "type": "object",
        "required": [
          "message",
          "statusCode",
          "name"
        ],
        "properties": {
          "message": {
            "type": "string",
            "description": "Describes which field failed validation and why (varies per request)."
          },
          "statusCode": {
            "type": "integer",
            "const": 400
          },
          "name": {
            "type": "string",
            "const": "validation_error",
            "description": "Always `validation_error` for HTTP 400."
          }
        },
        "example": {
          "message": "event is required",
          "statusCode": 400,
          "name": "validation_error"
        }
      },
      "InvalidWriteKeyErrorResponse": {
        "type": "object",
        "required": [
          "message",
          "statusCode",
          "name"
        ],
        "properties": {
          "message": {
            "type": "string",
            "description": "Missing or invalid Project Token."
          },
          "statusCode": {
            "type": "integer",
            "const": 401
          },
          "name": {
            "type": "string",
            "const": "invalid_write_key",
            "description": "Always `invalid_write_key` for HTTP 401."
          }
        },
        "example": {
          "message": "Missing or invalid Project Token.",
          "statusCode": 401,
          "name": "invalid_write_key"
        }
      },
      "NotFoundErrorResponse": {
        "type": "object",
        "required": [
          "message",
          "statusCode",
          "name"
        ],
        "properties": {
          "message": {
            "type": "string",
            "description": "User not found; identify the user before tracking."
          },
          "statusCode": {
            "type": "integer",
            "const": 404
          },
          "name": {
            "type": "string",
            "const": "not_found",
            "description": "Always `not_found` for HTTP 404 on /track."
          }
        },
        "example": {
          "message": "User not found, please identify the user first using the /identify endpoint.",
          "statusCode": 404,
          "name": "not_found"
        }
      },
      "RateLimitErrorResponse": {
        "type": "object",
        "required": [
          "message",
          "statusCode",
          "name"
        ],
        "properties": {
          "message": {
            "type": "string",
            "description": "Rate limit exceeded."
          },
          "statusCode": {
            "type": "integer",
            "const": 429
          },
          "name": {
            "type": "string",
            "const": "rate_limit_exceeded",
            "description": "Always `rate_limit_exceeded` for HTTP 429."
          }
        },
        "example": {
          "message": "Too many requests. Please limit the number of requests per second.",
          "statusCode": 429,
          "name": "rate_limit_exceeded"
        }
      },
      "ApplicationErrorResponse": {
        "type": "object",
        "required": [
          "message",
          "statusCode",
          "name"
        ],
        "properties": {
          "message": {
            "type": "string",
            "description": "Unexpected server error."
          },
          "statusCode": {
            "type": "integer",
            "const": 500
          },
          "name": {
            "type": "string",
            "const": "application_error",
            "description": "Always `application_error` for HTTP 500."
          }
        },
        "example": {
          "message": "An unexpected error occurred, please try again later.",
          "statusCode": 500,
          "name": "application_error"
        }
      },
      "ErrorResponse": {
        "description": "Union of all API error bodies. Each HTTP status uses a fixed `name` and `statusCode`; see [Error codes](/api-reference/errors#error-codes).",
        "oneOf": [
          {
            "$ref": "#/components/schemas/ValidationErrorResponse"
          },
          {
            "$ref": "#/components/schemas/InvalidWriteKeyErrorResponse"
          },
          {
            "$ref": "#/components/schemas/NotFoundErrorResponse"
          },
          {
            "$ref": "#/components/schemas/RateLimitErrorResponse"
          },
          {
            "$ref": "#/components/schemas/ApplicationErrorResponse"
          }
        ]
      }
    },
    "securitySchemes": {
      "writeKey": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "Write Key",
        "description": "Your organization's Project Token (starts with rk-). Get it from Settings."
      }
    }
  }
}
