> ## 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.

# Inicio rápido de User Lookup

> Esta guía te guía en la consulta de usuarios por su ID o username. Referencia del nivel estándar de X API v2 sobre inicio rápido.

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 te guía en la consulta de usuarios por su ID o username.

<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 de tu App
</Note>

***

## Buscar por ID

### Un solo usuario

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/users/2244994945?\
  user.fields=created_at,description,verified,public_metrics" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # Obtener usuario por ID
  response = client.users.get(
      "2244994945",
      user_fields=["created_at", "description", "verified", "public_metrics"]
  )

  print(f"Name: {response.data.name}")
  print(f"Username: {response.data.username}")
  print(f"Followers: {response.data.public_metrics.followers_count}")
  ```

  ```javascript title="JavaScript SDK" lines wrap icon="square-js" theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });

  // Obtener usuario por ID
  const response = await client.users.get("2244994945", {
    userFields: ["created_at", "description", "verified", "public_metrics"],
  });

  console.log(`Name: ${response.data?.name}`);
  console.log(`Username: ${response.data?.username}`);
  console.log(`Followers: ${response.data?.public_metrics?.followers_count}`);
  ```
</CodeGroup>

### Respuesta

```json title="Example response" 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": {
    "id": "2244994945",
    "name": "X Developers",
    "username": "XDevelopers",
    "created_at": "2013-12-14T04:35:55.000Z",
    "description": "The voice of the X developer community",
    "verified": true,
    "public_metrics": {
      "followers_count": 583423,
      "following_count": 2048,
      "tweet_count": 14052,
      "listed_count": 1672
    }
  }
}
```

### Múltiples usuarios

Consulta hasta 100 usuarios a la vez:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/users?\
  ids=2244994945,783214,6253282&\
  user.fields=username,verified" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # Obtener múltiples usuarios por ID
  response = client.users.get_users(
      ids=["2244994945", "783214", "6253282"],
      user_fields=["username", "verified"]
  )

  for user in response.data:
      print(f"{user.username} - Verified: {user.verified}")
  ```

  ```javascript title="JavaScript SDK" lines wrap icon="square-js" theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });

  // Obtener múltiples usuarios por ID
  const response = await client.users.getUsers({
    ids: ["2244994945", "783214", "6253282"],
    userFields: ["username", "verified"],
  });

  response.data?.forEach((user) => {
    console.log(`${user.username} - Verified: ${user.verified}`);
  });
  ```
</CodeGroup>

***

## Buscar por username

### Un solo usuario

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/users/by/username/XDevelopers?\
  user.fields=created_at,description,verified" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # Obtener usuario por username
  response = client.users.get_by_username(
      "XDevelopers",
      user_fields=["created_at", "description", "verified"]
  )

  print(f"ID: {response.data.id}")
  print(f"Name: {response.data.name}")
  ```

  ```javascript JavaScript SDK theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });

  // Obtener usuario por username
  const response = await client.users.getByUsername("XDevelopers", {
    userFields: ["created_at", "description", "verified"],
  });

  console.log(`ID: ${response.data?.id}`);
  console.log(`Name: ${response.data?.name}`);
  ```
</CodeGroup>

### Múltiples usuarios

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/users/by?\
  usernames=XDevelopers,X,elonmusk&\
  user.fields=created_at,verified" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # Obtener múltiples usuarios por username
  response = client.users.get_users_by_usernames(
      usernames=["XDevelopers", "X", "elonmusk"],
      user_fields=["created_at", "verified"]
  )

  for user in response.data:
      print(f"{user.username} - {user.created_at}")
  ```

  ```javascript title="JavaScript SDK" lines wrap icon="square-js" theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });

  // Obtener múltiples usuarios por username
  const response = await client.users.getUsersByUsernames({
    usernames: ["XDevelopers", "X", "elonmusk"],
    userFields: ["created_at", "verified"],
  });

  response.data?.forEach((user) => {
    console.log(`${user.username} - ${user.created_at}`);
  });
  ```
</CodeGroup>

***

## Fields disponibles

| Field               | Descripción                       |
| :------------------ | :-------------------------------- |
| `created_at`        | Fecha de creación de la cuenta    |
| `description`       | Bio del usuario                   |
| `profile_image_url` | URL del avatar                    |
| `verified`          | Estado de verificación            |
| `public_metrics`    | Recuentos de seguidores/seguidos  |
| `location`          | Ubicación definida por el usuario |
| `url`               | Sitio web del usuario             |
| `protected`         | Estado de cuenta protegida        |
| `pinned_tweet_id`   | ID del Post fijado                |

***

## Gestionar errores

### Usuario no encontrado

```json theme={null}
{
  "errors": [
    {
      "resource_type": "user",
      "title": "Not Found Error",
      "detail": "Could not find user with username: [nonexistent_user]."
    }
  ]
}
```

### Usuario protegido

Los datos de los usuarios protegidos se siguen devolviendo, pero no podrás acceder a sus Posts a menos que los sigas.

***

## Próximos pasos

<CardGroup cols={2}>
  <Card title="Usuario autenticado" icon="user-check" href="/x-api/users/lookup/quickstart/authenticated-lookup">
    Obtén el usuario actual
  </Card>

  <Card title="Guía de integración" icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-book.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=22ac564792481d14ae36a941546039c8" href="/x-api/users/lookup/integrate" width="24" height="24" data-path="icons/xds/icon-book.svg">
    Conceptos clave y mejores prácticas
  </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/users/get-user-by-id" width="24" height="24" data-path="icons/xds/icon-code.svg">
    Documentación completa del endpoint
  </Card>
</CardGroup>
