x
Use when building applications that access X's public data: searching posts, retrieving user information, managing timelines, streaming real-time posts, publishing content, managing direct messages, lists, and analyzing trends. Use for data collection, automation, analytics, and building integrations with X.
Savant verdict: Analyzed
Scanned or evaluated by Savant; not yet both passing.
Live evaluation
Not evaluated yet. Workspaces can request a live evaluation.
Security assessment
Risk score
5/100
Recommendation
CAUTION
Severity
LOW
Savant decision
Passed (low risk)
The assessment recommended caution, but its risk score is below 20/100, so Savant's policy passes it. Its findings are still listed for review. Static security analysis completed.
1 pattern found
- Data Exfiltration: https://api.x.com/medium · SKILL.md:17 · Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.
Structure
- No license declaredConfirm you may reuse this skill before importing it into your repository.
SKILL.md
---
name: x
description: "Use when building applications that access X's public data:
searching posts, retrieving user information, managing timelines, streaming
real-time posts, publishing content, managing direct messages, lists, and
analyzing trends. Use for data collection, automation, analytics, and building
integrations with X."
metadata:
mintlify-proj: x
version: "1.0"
---
# X API Skill Reference
## Product summary
The X API provides programmatic access to X's public conversation through modern REST endpoints. Agents use it to search posts, retrieve user data, manage timelines, stream real-time posts, publish content, manage direct messages, and analyze trends. The API uses pay-per-usage pricing with no commitments. Key files: Bearer Token (from Developer Console), API endpoints at `https://api.x.com/2/`, authentication via OAuth 1.0a or OAuth 2.0. Official SDKs available for Python (`xdk`) and TypeScript (`@xdevplatform/xdk`). Primary docs: https://docs.x.com/x-api/introduction
## When to use
Reach for this skill when:
- Building tools to search or retrieve posts from the last 7 days or full archive (enterprise)
- Looking up user profiles, followers, following lists, or user timelines
- Streaming real-time posts matching filter rules
- Publishing posts, managing likes, reposts, bookmarks, or replies
- Managing direct messages, lists, spaces, or trends
- Analyzing post metrics and engagement data
- Integrating X data into dashboards, bots, or analytics platforms
- Handling authentication for user-context or app-only requests
- Debugging rate limits, pagination, or API errors
## Quick reference
### Authentication methods
| Method | Use case | Scope |
|:-------|:---------|:------|
| Bearer Token (app-only) | Read-only public data, no user context | App-wide |
| OAuth 1.0a User Context | Post on behalf of user, manage user's data | User-specific |
| OAuth 2.0 Authorization Code (PKCE) | Secure user-authorized access with scopes | User-specific |
| OAuth 2.0 App-Only | Read public data, app-wide access | App-wide |
Get credentials from Developer Console: https://console.x.com
### Common endpoints
| Task | Endpoint | Method |
|:-----|:---------|:--------|
| Look up user by username | `/2/users/by/username/:username` | GET |
| Look up post by ID | `/2/tweets/:id` | GET |
| Search recent posts (7 days) | `/2/tweets/search/recent` | GET |
| Search full archive | `/2/tweets/search/all` | GET |
| Get user's posts | `/2/users/:id/tweets` | GET |
| Create post | `/2/tweets` | POST |
| Delete post | `/2/tweets/:id` | DELETE |
| Connect to filtered stream | `/2/tweets/search/stream` | GET |
| Add stream rules | `/2/tweets/search/stream/rules` | POST |
| Get stream rules | `/2/tweets/search/stream/rules` | GET |
| Like post | `/2/users/:id/likes` | POST |
| Get liked posts | `/2/users/:id/liked_tweets` | GET |
### Rate limit headers
Monitor these response headers to avoid hitting limits:
```
x-rate-limit-limit: 450
x-rate-limit-remaining: 425
x-rate-limit-reset: 1705420800
```
Most endpoints have 15-minute windows. Check `/x-api/fundamentals/rate-limits` for per-endpoint limits.
### Fields and expansions
Request additional data with query parameters:
```bash
# Request specific fields
?tweet.fields=created_at,public_metrics,conversation_id
# Include related objects
?expansions=author_id,attachments.media_keys
# Request user fields on expanded author
?user.fields=username,name,profile_image_url
```
Default response includes only `id` and `text` for posts. Use fields/expansions to customize.
### Pagination
Use `max_results` and `next_token` for large result sets:
```bash
?max_results=100&next_token=b26v89c19zqg8o3fpza...
```
SDKs handle pagination automatically. For cURL, save `next_token` from response and use in next request.
## Decision guidance
| Scenario | Choose | Why |
|:---------|:-------|:----|
| Need real-time posts as they publish | Filtered Stream | 4-5 second latency, persistent connection |
| Need lowest latency (< 1 second) | Powerstream (Enterprise) | Optimized for speed, similar to legacy Powertrack |
| Searching historical posts | Full-Archive Search (enterprise) | Access back to 2006; recent search limited to 7 days |
| Publishing posts | OAuth 1.0a or OAuth 2.0 user context | Requires user authorization |
| Read-only public data | Bearer Token (app-only) | Simpler, no user context needed |
| Managing user's own data | OAuth 1.0a or OAuth 2.0 user context | Access private/owned data |
| High-volume streaming | Enterprise with multiple connections | Pay-per-use limited to 1 connection |
| Building for production | Official SDK (Python/TypeScript) | Handles auth, pagination, rate limits automatically |
| Quick testing | cURL or Postman | No setup required, good for exploration |
## Workflow
### Making your first request
1. **Get credentials**: Sign up at https://console.x.com, create an app, copy Bearer Token from "Keys and tokens"
2. **Choose endpoint**: Start with user lookup, post lookup, or recent search
3. **Build request**: Use cURL, Postman, or SDK with Bearer Token in Authorization header
4. **Parse response**: Data is in `data` field; check for `meta.next_token` for pagination
5. **Add fields**: Use `tweet.fields`, `user.fields`, `expansions` to request additional data
6. **Handle errors**: Check HTTP status code and `errors` array in response
### Streaming real-time posts
1. **Create rules**: POST to `/2/tweets/search/stream/rules` with rule value (e.g., `{"add": [{"value": "from:xdevelopers"}]}`)
2. **Verify rules**: GET `/2/tweets/search/stream/rules` to list active rules
3. **Connect to stream**: GET `/2/tweets/search/stream` with persistent connection
4. **Receive posts**: Read lines from response; blank lines are keep-alive signals
5. **Handle disconnection**: Implement exponential backoff and reconnect; stream sends keep-alive every 20 seconds
6. **Manage rules**: Add/remove rules without disconnecting; changes take effect immediately
### Publishing posts
1. **Authenticate**: Use OAuth 1.0a or OAuth 2.0 user context (not app-only)
2. **Build payload**: `{"text": "Your post text"}` (max 280 characters after counting)
3. **POST to `/2/tweets`**: Include media IDs, reply settings, or quote post ID if needed
4. **Check response**: Returns new post ID and text in `data` field
5. **Handle errors**: 400 errors indicate invalid text, media, or permissions
### Searching posts
1. **Build query**: Use operators like `from:user`, `#hashtag`, `lang:en`, `-is:retweet`
2. **Choose endpoint**: Recent search (7 days, all developers) or full-archive (enterprise only)
3. **Set max_results**: Default 10, max 100 for recent search, 500 for full-archive
4. **Request fields**: Add `tweet.fields`, `user.fields`, `expansions` for additional data
5. **Paginate**: Use `next_token` from response to fetch next page
6. **Monitor rate limits**: Recent search: 450/15min (app), 300/15min (user); full-archive: 1/sec, 300/15min
## Common gotchas
- **Bearer Token vs. user context**: Bearer Token is app-only and can't post or access user-specific data. Use OAuth for user actions.
- **Default fields are minimal**: Posts return only `id` and `text` by default. Always add `tweet.fields` and `expansions` to get author, metrics, timestamps.
- **Character counting**: Use `twitter-text` library to count characters correctly (URLs, emoji, etc. count differently). Posts limited to 280 characters.
- **Rate limits reset on 15-minute windows**: Don't assume reset time is exactly 15 minutes from now. Use `x-rate-limit-reset` header (Unix timestamp).
- **Stream keep-alive signals**: Blank lines (`\r\n`) every 20 seconds are normal. If no data or keep-alive for 20+ seconds, reconnect.
- **Edited posts have new IDs**: Each edit creates a new post ID. `edit_history_tweet_ids` array shows all versions.
- **Search limited to 7 days**: Recent search endpoint only returns posts from last 7 days. Use full-archive search (enterprise) for older posts.
- **Pagination tokens are opaque**: Don't parse or modify `next_token`. Treat as a string and pass as-is in next request.
- **Protected accounts**: Posts from protected accounts only visible with authorization. Public posts always visible.
- **Streaming rules are per-project**: Rules persist across connections. Manage via `/2/tweets/search/stream/rules` endpoints.
- **429 errors require backoff**: Don't retry immediately. Wait until `x-rate-limit-reset` time. Implement exponential backoff for robustness.
## Verification checklist
Before submitting work with X API:
- [ ] Authentication method matches use case (app-only for read-only, user context for publishing/managing)
- [ ] Bearer Token or OAuth tokens are stored securely (environment variables, not hardcoded)
- [ ] Request includes required parameters (query for search, user ID for timelines, etc.)
- [ ] Response parsing handles both success (`data` field) and error (`errors` array) cases
- [ ] Rate limit headers are monitored; 429 responses trigger backoff/retry
- [ ] Pagination implemented for endpoints returning `next_token` (search, timelines, etc.)
- [ ] Fields and expansions requested match the data needed (don't request unnecessary fields)
- [ ] Streaming connections implement reconnection logic with exponential backoff
- [ ] Post text validated for length (280 characters) before publishing
- [ ] Error messages logged with HTTP status code and error code for debugging
- [ ] Tests use Postman collection or SDK examples before deploying
## Resources
**Comprehensive navigation**: https://docs.x.com/llms.txt
**Critical pages**:
- [X API Introduction](/x-api/introduction) — Overview of endpoints and features
- [Make Your First Request](/make-your-first-request) — Step-by-step quickstart with cURL examples
- [Authentication Overview](/fundamentals/authentication/overview) — All auth methods explained
- [Rate Limits Reference](/x-api/fundamentals/rate-limits) — Per-endpoint limits and handling 429s
- [Filtered Stream Introduction](/x-api/posts/filtered-stream/introduction) — Real-time streaming setup
- [Data Dictionary](/x-api/fundamentals/data-dictionary) — All available fields and expansions
- [Response Codes and Errors](/x-api/fundamentals/response-codes-and-errors) — Error handling guide
- [Official SDKs](/tools-and-libraries) — Python and TypeScript libraries with examples
---
> For additional documentation and navigation, see: https://docs.x.com/llms.txt