On this pageEn esta página
Start hereEmpieza aquí
Backend, Database & AuthBackend, Database & Auth
- Check the connectionComprueba la conexión
- Sign inInicia sesión
- Save and read documentsGuarda y lee documentos
- Live updatesActualizaciones en vivo
- Create end usersCrea usuarios finales
- Disable and enable usersDeshabilita y habilita usuarios
- Errors and limitsErrores y límites
AI Agents & AutomationAI Agents & Automation
- Check your keyComprueba tu llave
- Send a requestEnvía una solicitud
- ErrorsErrores
- What Doppio runs for youLo que Doppio opera por ti
For your coding agentPara tu agente de código
Getting startedPrimeros pasos
Your welcome email has the data. This page turns it into working calls for the Backend, Database & Auth service and for the AI Agents & Automation service. Pick your language once and every example follows it.
Tu correo de bienvenida trae los datos. Esta página los convierte en llamadas que funcionan, tanto para Backend, Database & Auth como para AI Agents & Automation. Elige tu lenguaje una vez y todos los ejemplos lo siguen.
Your welcome emailTu correo de bienvenida
When your payment is confirmed, Doppio sends you a welcome email with your access data. The Backend email and the AI email are different, and you receive one for each service you hired. Each field below feeds one variable in the examples.
Cuando se confirma tu pago, Doppio te envía un correo de bienvenida con tus datos de acceso. El correo de Backend y el de IA son distintos, y recibes uno por cada servicio que contrataste. Cada campo de abajo alimenta una variable de los ejemplos.
| Field in your emailCampo de tu correo | VariableVariable | What it doesPara qué sirve | Keep itCuidado |
|---|---|---|---|
| Backend, Database & Auth emailCorreo de Backend, Database & Auth | |||
| URL API | DOPPIO_API_URL | Base address of every backend callDirección base de cada llamada al backend | PublicPública |
| Anon key | DOPPIO_ANON_KEY | Identifies your project; goes in the apikey headerIdentifica tu proyecto; va en el header apikey | PublicPública |
| Tenant ID | DOPPIO_TENANT_ID | Your tenant; goes in every row you insertTu tenant; va en cada fila que insertas | PublicPública |
| Llave de tu backend (x-tenant-key) | DOPPIO_TENANT_KEY | Creates and disables end users from your serverCrea y deshabilita usuarios finales desde tu servidor | SecretSecreta |
| URL de alta de usuarios finales | DOPPIO_USERS_URL | Where your server creates and disables end usersDonde tu servidor crea y deshabilita usuarios finales | PublicPública |
| Usuario | DOPPIO_EMAIL | Owner sign-inInicio de sesión del owner | PrivatePrivado |
| Contraseña temporal | DOPPIO_PASSWORD | First sign-in; change it right awayPrimer inicio de sesión; cámbiala enseguida | SecretSecreta |
| AI Agents & Automation emailCorreo de AI Agents & Automation | |||
| URL de la API de IA | DOPPIO_AI_URL | Base address of the AI APIDirección base de la API de IA | PublicPública |
| API key de IA | DOPPIO_AI_KEY | Authorizes every AI requestAutoriza cada solicitud de IA | SecretSecreta |
Set up your environmentPrepara tu entorno
Export the values from your email as environment variables. The examples read them, so you can copy any snippet unchanged. In a .env file, drop the export.
Exporta los valores de tu correo como variables de entorno. Los ejemplos las leen, así que puedes copiar cualquier fragmento sin cambios. En un archivo .env quita el export.
# Backend, Database & Auth (from your Backend welcome email)
export DOPPIO_API_URL="https://supabase.doppio.cloud" # URL API
export DOPPIO_ANON_KEY="eyJ..." # Anon key
export DOPPIO_TENANT_ID="00000000-0000-0000-0000-000000000000" # Tenant ID
export DOPPIO_TENANT_KEY="dpk_..." # Llave de tu backend (x-tenant-key)
export DOPPIO_EMAIL="you@example.com" # Usuario
export DOPPIO_PASSWORD="..." # Contraseña temporal
export DOPPIO_USERS_URL="https://n8n.doppio.cloud/webhook/end-users" # URL de alta de usuarios finales
# AI Agents & Automation (from your AI welcome email)
export DOPPIO_AI_URL="https://ia.doppio.cloud" # URL de la API de IA
export DOPPIO_AI_KEY="sk-..." # API key de IAThen install what your language needs and set up the client. Each snippet in the next sections continues the same file, so paste them one after another.
Luego instala lo que tu lenguaje necesita y prepara el cliente. Cada fragmento de las secciones siguientes continúa el mismo archivo, así que pégalos uno tras otro.
# You only need curl and jq (jq reads the JSON responses).
command -v curl jq >/dev/null || echo "Install curl and jq first"# Node 18 or newer includes fetch. There is nothing to install.
node --versionpip install requests# Cargo.toml
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde_json = "1"# Nothing else to set up: every example reads the variables you exported.// doppio.mjs: run it with node doppio.mjs
const {
DOPPIO_API_URL: API,
DOPPIO_ANON_KEY: ANON,
DOPPIO_TENANT_ID: TENANT,
DOPPIO_TENANT_KEY: TENANT_KEY,
DOPPIO_EMAIL: EMAIL,
DOPPIO_PASSWORD: PASSWORD,
DOPPIO_USERS_URL: USERS_URL,
} = process.env;# doppio.py: run it with python doppio.py
import os
import requests
API = os.environ["DOPPIO_API_URL"]
ANON = os.environ["DOPPIO_ANON_KEY"]
TENANT_KEY = os.environ["DOPPIO_TENANT_KEY"]
USERS_URL = os.environ["DOPPIO_USERS_URL"]// src/main.rs
use serde_json::{json, Value};
use std::{env, error::Error};
fn var(name: &str) -> String {
env::var(name).unwrap_or_else(|_| panic!("missing {name}"))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let api = var("DOPPIO_API_URL");
let anon = var("DOPPIO_ANON_KEY");
let tenant_key = var("DOPPIO_TENANT_KEY");
let users_url = var("DOPPIO_USERS_URL");
let http = reqwest::Client::new();
// paste the next snippets here, one after another
Ok(())
}Backend, Database & Auth
Your data lives in a managed PostgreSQL database that Doppio shares across customers and isolates with Row Level Security: every request carries a user token tied to your tenant, and the database returns only your rows. You don't need to create tables to get started: save JSON documents in collections and the records table does the rest. If you need real tables or storage buckets, write to hello@doppio.cloud.
Tus datos viven en una base PostgreSQL administrada que Doppio comparte entre clientes y aísla con Row Level Security: cada petición lleva un token de usuario ligado a tu tenant, y la base devuelve solo tus filas. No necesitas crear tablas para empezar: guarda documentos JSON en colecciones y la tabla records hace el resto. Si necesitas tablas reales o buckets de almacenamiento, escribe a hello@doppio.cloud.
1Check the connectionComprueba la conexión
A call to the Auth health endpoint confirms that the URL and the Anon key are right. Expect a 200.
Una llamada al endpoint de salud de Auth confirma que la URL y la Anon key son correctas. Debes recibir un 200.
curl -s "$DOPPIO_API_URL/auth/v1/health" -H "apikey: $DOPPIO_ANON_KEY"const health = await fetch(`${API}/auth/v1/health`, { headers: { apikey: ANON } });
console.log(health.status, await health.json());health = requests.get(f"{API}/auth/v1/health", headers={"apikey": ANON})
print(health.status_code, health.json())let health = http
.get(format!("{api}/auth/v1/health"))
.header("apikey", &anon)
.send()
.await?;
let status = health.status();
println!("{status} {}", health.text().await?);HTTP 200
{ "name": "GoTrue", "description": "GoTrue is a user registration and authentication API", ... }2Sign inInicia sesión
Sign in as the owner with the user and temporary password from your email. The response includes an access_token. It is short-lived (see expires_in): send it as Authorization: Bearer on the next calls, and refresh it with grant_type=refresh_token when it expires.
Inicia sesión como owner con el usuario y la contraseña temporal de tu correo. La respuesta incluye un access_token, de vida corta (mira expires_in): envíalo como Authorization: Bearer en las siguientes llamadas y renuévalo con grant_type=refresh_token cuando venza.
TOKEN=$(curl -s -X POST "$DOPPIO_API_URL/auth/v1/token?grant_type=password" \
-H "apikey: $DOPPIO_ANON_KEY" -H "Content-Type: application/json" \
-d "{\"email\":\"$DOPPIO_EMAIL\",\"password\":\"$DOPPIO_PASSWORD\"}" \
| jq -r .access_token)
echo "${TOKEN:0:24}..."const login = await fetch(`${API}/auth/v1/token?grant_type=password`, {
method: "POST",
headers: { apikey: ANON, "Content-Type": "application/json" },
body: JSON.stringify({ email: EMAIL, password: PASSWORD }),
});
const { access_token: token } = await login.json();login = requests.post(
f"{API}/auth/v1/token",
params={"grant_type": "password"},
headers={"apikey": ANON},
json={"email": os.environ["DOPPIO_EMAIL"], "password": os.environ["DOPPIO_PASSWORD"]},
)
token = login.json()["access_token"]
auth = {"apikey": ANON, "Authorization": f"Bearer {token}"}let login: Value = http
.post(format!("{api}/auth/v1/token?grant_type=password"))
.header("apikey", &anon)
.json(&json!({ "email": var("DOPPIO_EMAIL"), "password": var("DOPPIO_PASSWORD") }))
.send()
.await?
.json()
.await?;
let token = login["access_token"].as_str().ok_or("sign-in failed")?.to_string();{
"access_token": "eyJhbGciOi...",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "...",
"user": { "id": "...", "email": "you@example.com", ... }
}Change the temporary passwordCambia la contraseña temporal
curl -s -X PUT "$DOPPIO_API_URL/auth/v1/user" \
-H "apikey: $DOPPIO_ANON_KEY" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"password":"a-new-long-passphrase"}'await fetch(`${API}/auth/v1/user`, {
method: "PUT",
headers: {
apikey: ANON,
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ password: "a-new-long-passphrase" }),
});requests.put(
f"{API}/auth/v1/user", headers=auth, json={"password": "a-new-long-passphrase"}
)http.put(format!("{api}/auth/v1/user"))
.header("apikey", &anon)
.bearer_auth(&token)
.json(&json!({ "password": "a-new-long-passphrase" }))
.send()
.await?;Your end users sign in with this same call from your app, using only the Anon key.
Tus usuarios finales inician sesión con esta misma llamada desde tu app, usando solo la Anon key.
3Save and read documentsGuarda y lee documentos
A document is a JSON object that belongs to a collection (clientes, pedidos, whatever you need). The collection exists as soon as you save its first document. Row Level Security limits every call to your tenant: you can't read another customer's documents or save documents for another tenant, and tenant_id is filled in for you.
Un documento es un objeto JSON que pertenece a una colección (clientes, pedidos, lo que necesites). La colección existe desde que guardas su primer documento. Row Level Security limita cada llamada a tu tenant: no puedes leer documentos de otro cliente ni guardarlos en otro tenant, y el tenant_id se completa solo.
Create a documentCrea un documento
ID=$(curl -s -X POST "$DOPPIO_API_URL/rest/v1/records" \
-H "apikey: $DOPPIO_ANON_KEY" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -H "Prefer: return=representation" \
-d '{"collection":"clientes","data":{"nombre":"Ana","email":"ana@example.com"}}' \
| jq -r '.[0].id')
echo "$ID"const [doc] = await fetch(`${API}/rest/v1/records`, {
method: "POST",
headers: {
apikey: ANON,
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Prefer: "return=representation",
},
body: JSON.stringify({ collection: "clientes", data: { nombre: "Ana", email: "ana@example.com" } }),
}).then((r) => r.json());
console.log(doc);doc = requests.post(
f"{API}/rest/v1/records",
headers={**auth, "Prefer": "return=representation"},
json={"collection": "clientes", "data": {"nombre": "Ana", "email": "ana@example.com"}},
).json()[0]
print(doc)let created: Value = http
.post(format!("{api}/rest/v1/records"))
.header("apikey", &anon)
.bearer_auth(&token)
.header("Prefer", "return=representation")
.json(&json!({ "collection": "clientes", "data": { "nombre": "Ana", "email": "ana@example.com" } }))
.send()
.await?
.json()
.await?;
let doc_id = created[0]["id"].as_str().ok_or("no id")?.to_string();
println!("{created}");HTTP 201
[
{
"id": "6f1c0c1e-...",
"tenant_id": "00000000-0000-0000-0000-000000000000",
"collection": "clientes",
"data": { "nombre": "Ana", "email": "ana@example.com" },
"created_at": "2026-10-29T12:00:00Z",
"updated_at": "2026-10-29T12:00:00Z"
}
]Read and filterLee y filtra
Filter by collection and by any field inside data with data->>field=eq.value. The other operators work the same way: gt, lt, like, ilike and in.
Filtra por colección y por cualquier campo dentro de data con data->>campo=eq.valor. Los demás operadores funcionan igual: gt, lt, like, ilike e in.
curl -s -G "$DOPPIO_API_URL/rest/v1/records" \
--data-urlencode "collection=eq.clientes" \
--data-urlencode "data->>nombre=eq.Ana" \
--data-urlencode "select=id,data,created_at" \
--data-urlencode "order=created_at.desc" \
--data-urlencode "limit=10" \
-H "apikey: $DOPPIO_ANON_KEY" -H "Authorization: Bearer $TOKEN"const params = new URLSearchParams({
collection: "eq.clientes",
"data->>nombre": "eq.Ana",
select: "id,data,created_at",
order: "created_at.desc",
limit: "10",
});
const docs = await fetch(`${API}/rest/v1/records?${params}`, {
headers: { apikey: ANON, Authorization: `Bearer ${token}` },
}).then((r) => r.json());
console.log(docs);docs = requests.get(
f"{API}/rest/v1/records",
headers=auth,
params={
"collection": "eq.clientes",
"data->>nombre": "eq.Ana",
"select": "id,data,created_at",
"order": "created_at.desc",
"limit": 10,
},
).json()
print(docs)let docs: Value = http
.get(format!("{api}/rest/v1/records"))
.header("apikey", &anon)
.bearer_auth(&token)
.query(&[
("collection", "eq.clientes"),
("data->>nombre", "eq.Ana"),
("select", "id,data,created_at"),
("order", "created_at.desc"),
("limit", "10"),
])
.send()
.await?
.json()
.await?;
println!("{docs}");[
{
"id": "6f1c0c1e-...",
"data": { "nombre": "Ana", "email": "ana@example.com" },
"created_at": "2026-10-29T12:00:00Z"
}
]Update and deleteActualiza y borra
Updating a document replaces its whole data object, so send every field you want to keep.
Actualizar un documento reemplaza todo su objeto data, así que envía todos los campos que quieras conservar.
curl -s -X PATCH "$DOPPIO_API_URL/rest/v1/records?id=eq.$ID" \
-H "apikey: $DOPPIO_ANON_KEY" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -H "Prefer: return=representation" \
-d '{"data":{"nombre":"Ana B","email":"ana@example.com"}}'const updated = await fetch(`${API}/rest/v1/records?id=eq.${doc.id}`, {
method: "PATCH",
headers: {
apikey: ANON,
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Prefer: "return=representation",
},
body: JSON.stringify({ data: { nombre: "Ana B", email: "ana@example.com" } }),
}).then((r) => r.json());
console.log(updated);updated = requests.patch(
f"{API}/rest/v1/records",
headers={**auth, "Prefer": "return=representation"},
params={"id": f"eq.{doc['id']}"},
json={"data": {"nombre": "Ana B", "email": "ana@example.com"}},
).json()
print(updated)let updated: Value = http
.patch(format!("{api}/rest/v1/records?id=eq.{doc_id}"))
.header("apikey", &anon)
.bearer_auth(&token)
.header("Prefer", "return=representation")
.json(&json!({ "data": { "nombre": "Ana B", "email": "ana@example.com" } }))
.send()
.await?
.json()
.await?;
println!("{updated}");curl -s -X DELETE "$DOPPIO_API_URL/rest/v1/records?id=eq.$ID" \
-H "apikey: $DOPPIO_ANON_KEY" -H "Authorization: Bearer $TOKEN"await fetch(`${API}/rest/v1/records?id=eq.${doc.id}`, {
method: "DELETE",
headers: { apikey: ANON, Authorization: `Bearer ${token}` },
});requests.delete(f"{API}/rest/v1/records", headers=auth, params={"id": f"eq.{doc['id']}"})http.delete(format!("{api}/rest/v1/records?id=eq.{doc_id}"))
.header("apikey", &anon)
.bearer_auth(&token)
.send()
.await?;Your plan's limitsLos límites de tu plan
Each plan sets how much you can store: 500 MB of data and 1 GB of files on Starter, 5 GB of data and 20 GB of files on Growth, plus the number of end users (step 5). my_usage shows how much you have used. When you reach the data limit, saving a document returns 402; reading and deleting keep working, so you can free space.
Cada plan define cuánto puedes guardar: 500 MB de datos y 1 GB de archivos en Starter, 5 GB de datos y 20 GB de archivos en Growth, además de los usuarios finales (paso 5). my_usage muestra cuánto llevas usado. Al llegar al límite de datos, guardar un documento devuelve 402; leer y borrar siguen funcionando, así que puedes liberar espacio.
curl -s "$DOPPIO_API_URL/rest/v1/rpc/my_usage" \
-H "apikey: $DOPPIO_ANON_KEY" -H "Authorization: Bearer $TOKEN"const usage = await fetch(`${API}/rest/v1/rpc/my_usage`, {
headers: { apikey: ANON, Authorization: `Bearer ${token}` },
}).then((r) => r.json());
console.log(usage);usage = requests.get(f"{API}/rest/v1/rpc/my_usage", headers=auth).json()
print(usage)let usage: Value = http
.get(format!("{api}/rest/v1/rpc/my_usage"))
.header("apikey", &anon)
.bearer_auth(&token)
.send()
.await?
.json()
.await?;
println!("{usage}");{
"plan": "starter",
"end_users": { "used": 12, "limit": 1000 },
"data_bytes": { "used": 3145728, "limit": 524288000 }
}4Live updatesActualizaciones en vivo
Your app can hear every change to your documents as it happens. Subscribe to your tenant's private channel, tenant:<your Tenant ID>:records, with the session you signed in with. You receive INSERT, UPDATE and DELETE events, only for your own documents. Realtime uses WebSockets, so the example uses the official JavaScript client.
Tu app puede enterarse de cada cambio en tus documentos al instante. Suscríbete al canal privado de tu tenant, tenant:<tu Tenant ID>:records, con la sesión con la que iniciaste sesión. Recibes los eventos INSERT, UPDATE y DELETE, solo de tus propios documentos. Realtime usa WebSockets, así que el ejemplo usa el cliente oficial de JavaScript.
# Realtime uses WebSockets, so there is no cURL example.
# See the JavaScript tab for the topic and the events.// npm install @supabase/supabase-js
import { createClient } from "@supabase/supabase-js";
const supabase = createClient(API, ANON);
await supabase.auth.signInWithPassword({ email: EMAIL, password: PASSWORD });
await supabase.realtime.setAuth(); // the private channel uses the session token
supabase
.channel(`tenant:${TENANT}:records`, { config: { private: true } })
.on("broadcast", { event: "INSERT" }, (msg) => console.log("new", msg.payload))
.on("broadcast", { event: "UPDATE" }, (msg) => console.log("changed", msg.payload))
.on("broadcast", { event: "DELETE" }, (msg) => console.log("deleted", msg.payload))
.subscribe((status) => console.log("status:", status));# Realtime uses WebSockets: use an official Supabase client library with a private channel.
# The topic and the events are the ones shown in the JavaScript tab.// Realtime uses WebSockets and there is no official Supabase client for Rust.
// The topic and the events are the ones shown in the JavaScript tab.5Create end usersCrea usuarios finales
End users are the people who sign in to your app. Create them from your server with the backend key, never from a browser. The user can then sign in with the call from step 2, using only the Anon key.
Los usuarios finales son las personas que inician sesión en tu app. Créalos desde tu servidor con la llave del backend, nunca desde un navegador. Después, el usuario puede iniciar sesión con la llamada del paso 2, usando solo la Anon key.
curl -s -X POST "$DOPPIO_USERS_URL" \
-H "x-tenant-key: $DOPPIO_TENANT_KEY" -H "Content-Type: application/json" \
-d '{"action":"create","email":"ana@example.com","password":"a-long-passphrase"}'async function usersApi(body) {
const res = await fetch(USERS_URL, {
method: "POST",
headers: { "x-tenant-key": TENANT_KEY, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return { status: res.status, body: await res.json().catch(() => ({})) };
}
const newUser = await usersApi({
action: "create",
email: "ana@example.com",
password: "a-long-passphrase",
});
console.log(newUser.status, newUser.body);def users_api(body):
r = requests.post(
USERS_URL, headers={"x-tenant-key": TENANT_KEY}, json=body, timeout=15
)
try:
data = r.json()
except ValueError:
data = {}
return r.status_code, data
status, new_user = users_api(
{"action": "create", "email": "ana@example.com", "password": "a-long-passphrase"}
)
print(status, new_user)let res = http
.post(&users_url)
.header("x-tenant-key", &tenant_key)
.json(&json!({
"action": "create",
"email": "ana@example.com",
"password": "a-long-passphrase"
}))
.send()
.await?;
let status = res.status();
let new_user: Value = res.json().await.unwrap_or(Value::Null);
println!("{status} {new_user}");HTTP 201
{ "user_id": "6f1c0c1e-...", "email": "ana@example.com" }Your plan sets how many end users you can have: 1,000 on Starter, 10,000 on Growth. The endpoint accepts up to 5 requests per second from one IP, with bursts of up to 10. Above that it answers 429, so wait a moment and retry.
Tu plan define cuántos usuarios finales puedes tener: 1,000 en Starter, 10,000 en Growth. El endpoint acepta hasta 5 peticiones por segundo desde una misma IP, con ráfagas de hasta 10. Por encima de eso responde 429, así que espera un momento y reintenta.
6Disable and enable usersDeshabilita y habilita usuarios
Pass the user_id from the create call, with action set to disable or enable. A disabled user can't sign in or refresh a session; a token that was already issued keeps working until it expires.
Envía el user_id que devolvió la creación, con action en disable o enable. Un usuario deshabilitado no puede iniciar sesión ni renovar una sesión; un token que ya se emitió sigue funcionando hasta que venza.
curl -s -X POST "$DOPPIO_USERS_URL" \
-H "x-tenant-key: $DOPPIO_TENANT_KEY" -H "Content-Type: application/json" \
-d '{"action":"disable","user_id":"THE-USER-ID-FROM-THE-PREVIOUS-CALL"}'const off = await usersApi({ action: "disable", user_id: newUser.body.user_id });
console.log(off.status, off.body); // use action: "enable" to turn the user back onstatus, off = users_api({"action": "disable", "user_id": new_user["user_id"]})
print(status, off) # use "enable" to turn the user back onlet user_id = new_user["user_id"].as_str().ok_or("no user_id")?;
let off = http
.post(&users_url)
.header("x-tenant-key", &tenant_key)
.json(&json!({ "action": "disable", "user_id": user_id }))
.send()
.await?;
println!("{}", off.status()); // use "enable" to turn the user back onHTTP 200
{ "user_id": "6f1c0c1e-...", "status": "disabled" }Errors and limitsErrores y límites
Creating and disabling end usersCrear y deshabilitar usuarios finales
| StatusEstado | MeaningSignificado | What to doQué hacer |
|---|---|---|
200 | disable or enable appliedSe aplicó disable o enable | NothingNada |
201 | User createdUsuario creado | Store the user_idGuarda el user_id |
400 | Invalid request; error says why (action, email, password of at least 8 characters, user_id)Petición inválida; error dice por qué (action, email, password de al menos 8 caracteres, user_id) | Fix the inputCorrige los datos |
401 | Wrong or missing x-tenant-key, or your service is suspendedx-tenant-key incorrecta o ausente, o tu servicio está suspendido | Check the key, then contact DoppioRevisa la llave y luego contacta a Doppio |
403 | End-user limit reached; the body has used and maxLímite de usuarios finales alcanzado; el cuerpo trae used y max | Free a slot or change planLibera un cupo o cambia de plan |
404 | The user_id isn't an end user of your tenantEl user_id no es un usuario final de tu tenant | Check the idRevisa el id |
409 | The email is already in use. Emails are unique across all Doppio customersEl correo ya está en uso. Los correos son únicos entre todos los clientes de Doppio | Ask for another emailPide otro correo |
429 | More than 5 requests per second from one IPMás de 5 peticiones por segundo desde una misma IP | Wait and retryEspera y reintenta |
502 | The user couldn't be created or updatedNo se pudo crear o actualizar el usuario | Retry later, then contact DoppioReintenta más tarde y luego contacta a Doppio |
Documents and sign-inDocumentos e inicio de sesión
| SymptomSíntoma | MeaningSignificado | What to doQué hacer |
|---|---|---|
401 with an expired-token message | The access token expiredEl access token venció | Refresh it or sign in againRenuévalo o inicia sesión de nuevo |
401 mentioning the API key | The apikey header is missing or wrongEl header apikey falta o es incorrecto | Send your Anon keyEnvía tu Anon key |
400 when saving | The collection name is invalid, or data isn't a JSON object, or it is over 256 KBEl nombre de la colección es inválido, o data no es un objeto JSON, o pesa más de 256 KB | Fix the inputCorrige los datos |
402 when saving | The data limit of your plan was reachedSe alcanzó el límite de datos de tu plan | Delete data you no longer need, or ask about a higher planBorra datos que ya no necesites o consulta por un plan superior |
403 when saving | Row-level security rejected the write: the documents feature isn't active for your project, or your service is suspendedRow-level security rechazó la escritura: la función de documentos no está activa en tu proyecto, o tu servicio está suspendido | Write to DoppioEscribe a Doppio |
200 with an empty list | No documents for your tenant, a token from another tenant, or a suspended serviceNo hay documentos para tu tenant, un token de otro tenant, o un servicio suspendido | Check the token and the collectionRevisa el token y la colección |
AI Agents & Automation
Your AI key works with any OpenAI-compatible client. Doppio builds and runs your agents and automation flows; this API is for calling the models from your own code. The examples are self-contained and only need DOPPIO_AI_URL and DOPPIO_AI_KEY.
Tu API key de IA funciona con cualquier cliente compatible con OpenAI. Doppio construye y opera tus agentes y flujos de automatización; esta API sirve para llamar a los modelos desde tu propio código. Los ejemplos son independientes y solo necesitan DOPPIO_AI_URL y DOPPIO_AI_KEY.
1Check your keyComprueba tu llave
List the models your key can use, and pick one from that list for your requests. Today it includes chat, Doppio’s general-purpose model. The name chat stays the same even if Doppio changes the model behind it; the list is always the source of truth.
Lista los modelos que tu llave puede usar y elige uno de esa lista para tus solicitudes. Hoy incluye chat, el modelo de uso general de Doppio. El nombre chat se mantiene aunque Doppio cambie el modelo que hay detrás; la lista siempre es la fuente de verdad.
curl -s "$DOPPIO_AI_URL/v1/models" -H "Authorization: Bearer $DOPPIO_AI_KEY"// npm install openai (any OpenAI-compatible SDK works)
import OpenAI from "openai";
const ai = new OpenAI({
baseURL: `${process.env.DOPPIO_AI_URL}/v1`,
apiKey: process.env.DOPPIO_AI_KEY,
});
const models = await ai.models.list();
console.log(models.data.map((m) => m.id));# pip install openai (any OpenAI-compatible SDK works)
import os
from openai import OpenAI
ai = OpenAI(
base_url=f"{os.environ['DOPPIO_AI_URL']}/v1",
api_key=os.environ["DOPPIO_AI_KEY"],
)
print([m.id for m in ai.models.list().data])// src/main.rs (same Cargo.toml as above)
use serde_json::{json, Value};
use std::{env, error::Error};
fn var(name: &str) -> String {
env::var(name).unwrap_or_else(|_| panic!("missing {name}"))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let ai = var("DOPPIO_AI_URL");
let key = var("DOPPIO_AI_KEY");
let http = reqwest::Client::new();
let models: Value = http
.get(format!("{ai}/v1/models"))
.bearer_auth(&key)
.send()
.await?
.json()
.await?;
println!("{models}");
// paste the next snippet here
Ok(())
}{
"object": "list",
"data": [ { "id": "chat", "object": "model", ... } ]
}2Send a requestEnvía una solicitud
A chat completion works as in any OpenAI-compatible API. With an SDK, set the base URL to your AI URL plus /v1. The JavaScript and Python snippets continue the file from the previous step; the Rust one goes inside main.
Una solicitud de chat funciona como en cualquier API compatible con OpenAI. Con un SDK, usa como URL base tu URL de IA más /v1. Los fragmentos de JavaScript y Python continúan el archivo del paso anterior; el de Rust va dentro de main.
curl -s "$DOPPIO_AI_URL/v1/chat/completions" \
-H "Authorization: Bearer $DOPPIO_AI_KEY" -H "Content-Type: application/json" \
-d '{"model":"chat","messages":[
{"role":"user","content":"Say hello in one sentence."}]}'const chat = await ai.chat.completions.create({
model: "chat",
messages: [{ role: "user", content: "Say hello in one sentence." }],
});
console.log(chat.choices[0].message.content);chat = ai.chat.completions.create(
model="chat",
messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(chat.choices[0].message.content)let chat: Value = http
.post(format!("{ai}/v1/chat/completions"))
.bearer_auth(&key)
.json(&json!({
"model": "chat",
"messages": [{ "role": "user", "content": "Say hello in one sentence." }]
}))
.send()
.await?
.json()
.await?;
println!("{}", chat["choices"][0]["message"]["content"].as_str().unwrap_or_default());{
"choices": [
{ "message": { "role": "assistant", "content": "Hello! ..." }, "finish_reason": "stop" }
],
"usage": { "prompt_tokens": 12, "completion_tokens": 9, "total_tokens": 21 }
}ErrorsErrores
| StatusEstado | MeaningSignificado | What to doQué hacer |
|---|---|---|
401 | The key is invalid, or blocked (Key is blocked means your service is suspended)La llave es inválida o está bloqueada (Key is blocked significa que tu servicio está suspendido) | Check the key, then contact DoppioRevisa la llave y luego contacta a Doppio |
400 | The model isn't available for your key, or your usage allowance is used upEl modelo no está disponible para tu llave, o se agotó tu cupo de uso | Check the model listRevisa la lista de modelos |
429 / 5xx | Temporary problemProblema temporal | Retry with a growing waitReintenta con una espera creciente |
Your key has a usage allowance for each 30-day period. If you reach it, or need more, write to hello@doppio.cloud.
Tu llave tiene un cupo de uso por cada periodo de 30 días. Si lo alcanzas, o necesitas más, escribe a hello@doppio.cloud.
What Doppio runs for youLo que Doppio opera por ti
Your agents and automation flows (WhatsApp and web chat, CRM) are built and operated by Doppio, and so is your knowledge base: your documents are indexed so the agent can answer from them. You don't install or sign in to anything for that. To start, answer your welcome email with what you want to automate and the documents you want the agent to know.
Tus agentes y flujos de automatización (WhatsApp y chat web, CRM) los construye y opera Doppio, y también tu base de conocimiento: tus documentos se indexan para que el agente responda a partir de ellos. No instalas ni inicias sesión en nada para eso. Para empezar, responde tu correo de bienvenida con lo que quieres automatizar y los documentos que quieres que el agente conozca.
A skill file for your coding agentUn archivo de skills para tu agente de código
If you build with a coding agent in a spec-driven workflow, give it this file. It describes both services, the credentials, the calls on this page, the limits and the rules an agent should follow, so the specs and code it writes match how the services really behave.
Si construyes con un agente de código en un flujo guiado por especificaciones, dale este archivo. Describe ambos servicios, las credenciales, las llamadas de esta página, los límites y las reglas que un agente debe seguir, para que las especificaciones y el código que escriba coincidan con cómo se comportan realmente los servicios.
Where to put itDónde ponerlo
- Claude Code:
.claude/skills/doppio-cloud/SKILL.md - Claude Code:
.claude/skills/doppio-cloud/SKILL.md - Other agents: save it as
docs/doppio-cloud.mdand mention it from yourAGENTS.mdor project instructions. - Otros agentes: guárdalo como
docs/doppio-cloud.mdy menciónalo en tuAGENTS.mdo en las instrucciones del proyecto. - Spec-driven tools such as OpenSpec: reference it from your project context file, so every proposal reads the Doppio constraints.
- Herramientas guiadas por especificaciones, como OpenSpec: referéncialo desde tu archivo de contexto del proyecto, para que cada propuesta lea las restricciones de Doppio.
Preview SKILL.mdVer SKILL.md
---
name: doppio-cloud
description: Integrate an application with Doppio Cloud, a managed multi-tenant backend (PostgreSQL REST API, authentication, end-user provisioning) and an OpenAI-compatible AI API. Use when writing specs, code or tests that call the Doppio API URL, the end-user provisioning endpoint or the Doppio AI endpoint, or when a task mentions Doppio, DOPPIO_* variables, tenant keys or end users.
---
# Doppio Cloud integration
Doppio Cloud sells two services. A customer can have one or both, and each one is consumed over HTTPS with the values in the customer's welcome email. Reply to the user in the language they write in.
## Credentials
Read every value from the environment. Never hard-code, log or commit one, and never ship a secret to a browser or a mobile app.
| Variable | Welcome email field | Secret | Used for |
|---|---|---|---|
| `DOPPIO_API_URL` | URL API | no | Base URL of the backend (`/auth/v1`, `/rest/v1`) |
| `DOPPIO_ANON_KEY` | Anon key | no (public) | `apikey` header on every backend call |
| `DOPPIO_TENANT_ID` | Tenant ID | no | `tenant_id` value on every insert |
| `DOPPIO_TENANT_KEY` | Llave de tu backend (x-tenant-key) | **yes** | Creating and disabling end users, from the server only |
| `DOPPIO_EMAIL`, `DOPPIO_PASSWORD` | Usuario, Contraseña temporal | **yes** | First sign-in as the owner; change the password afterwards |
| `DOPPIO_USERS_URL` | URL de alta de usuarios finales | no | Provisioning endpoint for end users (`https://n8n.doppio.cloud/webhook/end-users`) |
| `DOPPIO_AI_URL` | URL de la API de IA | no | Base URL of the AI API |
| `DOPPIO_AI_KEY` | API key de IA | **yes** | Bearer token for the AI API |
The Anon key is the only value that may appear in client-side code. Row Level Security limits what it can reach.
## Service 1: Backend, Database & Auth
The data lives in a PostgreSQL database shared with other Doppio customers and isolated by Row Level Security. Every user token carries the tenant, and the database returns only that tenant's rows. Customers never receive a service-role key and cannot run DDL. They store data as **JSON documents in collections** without any setup (see below). **Real tables and storage buckets are set up by Doppio** (hello@doppio.cloud). Do not invent tables, columns or endpoints. If a table's schema is unknown, ask the user for it, and prefer collections when the data is simple.
**Sign in** (owner or end user):
```
POST {DOPPIO_API_URL}/auth/v1/token?grant_type=password
apikey: {DOPPIO_ANON_KEY}
{"email": "...", "password": "..."}
-> {"access_token": "...", "refresh_token": "...", "expires_in": ...}
```
Refresh with `grant_type=refresh_token` and `{"refresh_token": "..."}`. Change a password with `PUT /auth/v1/user` and `{"password": "..."}`.
**Documents** are the default way to store data. A document is a JSON object in a named collection, saved in the `records` table. The collection exists as soon as its first document is saved. Every call sends `apikey: {DOPPIO_ANON_KEY}` and `Authorization: Bearer {access_token}`:
```
POST {DOPPIO_API_URL}/rest/v1/records {"collection": "clientes", "data": {"nombre": "Ana"}}
header Prefer: return=representation
GET {DOPPIO_API_URL}/rest/v1/records?collection=eq.clientes&data->>nombre=eq.Ana
&select=id,data,created_at&order=created_at.desc&limit=10
PATCH {DOPPIO_API_URL}/rest/v1/records?id=eq.{id} {"data": {...}} replaces the whole data object
DELETE {DOPPIO_API_URL}/rest/v1/records?id=eq.{id}
```
Rules: a collection name matches `^[a-z][a-z0-9_]{1,39}$`; `data` is a JSON object of at most 256 KB. Do not send `tenant_id`: it is filled in automatically, and one that belongs to another tenant is rejected. Filter operators are PostgREST's (`eq`, `gt`, `lt`, `like`, `ilike`, `in`). There are no joins or foreign keys between documents: keep relations in the application, or ask Doppio for real tables.
Tables that Doppio creates for a customer are used the same way through `{DOPPIO_API_URL}/rest/v1/{table}`.
Plan limits on stored data: 500 MB on Starter and 5 GB on Growth (files: 1 GB and 20 GB, set up by Doppio). `GET {DOPPIO_API_URL}/rest/v1/rpc/my_usage` (same headers) returns `{"plan", "end_users": {"used", "limit"}, "data_bytes": {"used", "limit"}}`. At the data limit, writes return `402`; reads and deletes still work. Handle `402` by telling the user to free space or upgrade, never by retrying.
Status codes when saving: `400` invalid collection name or `data`; `402` data limit of the plan reached; `403` row-level security rejected the write (the documents feature is not active for the project, or the service is suspended). A read that returns an empty list can mean a wrong tenant or a suspended service, not only missing data. A `401` with an expired-token message means sign in again or refresh.
**Live updates** (WebSockets, Supabase Realtime). Each tenant has a private channel with the topic `tenant:{DOPPIO_TENANT_ID}:records` that broadcasts `INSERT`, `UPDATE` and `DELETE` events for its documents. With `supabase-js`: sign in, call `await supabase.realtime.setAuth()`, then `supabase.channel(topic, { config: { private: true } }).on("broadcast", { event: "INSERT" }, handler).subscribe()`. A private channel is required: a public one receives nothing. There is no official Rust client; for other languages use an official Supabase library.
**End users** (the people who sign in to the customer's app) are provisioned from server code only:
```
POST {DOPPIO_USERS_URL}
x-tenant-key: {DOPPIO_TENANT_KEY}
{"action": "create", "email": "...", "password": "..."} password has at least 8 characters
{"action": "disable", "user_id": "..."} also "enable"
```
| Status | Meaning | What the app should do |
|---|---|---|
| 201 | User created: `{user_id, email}` | Store `user_id` |
| 200 | `disable` or `enable` applied: `{user_id, status}` | |
| 400 | Invalid request, `error` says why | Fix the input |
| 401 | Invalid `x-tenant-key`, or the service is suspended | Stop and alert the owner |
| 403 | End-user limit reached: `{error, used, max}` | Show "plan limit reached" |
| 404 | `user_id` is not an end user of this tenant | Treat as not found |
| 409 | Email already in use. Emails are unique across all Doppio customers | Ask for another email |
| 429 | Over 5 requests per second per IP (burst 10) | Retry with a growing wait |
| 502 | The user could not be created or updated | Retry later, then contact Doppio |
Limits: 1,000 end users on Starter, 10,000 on Growth. A disabled user cannot sign in or refresh, but a token that was already issued works until it expires, so do not rely on `disable` for instant revocation.
## Service 2: AI Agents & Automation
The AI API is OpenAI-compatible.
```
GET {DOPPIO_AI_URL}/v1/models Authorization: Bearer {DOPPIO_AI_KEY}
POST {DOPPIO_AI_URL}/v1/chat/completions {"model": "...", "messages": [...]}
```
With an OpenAI SDK, set `base_url` to `{DOPPIO_AI_URL}/v1` and `api_key` to `DOPPIO_AI_KEY`. List the models instead of hard-coding one: the list is the source of truth for what the key can use. Errors: `401` means an invalid key or a blocked key (the service is suspended), `400` can mean a model the key cannot use or that the usage allowance for the 30-day period is used up, and `429` or `5xx` deserve a retry with a growing wait.
Doppio builds and operates the customer's agents and automation flows (WhatsApp and web chat, CRM) on its own n8n, and also operates the customer's knowledge base (their documents are indexed so the agent answers from them). Customers have no n8n access and no API for the knowledge base, so never write code or specs that assume either.
## Rules
1. Secrets stay on the server. Only the Anon key can reach a browser.
2. Do not invent tables, columns, buckets, endpoints or models. Use collections (`records`) for simple data before asking for tables.
3. Provision and disable end users only from server code, and map every status in the table above to a behavior.
4. Retry `429` with exponential backoff and a cap. Do not retry `400`, `401`, `402`, `403` or `409`.
5. Do not run tests against real keys. Mock the Doppio endpoints.
6. Never print a key or a password in logs, errors or commit messages.
## Writing specs (spec-driven development)
For each requirement that touches Doppio, state which service it uses, which credential it needs and whether that credential lives on the server or in the browser. Add scenarios for the failure paths, not only the happy path:
- WHEN the server creates an end user AND the plan limit is reached THEN the API answers 403 and the UI shows "user limit reached".
- WHEN the provisioning endpoint answers 429 THEN the server retries up to three times with a growing wait and then reports a temporary failure.
- WHEN an end user's email is already in use THEN the UI asks for another email without saying who owns it.
- WHEN an access token expires THEN the client refreshes the session once and repeats the call.
- WHEN the app saves a document with an invalid collection name or a payload over 256 KB THEN the API answers 400 and the UI shows a validation message.
- WHEN another client of the app changes a document THEN the subscribed UI receives the event on the private tenant channel and updates without reloading.
A typical task list: define the environment variables, write one small client module per service, map the status codes to app behavior, and write tests with mocked responses.
## Reference: provisioning client (TypeScript)
```ts
type UsersResult = { status: number; body: any };
export async function doppioUsers(
body: Record<string, unknown>,
attempts = 3,
): Promise<UsersResult> {
for (let i = 0; i < attempts; i++) {
const res = await fetch(process.env.DOPPIO_USERS_URL!, {
method: "POST",
headers: {
"x-tenant-key": process.env.DOPPIO_TENANT_KEY!,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (res.status !== 429) {
return { status: res.status, body: await res.json().catch(() => ({})) };
}
await new Promise((r) => setTimeout(r, 500 * 2 ** i));
}
return { status: 429, body: { error: "rate limited" } };
}
```
## Support
hello@doppio.cloud. Doppio sets up tables, buckets and agents, and replaces a lost backend key (it issues a new one and revokes the old one).