# Leads

Gestiona leads (contactos) de tu proyecto via API. Incluye CRUD, segmentos, tags y atributos.

## Autenticacion

Todas las peticiones requieren un Bearer token:

```
Authorization: Bearer sk_proj_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

***

## Endpoints

### POST /v1/leads

Crear o actualizar uno o muchos leads. Si el email ya existe en el proyecto, se actualiza (upsert).

**Request (individual):**

```json
{
  "email": "jane@acme.com",
  "data": { "name": "Jane", "phone": "+1234567890" },
  "segment_ids": ["uuid-segmento-1"]
}
```

**Request (bulk, hasta 1,000):**

```json
{
  "leads": [
    { "email": "jane@acme.com", "data": { "name": "Jane" } },
    { "email": "mike@store.co", "data": { "name": "Mike" }, "segment_ids": ["uuid"] }
  ]
}
```

| Campo        | Tipo      | Requerido              | Descripcion                               |
| ------------ | --------- | ---------------------- | ----------------------------------------- |
| email        | string    | Si (si no hay `leads`) | Email del lead                            |
| data         | object    | No                     | Atributos custom (nombre, telefono, etc.) |
| segment\_ids | string\[] | No                     | UUIDs de segmentos a asignar              |
| leads        | array     | Si (si no hay `email`) | Array de leads para bulk                  |

**Response (201):**

```json
{
  "success": true,
  "total": 2,
  "leads": [
    { "id": "uuid", "email": "jane@acme.com", "created": true },
    { "id": "uuid", "email": "mike@store.co", "created": false }
  ]
}
```

`created: true` = lead nuevo. `created: false` = lead existente actualizado.

***

### GET /v1/leads

Listar leads con paginacion.

| Parametro   | Tipo   | Default | Descripcion                     |
| ----------- | ------ | ------- | ------------------------------- |
| page        | number | 1       | Pagina                          |
| per\_page   | number | 50      | Resultados por pagina (max 200) |
| search      | string | —       | Buscar por email o nombre       |
| segment\_id | UUID   | —       | Filtrar por segmento            |

**Response (200):**

```json
{
  "success": true,
  "data": [
    { "id": "uuid", "email": "jane@acme.com", "data": { "name": "Jane" }, "created_at": "...", "updated_at": "..." }
  ],
  "pagination": {
    "page": 1,
    "per_page": 50,
    "total": 1234,
    "total_pages": 25
  }
}
```

***

### GET /v1/leads/:id

Obtener un lead por ID, incluyendo sus segmentos.

**Response (200):**

```json
{
  "success": true,
  "lead": {
    "id": "uuid",
    "email": "jane@acme.com",
    "data": { "name": "Jane" },
    "created_at": "...",
    "updated_at": "...",
    "segment_ids": ["uuid-1", "uuid-2"]
  }
}
```

***

### PUT /v1/leads/:id

Actualizar un lead. Al menos uno de `email`, `data`, o `segment_ids` es requerido.

Si se envia `segment_ids`, **reemplaza** todas las memberships existentes.

**Request:**

```json
{
  "email": "new@acme.com",
  "data": { "name": "Jane Updated", "plan": "pro" },
  "segment_ids": ["uuid-1"]
}
```

**Response (200):** Mismo formato que GET /v1/leads/:id

***

### DELETE /v1/leads/:id

Eliminar un lead y sus memberships de segmentos.

**Response (200):**

```json
{ "success": true }
```

***

## Segmentos

### POST /v1/leads/:id/segments

Agregar un lead a uno o mas segmentos.

```json
{ "segment_ids": ["uuid-1", "uuid-2"] }
```

**Response (200):**

```json
{ "success": true, "added": 2 }
```

### DELETE /v1/leads/:id/segments/:segmentId

Quitar un lead de un segmento.

**Response (200):**

```json
{ "success": true }
```

***

## Tags

Tags se almacenan como un array en los atributos del lead. Son etiquetas simples de texto.

### POST /v1/leads/:email/tags

Agregar tags a un lead (se combinan con los existentes, sin duplicados).

```json
{ "tags": ["vip", "spanish_speaker", "hot_lead"] }
```

**Response (200):**

```json
{ "success": true, "tags": ["vip", "spanish_speaker", "hot_lead"] }
```

### DELETE /v1/leads/:email/tags

Quitar tags de un lead.

```json
{ "tags": ["hot_lead"] }
```

**Response (200):**

```json
{ "success": true, "tags": ["vip", "spanish_speaker"] }
```

### GET /v1/leads/:email/tags

Listar tags de un lead.

**Response (200):**

```json
{ "success": true, "tags": ["vip", "spanish_speaker"] }
```

***

## Attributes

Atributos custom almacenados en el campo `data` del lead. Se hace merge (shallow) con los existentes.

### POST /v1/leads/:email/attributes

```json
{ "plan": "pro", "mrr": 49, "team_size": 12 }
```

**Response (200):**

```json
{ "success": true, "data": { "plan": "pro", "mrr": 49, "team_size": 12, "name": "Jane" } }
```

### GET /v1/leads/:email/attributes

**Response (200):**

```json
{ "success": true, "data": { "plan": "pro", "mrr": 49, "team_size": 12, "name": "Jane" } }
```

***

## Errores

| Codigo | Significado                                            |
| ------ | ------------------------------------------------------ |
| 400    | Validacion fallida (campo requerido, formato invalido) |
| 401    | API key invalido o faltante                            |
| 404    | Lead o segmento no encontrado                          |
| 409    | Email ya existe en otro lead del proyecto              |
| 500    | Error interno                                          |

Formato de error:

```json
{ "error": "Descripcion del error" }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://reallyquickemails.gitbook.io/reallyquickemails-docs/referencia-api/leads.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
