Skip to main content
This guide covers the key concepts you need to integrate the User lookup endpoints into your application.

Authentication

All X API v2 endpoints require authentication. Choose the method that fits your use case:
MethodBest forCan access private metrics?
OAuth 2.0 App-OnlyServer-to-server, public dataNo
OAuth 2.0 Authorization Code with PKCEUser-facing appsYes (for authorized user’s data)
OAuth 1.0a User ContextLegacy integrationsYes (for authorized user’s data)

App-Only authentication

For public user data, use a Bearer Token:
cURL
curl "https://api.x.com/2/users/by/username/XDevelopers" \
  -H "Authorization: Bearer $BEARER_TOKEN"
from xdk import Client

client = Client(bearer_token="YOUR_BEARER_TOKEN")

# Get user by username
response = client.users.get_by_username("XDevelopers")
print(response.data)
import { Client } from "@xdevplatform/xdk";

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

const response = await client.users.getByUsername("XDevelopers");
console.log(response.data);

User Context authentication

Required for the authenticated user endpoint (/2/users/me):
cURL
curl "https://api.x.com/2/users/me" \
  -H "Authorization: Bearer $USER_ACCESS_TOKEN"
from xdk import Client

# Using OAuth 2.0 user access token
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

# Get authenticated user's profile
response = client.users.get_me()
print(response.data)
import { Client } from "@xdevplatform/xdk";

// Using OAuth 2.0 user access token
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });

const response = await client.users.getMe();
console.log(response.data);
The /2/users/me endpoint only works with User Context authentication. App-Only tokens will return an error.

Fields and expansions

The X API v2 returns minimal data by default. Use fields and expansions to request exactly what you need.

Default response

{
  "data": {
    "id": "2244994945",
    "name": "X Developers",
    "username": "XDevelopers"
  }
}

Available fields

FieldDescription
created_atAccount creation timestamp
descriptionUser bio
entitiesParsed URLs in bio
locationUser-defined location
pinned_tweet_idPinned Post ID
profile_image_urlAvatar URL
protectedWhether account is protected
public_metricsFollower/following counts
urlWebsite URL
verifiedVerification status
withheldWithholding information
FieldDescription
created_atPost creation timestamp
textPost content
public_metricsEngagement counts
entitiesHashtags, mentions, URLs

Example with fields

cURL
curl "https://api.x.com/2/users/by/username/XDevelopers?\
user.fields=created_at,description,public_metrics,verified&\
expansions=pinned_tweet_id&\
tweet.fields=created_at,public_metrics" \
  -H "Authorization: Bearer $BEARER_TOKEN"
from xdk import Client

client = Client(bearer_token="YOUR_BEARER_TOKEN")

# Get user with additional fields and expansions
response = client.users.get_by_username(
    "XDevelopers",
    user_fields=["created_at", "description", "public_metrics", "verified"],
    expansions=["pinned_tweet_id"],
    tweet_fields=["created_at", "public_metrics"]
)

print(response.data)
print(response.includes)  # Contains expanded pinned tweet
import { Client } from "@xdevplatform/xdk";

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

const response = await client.users.getByUsername("XDevelopers", {
  userFields: ["created_at", "description", "public_metrics", "verified"],
  expansions: ["pinned_tweet_id"],
  tweetFields: ["created_at", "public_metrics"],
});

console.log(response.data);
console.log(response.includes); // Contains expanded pinned tweet

Response with expansions

{
  "data": {
    "id": "2244994945",
    "name": "X Developers",
    "username": "XDevelopers",
    "created_at": "2013-12-14T04:35:55.000Z",
    "verified": true,
    "pinned_tweet_id": "1234567890",
    "public_metrics": {
      "followers_count": 583423,
      "following_count": 2048,
      "tweet_count": 14052
    }
  },
  "includes": {
    "tweets": [
      {
        "id": "1234567890",
        "text": "Welcome to the X Developer Platform!",
        "created_at": "2024-01-15T10:00:00.000Z"
      }
    ]
  }
}

Fields and expansions guide

Learn more about customizing responses

Batch lookups

Look up multiple users in a single request:
cURL (by IDs)
curl "https://api.x.com/2/users?ids=2244994945,783214,6253282&\
user.fields=username,verified" \
  -H "Authorization: Bearer $BEARER_TOKEN"
curl "https://api.x.com/2/users/by?usernames=XDevelopers,X,XAPI&\
user.fields=username,verified" \
  -H "Authorization: Bearer $BEARER_TOKEN"
from xdk import Client

client = Client(bearer_token="YOUR_BEARER_TOKEN")

# Get multiple users by IDs
response = client.users.get_users(
    ids=["2244994945", "783214", "6253282"],
    user_fields=["username", "verified"]
)
for user in response.data:
    print(f"{user.username}: {user.verified}")

# Get multiple users by usernames
response = client.users.get_users_by_usernames(
    usernames=["XDevelopers", "X", "XAPI"],
    user_fields=["username", "verified"]
)
for user in response.data:
    print(f"{user.username}: {user.verified}")
import { Client } from "@xdevplatform/xdk";

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

// Get multiple users by IDs
const byIds = await client.users.getUsers({
  ids: ["2244994945", "783214", "6253282"],
  userFields: ["username", "verified"],
});
byIds.data.forEach((user) => {
  console.log(`${user.username}: ${user.verified}`);
});

// Get multiple users by usernames
const byUsernames = await client.users.getUsersByUsernames({
  usernames: ["XDevelopers", "X", "XAPI"],
  userFields: ["username", "verified"],
});
byUsernames.data.forEach((user) => {
  console.log(`${user.username}: ${user.verified}`);
});
Batch requests are limited to 100 users. Use multiple requests for larger datasets.

Error handling

Common errors

StatusErrorSolution
400Invalid requestCheck parameter formatting
401UnauthorizedVerify authentication credentials
403ForbiddenCheck App permissions
404Not FoundUser doesn’t exist or was suspended
429Too Many RequestsWait and retry (see rate limits)

Suspended or deleted users

If a user is suspended or deleted:
  • Single user lookup returns 404
  • Multi-user lookup omits the user from results with an errors array
{
  "data": [
    { "id": "2244994945", "username": "XDevelopers" }
  ],
  "errors": [
    {
      "resource_id": "1234567890",
      "resource_type": "user",
      "title": "Not Found Error",
      "detail": "Could not find user with id: [1234567890]."
    }
  ]
}

Protected users

For protected accounts you don’t follow:
  • Basic info (id, name, username) is available
  • Protected content (pinned Post) may be restricted
  • protected: true indicates the account status

Best practices

Batch requests

Use multi-user endpoints to fetch up to 100 users at once, reducing API calls.

Request only needed fields

Specify only the fields you need to minimize response size.

Cache user data

Cache user profiles locally to reduce repeated requests.

Handle errors gracefully

Check for partial errors in batch responses.

Next steps

API Reference

Complete endpoint documentation

Data dictionary

All available objects and fields

Sample code

Working code examples

Error handling

Handle errors gracefully