> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Guía de inicio rápido de la X Activity API para transmitir eventos

> Esta guía explica cómo suscribirse y recibir eventos usando los endpoints de la X Activity API. Referencia del nivel estándar de X API v2 que cubre activity.

export const Button = ({href, children}) => {
  return <div className="not-prose">
    <a href={href}>
      <button className="x-btn">
        <span>{children}</span>
        <svg width="3" height="24" viewBox="0 -9 3 24" class="h-6 rotate-0 overflow-visible"><path d="M0 0L3 3L0 6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>
      </button>
    </a>
  </div>;
};

Esta guía explica cómo suscribirse y recibir eventos usando los endpoints de la X Activity API. Generalmente hay 3 pasos involucrados:

1. Identificar el User ID del usuario cuyos eventos quieres filtrar
2. Crear una suscripción para el tipo de evento que quieres filtrar para ese usuario
3. Recibir los eventos mediante webhook o una conexión HTTP persistente de streaming

<Note>
  **Requisitos previos**

  Antes de comenzar, necesitarás:

  * Una [cuenta de desarrollador](https://developer.x.com/en/portal/petition/essential/basic-info) con una App aprobada
  * El [Bearer Token](/resources/fundamentals/authentication) de tu App
</Note>

***

## Obtener IDs de usuario

Antes de crear suscripciones, necesitarás conocer el user ID de la cuenta que deseas filtrar. En este ejemplo, usaremos el handle XDevelopers. Puedes buscar user IDs de varias formas, incluyendo:

**Buscar el ID de un usuario por username:**

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" "https://api.x.com/2/users/by/username/xdevelopers"
```

**Obtener tu propio user ID:**

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" https://api.x.com/2/users/me
```

Ambos endpoints devuelven información del usuario incluyendo el campo `id`, que puedes usar en los filtros de suscripción. A continuación se muestra un ejemplo de respuesta JSON:

```json theme={null}
{
    "data": {
        "id": "2244994945",
        "name": "Developers",
        "username": "XDevelopers"
    }
}
```

***

## Crear una suscripción

El siguiente paso es crear una suscripción. En este ejemplo, nos suscribiremos a las actualizaciones de biografía de XDevelopers. Para ello, pasaremos el `user_id` y el `event_type` en el cuerpo JSON. En este caso, el `event_type` es `profile.update.bio`.

Pasaremos el user ID de X Developers: `2244994945`, y un tag opcional:

```json theme={null}
{
  "event_type": "profile.update.bio",
  "filter": {
    "user_id": "2244994945"
  },
  "tag": "Xdevelopers' bio updates"
}
```

Usaremos nuestro [bearer token](https://docs.x.com/fundamentals/authentication/oauth-2-0/overview#bearer-token-also-known-as-app-only) (del portal de desarrolladores) para la autorización. El bearer token de solo aplicación funciona para eventos públicos como este. Algunos eventos son privados y requieren autenticación con [contexto de usuario (OAuth 2.0)](https://docs.x.com/fundamentals/authentication/oauth-2-0/overview#oauth-2-0-authorization-code-flow-with-pkce) — consulta [Privacidad de eventos y autenticación](/x-api/activity/introduction#event-privacy-and-authentication) para más detalles.

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" \
  https://api.x.com/2/activity/subscriptions \
  -X POST \
  -d '{
    "event_type": "profile.update.bio",
    "filter": {
      "user_id": "2244994945"
    },
    "tag": "Xdevelopers' bio updates"
  }'
```

Si la solicitud es exitosa, tu suscripción se creará:

```json title="profile.update.bio" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data":[
    {
      "created_at":"2025-10-09T16:35:08.000Z",
      "event_type":"profile.update.bio",
      "filter":{
        "user_id":"2244994945"
      },
      "subscription_id":"1976325569252868096",
      "tag": "Xdevelopers' bio updates",
      "updated_at":"2025-10-09T16:35:08.000Z"
    }
  ],
  "meta": {
    "total_subscriptions": 1
  }
}
```

***

## Recibir los eventos

Una vez creada la suscripción, podemos recibir los eventos a través de [webhooks](https://docs.x.com/x-api/webhooks/introduction) o de un stream HTTP persistente. En este ejemplo, abriremos el stream HTTP persistente:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" https://api.x.com/2/activity/stream
```

Cuando la cuenta Xdevelopers actualice su biografía de perfil, el evento se entregará a través del stream:

```json title="profile.update.bio" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": {
    "filter": {
      "user_id": "2244994945"
    },
    "event_type": "profile.update.bio",
    "tag": "Xdevelopers' bio updates",
    "payload": {
      "before": "Mars & Cars",
      "after": "Mars, Cars & AI"
    }
  }
}
```

***

## Gestión de suscripciones

La X Activity API proporciona endpoints para gestionar tus suscripciones mediante operaciones CRUD estándar.

### Crear suscripción

Crea una nueva suscripción para recibir eventos:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" \
  -X POST \
  https://api.x.com/2/activity/subscriptions \
  -d '{
    "event_type": "profile.update.bio",
    "filter": {
      "user_id": "123456789"
    },
    "tag": "my bio updates",
    "webhook_id": "1976325569252868099"
  }'
```

<Note>
  * El campo `tag` es opcional. Se puede usar para ayudar a identificar los eventos en la entrega.
  * El campo `webhook_id` también es opcional. Consulta nuestra [documentación de webhooks](https://docs.x.com/x-api/webhooks/introduction) para ayuda con la configuración de un webhook. Si se especifica un `webhook_id`, el evento se entregará al webhook proporcionado, además del stream si está abierto.
</Note>

**Respuesta:**

```json title="profile.update.bio" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": {
    "subscription_id": "1976325569252868096",
    "event_type": "profile.update.bio",
    "filter": {
      "user_id": "123456789"
    },
    "created_at": "2025-10-09T16:35:08.000Z",
    "updated_at": "2025-10-09T16:35:08.000Z",
    "tag": "my bio updates",
    "webhook_id": "1976325569252868099"
  }
}
```

### Listar suscripciones

Recupera todas las suscripciones activas de tu aplicación:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" \
  https://api.x.com/2/activity/subscriptions
```

**Respuesta:**

```json title="profile.update.bio" expandable lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": [
    {
      "subscription_id": "1976325569252868096",
      "event_type": "profile.update.bio",
      "filter": {
        "user_id": "123456789"
      },
      "created_at": "2025-10-09T16:35:08.000Z",
      "updated_at": "2025-10-10T03:50:59.000Z"
    },
    {
      "subscription_id": "1976325569252868097",
      "event_type": "profile.update.profile_picture",
      "filter": {
        "user_id": "987654321"
      },
      "created_at": "2025-10-08T14:35:08.000Z",
      "updated_at": "2025-10-08T14:35:08.000Z"
    }
  ],
  "meta": {
    "total_subscriptions": 2
  }
}
```

### Eliminar suscripción

Elimina una suscripción:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" \
  -X DELETE \
  https://api.x.com/2/activity/subscriptions/1976325569252868096
```

**Respuesta:**

```json theme={null}
{
  "data": {
    "deleted": true
  },
  "meta": {
    "total_subscriptions": 0
  }
}
```

`total_subscriptions` muestra el número restante de suscripciones asociadas a tu app tras la operación de eliminación.

### Actualizar suscripción

El endpoint PUT te permite actualizar el método de entrega o el tag de una suscripción.

Actualizar el `filter` o el `event_type` requiere eliminar la suscripción existente y agregar una nueva.

```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" \
  -X PUT \
  https://api.x.com/2/activity/subscriptions/1976325569252868096 \
  -d '{
    "tag": "my new tag",
    "webhook_id": "192846273860294839"
  }'
```

**Respuesta:**

```json title="profile.update.bio" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": {
    "subscription_id": "1976325569252868096",
    "event_type": "profile.update.bio",
    "filter": {
      "user_id": "123456789"
    },
    "created_at": "2025-10-09T16:35:08.000Z",
    "updated_at": "2025-10-10T17:10:58.000Z",
    "tag": "my new tag",
    "webhook_id": "192846273860294839"
  },
  "meta": {
    "total_subscriptions": 1
  }
}
```

***

## Próximos pasos

<CardGroup cols={2}>
  <Card title="Payloads de eventos" icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" href="/x-api/activity/event-payloads" width="24" height="24" data-path="icons/xds/icon-brackets.svg">
    JSON de ejemplo para cada tipo de evento de activity
  </Card>

  <Card title="Referencia de la API" icon="https://mintcdn.com/x-preview/ygI6sSJPehlc0qNT/icons/xds/icon-code.svg?fit=max&auto=format&n=ygI6sSJPehlc0qNT&q=85&s=488e23401b19225b89acc0136d242219" href="/x-api/activity/activity-stream" width="24" height="24" data-path="icons/xds/icon-code.svg">
    Documentación completa del endpoint
  </Card>

  <Card title="Webhooks" icon="webhook" href="/x-api/webhooks/introduction">
    Configura la entrega mediante webhook
  </Card>
</CardGroup>
