# AGENT
Source: https://docs.x.com/AGENT
# X Developer Platform — Agent Instructions
This document provides guidance for AI agents, coding assistants, and LLM-based tools interacting with the X Developer Platform documentation at [https://docs.x.com](https://docs.x.com).
## Preferred Documentation Access Methods
**Always prefer these methods for the most accurate, up-to-date, and agent-friendly content:**
1. **llms.txt** (recommended starting point)
* [https://docs.x.com/llms.txt](https://docs.x.com/llms.txt) — Small, curated root index with links to section-specific indexes.
* Section indexes (follow the links in the root):
* [https://docs.x.com/x-api/llms.txt](https://docs.x.com/x-api/llms.txt) (X API v2 — 370+ pages)
* [https://docs.x.com/enterprise-api/llms.txt](https://docs.x.com/enterprise-api/llms.txt)
* [https://docs.x.com/x-ads-api/llms.txt](https://docs.x.com/x-ads-api/llms.txt)
* [https://docs.x.com/xdks/llms.txt](https://docs.x.com/xdks/llms.txt) (Python + TypeScript XDKs)
2. **llms-full.txt** — Complete documentation as a single Markdown file for maximum context:
* [https://docs.x.com/llms-full.txt](https://docs.x.com/llms-full.txt)
3. **Raw Markdown for any individual page**
* Append `.md` to any documentation URL.
* Example: `https://docs.x.com/x-api/posts/get-post-by-id.md`
* Every page supports this. Use it instead of the HTML view when possible.
4. **MCP Server** (for tool-using agents)
* [https://docs.x.com/tools/mcp](https://docs.x.com/tools/mcp) — Hosted X MCP (`api.x.com/mcp` via `xurl`) + documentation search MCP.
5. **skill.md** (capability summary)
* [https://docs.x.com/skill.md](https://docs.x.com/skill.md) — Structured description of every action an agent can perform with the X API (agentskills.io format).
## Site Structure & Navigation
* **X API v2** (`/x-api/...`): Posts, Users, Direct Messages, Lists, Spaces, Media, Streams (filtered + volume), Compliance, Webhooks, Account Activity, Trends, News, Usage, Connections.
* **Enterprise APIs** (`/enterprise-api/...`): Account Activity (webhooks), X Activity (XAA), GNIP/PowerTrack historical & real-time, Compliance.
* **Ads API** (`/x-ads-api/...`): Campaign Management, Creatives, Audiences, Analytics, Measurement, Catalog.
* **SDKs (XDKs)** (`/xdks/python/...` and `/xdks/typescript/...`): Official client libraries with full type coverage, pagination, and streaming helpers.
* **Fundamentals**: Authentication, rate limits, data dictionary, expansions, fields, pagination, versioning, consistency.
* **AI & Agent Tools** (`/tools/ai`, `/tools/llms-txt`, `/tools/skill-md`, `/tools/mcp`).
All pages are available in the navigation tree defined in `docs.json`.
## Important Technical Notes for Agents
* **Authentication**: The platform supports OAuth 1.0a (user context), OAuth 2.0 (user context + PKCE, app-only Bearer), and Basic Auth for some enterprise endpoints. See `/fundamentals/authentication/...`.
* **Rate Limits**: Most endpoints have both app-level and user-level rate limits. See `/fundamentals/rate-limits.md` and per-endpoint documentation.
* **Data Model**: Use the official data dictionary, fields, expansions, and metrics pages. Posts, Users, and Spaces are the core objects.
* **Real-time Data**: Filtered Stream, Volume Streams, Account Activity webhooks, and X Activity (XAA) are the primary real-time mechanisms.
* **Compliance & Safety**: Always respect developer terms, display requirements, and restricted use cases. See `/developer-guidelines.md` and `/developer-terms/...`.
## How to Use This Documentation Effectively
* Start with the root `llms.txt` to discover relevant pages.
* Fetch individual pages via the `.md` suffix for clean, structured Markdown.
* For deep context on the entire platform, load `llms-full.txt`.
* For structured capabilities (what actions are possible), load `skill.md`.
* For live tool calling against the X API, use the MCP server.
* When writing code, prefer the official Python or TypeScript XDKs (full references available in their `llms.txt` files).
## Do Not
* Rely solely on the HTML-rendered pages when a clean Markdown alternative exists.
* Assume deprecated v1.1 endpoints are still primary (focus on v2 and Enterprise equivalents).
* Ignore rate limits, authentication context (app-only vs user context), or pagination requirements.
* Generate code that violates the X Developer Agreement or Display Requirements.
## Additional Resources
* OpenAPI spec: [https://docs.x.com/openapi.json](https://docs.x.com/openapi.json) (or [https://api.x.com/2/openapi.json](https://api.x.com/2/openapi.json))
* Changelog: [https://docs.x.com/changelog.md](https://docs.x.com/changelog.md) (RSS feed: [https://docs.x.com/changelog/rss.xml](https://docs.x.com/changelog/rss.xml))
* Status page: [https://docs.x.com/status.md](https://docs.x.com/status.md)
* Developer Guidelines: [https://docs.x.com/developer-guidelines.md](https://docs.x.com/developer-guidelines.md)
* Support & Community: [https://devcommunity.x.com](https://devcommunity.x.com)
This documentation is designed to be consumed reliably by AI agents. Use the machine-readable formats (`llms.txt` family, `.md` suffix, `skill.md`, MCP) for the best results.
# AGENTS
Source: https://docs.x.com/AGENTS
# X Developer Platform — Agent Instructions
This document provides guidance for AI agents, coding assistants, and LLM-based tools interacting with the X Developer Platform documentation at [https://docs.x.com](https://docs.x.com).
## Preferred Documentation Access Methods
**Always prefer these methods for the most accurate, up-to-date, and agent-friendly content:**
1. **llms.txt** (recommended starting point)
* [https://docs.x.com/llms.txt](https://docs.x.com/llms.txt) — Small, curated root index with links to section-specific indexes.
* Section indexes (follow the links in the root):
* [https://docs.x.com/x-api/llms.txt](https://docs.x.com/x-api/llms.txt) (X API v2 — 370+ pages)
* [https://docs.x.com/enterprise-api/llms.txt](https://docs.x.com/enterprise-api/llms.txt)
* [https://docs.x.com/x-ads-api/llms.txt](https://docs.x.com/x-ads-api/llms.txt)
* [https://docs.x.com/xdks/llms.txt](https://docs.x.com/xdks/llms.txt) (Python + TypeScript XDKs)
2. **llms-full.txt** — Complete documentation as a single Markdown file for maximum context:
* [https://docs.x.com/llms-full.txt](https://docs.x.com/llms-full.txt)
3. **Raw Markdown for any individual page**
* Append `.md` to any documentation URL.
* Example: `https://docs.x.com/x-api/posts/get-post-by-id.md`
* Every page supports this. Use it instead of the HTML view when possible.
4. **MCP Server** (for tool-using agents)
* [https://docs.x.com/tools/mcp](https://docs.x.com/tools/mcp) — Hosted X MCP (`api.x.com/mcp` via `xurl`) + documentation search MCP.
5. **skill.md** (capability summary)
* [https://docs.x.com/skill.md](https://docs.x.com/skill.md) — Structured description of every action an agent can perform with the X API (agentskills.io format).
## Site Structure & Navigation
* **X API v2** (`/x-api/...`): Posts, Users, Direct Messages, Lists, Spaces, Media, Streams (filtered + volume), Compliance, Webhooks, Account Activity, Trends, News, Usage, Connections.
* **Enterprise APIs** (`/enterprise-api/...`): Account Activity (webhooks), X Activity (XAA), GNIP/PowerTrack historical & real-time, Compliance.
* **Ads API** (`/x-ads-api/...`): Campaign Management, Creatives, Audiences, Analytics, Measurement, Catalog.
* **SDKs (XDKs)** (`/xdks/python/...` and `/xdks/typescript/...`): Official client libraries with full type coverage, pagination, and streaming helpers.
* **Fundamentals**: Authentication, rate limits, data dictionary, expansions, fields, pagination, versioning, consistency.
* **AI & Agent Tools** (`/tools/ai`, `/tools/llms-txt`, `/tools/skill-md`, `/tools/mcp`).
All pages are available in the navigation tree defined in `docs.json`.
## Important Technical Notes for Agents
* **Authentication**: The platform supports OAuth 1.0a (user context), OAuth 2.0 (user context + PKCE, app-only Bearer), and Basic Auth for some enterprise endpoints. See `/fundamentals/authentication/...`.
* **Rate Limits**: Most endpoints have both app-level and user-level rate limits. See `/fundamentals/rate-limits.md` and per-endpoint documentation.
* **Data Model**: Use the official data dictionary, fields, expansions, and metrics pages. Posts, Users, and Spaces are the core objects.
* **Real-time Data**: Filtered Stream, Volume Streams, Account Activity webhooks, and X Activity (XAA) are the primary real-time mechanisms.
* **Compliance & Safety**: Always respect developer terms, display requirements, and restricted use cases. See `/developer-guidelines.md` and `/developer-terms/...`.
## How to Use This Documentation Effectively
* Start with the root `llms.txt` to discover relevant pages.
* Fetch individual pages via the `.md` suffix for clean, structured Markdown.
* For deep context on the entire platform, load `llms-full.txt`.
* For structured capabilities (what actions are possible), load `skill.md`.
* For live tool calling against the X API, use the MCP server.
* When writing code, prefer the official Python or TypeScript XDKs (full references available in their `llms.txt` files).
## Do Not
* Rely solely on the HTML-rendered pages when a clean Markdown alternative exists.
* Assume deprecated v1.1 endpoints are still primary (focus on v2 and Enterprise equivalents).
* Ignore rate limits, authentication context (app-only vs user context), or pagination requirements.
* Generate code that violates the X Developer Agreement or Display Requirements.
## Additional Resources
* OpenAPI spec: [https://docs.x.com/openapi.json](https://docs.x.com/openapi.json) (or [https://api.x.com/2/openapi.json](https://api.x.com/2/openapi.json))
* Changelog: [https://docs.x.com/changelog.md](https://docs.x.com/changelog.md) (RSS feed: [https://docs.x.com/changelog/rss.xml](https://docs.x.com/changelog/rss.xml))
* Status page: [https://docs.x.com/status.md](https://docs.x.com/status.md)
* Developer Guidelines: [https://docs.x.com/developer-guidelines.md](https://docs.x.com/developer-guidelines.md)
* Support & Community: [https://devcommunity.x.com](https://devcommunity.x.com)
This documentation is designed to be consumed reliably by AI agents. Use the machine-readable formats (`llms.txt` family, `.md` suffix, `skill.md`, MCP) for the best results.
# X API changelog and release notes
Source: https://docs.x.com/changelog
Release notes and version history for the X API v2, Enterprise APIs, Ads API, SDKs, streaming, webhooks, and the developer platform.
To subscribe to updates, please [**“Turn on notifications”**](https://help.x.com/en/managing-your-account/notifications-on-mobile-devices#:~:text=In%20the%20top%20menu,%20you,you%20would%20like%20to%20receive) for [**@API**](https://x.com/api). You can also follow this changelog in your feed reader via the [**RSS feed**](https://docs.x.com/changelog/rss.xml).
### Articles draft and publish endpoints
Today, we added [new endpoints](/x-api/articles/introduction) for drafting and publishing Articles via the X API.
### Post create and delete events for X Activity API
Today, we added `post.create` and `post.delete` events to the [X Activity API](https://docs.x.com/x-api/activity/introduction). You can now subscribe by User ID to receive real-time notifications when a user creates or deletes a Post.
For basic per-user post activity, use XAA. For advanced keyword filtering and the full set of Filtered Stream operators, continue to use the [Filtered Stream](/x-api/posts/filtered-stream/introduction).
### `paid_partnership` Post field
Added support for the `paid_partnership` field on Posts.
* When creating a Post via `POST /2/tweets`, set `"paid_partnership": true` to indicate the Post is a paid partnership (i.e., the author is disclosing that it contains paid promotion). The Post will be labeled as a paid promotion.
* When reading Posts, request `tweet.fields=paid_partnership` to retrieve the value (`true` if the author has disclosed the Post as containing paid promotion).
### Search endpoints migrating to new search index
Today, we migrated the X API v2 search endpoints (`/2/tweets/search/recent`, `/2/tweets/search/all`, `/2/tweets/counts/recent`, `/2/tweets/counts/all`) to the new X core platform search index. This brings major performance improvements, dramatically fewer 503 errors, and three new precision operators: `min\_likes:`, `min\_replies:`, and `min\_reposts:`. Note: retweets are no longer returned in keyword-based search results (the Filtered Stream is unchanged). Learn more [here](https://devcommunity.x.com/t/important-update-x-api-search-endpoints-migrating-to-new-search-index/264595).
### X API pricing update: Owned Reads now \$0.001
Effective April 20, 2026, we introduced new **"Owned Reads"** pricing at **\$0.001** per resource (1,000 for **\$1**) for qualifying endpoints when accessing your own data:\
`GET /2/users/{id}/bookmarks`, `/blocking`, `/muting`, `/pinned_lists`, `/tweets`, `/mentions`, `/liked_tweets`, `/followers`, `/following`, `/owned_lists`, `/followed_lists`, and `/list_memberships`.
We also updated writes — `POST /2/tweets` is now **\$0.015** per post, and Posts containing a URL are **\$0.20** per Post (summoned replies remain **\$0.01**).
Following, Likes, and Quote-Posts via the API have been removed from all self-serve tiers.
Learn more [here](https://devcommunity.x.com/t/x-api-pricing-update-owned-reads-now-0-001-other-changes-effective-april-20-2026/263025).
### Deprecation of Account Activity replay endpoint
Today, we announced the deprecation of `POST /2/account_activity/replay/webhooks/{webhook_id}/subscriptions/all`, effective March 25, 2026 at 12:00 PM ET. Use the new consolidated `POST /2/webhooks/replay` endpoint instead — it provides identical functionality. Learn more [here](https://devcommunity.x.com/t/deprecation-of-account-activity-replay-endpoint/260354).
### Direction filter for X Activity API subscriptions
Today, we added an optional `direction` filter to X Activity API subscriptions. Subscribers can now scope DM and chat events to `sent`, `received`, or both, reducing noise when only outgoing or incoming events are needed.
### Updates to event types format in the X Activity API
Today, we announced changes to event type naming in the X Activity API, effective March 18, 2026. PascalCase event types (e.g., `ProfileBioUpdate`) are being deprecated in favor of a dot-separated lowercase format (e.g., `profile.update.bio`). Update any filtering, switch statements, or deserialization logic that relies on the old values. Learn more [here](https://devcommunity.x.com/t/updates-to-event-types-format-in-the-x-activity-api/259765).
### Legacy Direct Message events in the X Activity API
Today, we added legacy DM events (`dm.received`, `dm.sent`, `dm.read`, `dm.indicate_typing`) to the [X Activity API](https://docs.x.com/x-api/activity/introduction). This brings DM event delivery from the Account Activity API into the lower-latency XAA pipeline.
### Addressing LLM-generated spam
Today, we made changes to reduce automated, low-quality replies on X. Programmatic replies via `POST /2/tweets` are now only permitted when the original Post's author has "summoned" the replier (by @mentioning that account or quoting one of its Posts). Additional restrictions apply to programmatically @mentioning or quoting users. These changes affect self-serve tiers only — Enterprise access is not impacted. Learn more [here](https://devcommunity.x.com/t/x-api-v2-update-addressing-llm-generated-spam/257909).
### Launch of X API Pay-Per-Use pricing
Today, we officially launched **X API Pay-Per-Use** pricing — a flexible credit-based model built for indie builders, startups, and hobbyists. Highlights:
* A new Developer Console at [console.x.com](https://console.x.com)
* The [XDK (X Developer Kit)](https://docs.x.com/xdks/overview) with first-party Python and TypeScript SDKs
* An interactive [Playground](https://github.com/xdevplatform/playground) for testing
* An [MCP server](https://github.com/xdevplatform/xmcp) for AI models
* Earn up to **20% back in xAI/Grok API credits** on every dollar spent on the X API
Public Utility Apps continue to receive free scaled access. Recently active Legacy Free tier users receive a one-time \$10 voucher. Basic and Pro plans remain available, and existing subscribers can opt in to Pay-Per-Use. Learn more [here](https://devcommunity.x.com/t/announcing-the-launch-of-x-api-pay-per-use-pricing/256476).
### Spaces events in the X Activity API
Today, we added Spaces lifecycle events (`spaces.start`, `spaces.end`) to the [X Activity API](https://docs.x.com/x-api/activity/introduction). Subscribe by User ID to be notified in real time when a Space starts or ends.
### Deprecating count-based operators
Today, we deprecated the `min\_likes`, `min\_replies`, and `min\_reposts` operators on `/2/tweets/search/recent` and `/2/tweets/search/all`. This change does not affect the equivalent operators in the Filtered Stream. We are evaluating how to best re-enable these in the future. Learn more [here](https://devcommunity.x.com/t/deprecating-count-based-operators-in-the-x-api/254933).
### OAuth 2.0 support added to Account Activity API v2
Today, we added full OAuth 2.0 support to the [Account Activity API v2](https://docs.x.com/x-api/account-activity/introduction). Developers can now create subscriptions using OAuth 2.0 with fine-grained scopes (e.g., `follow.read`) instead of the all-or-nothing OAuth 1.0a permission model. Existing OAuth 1.0a-based integrations continue to work without disruption — when present, OAuth 1.0a permissions fully override OAuth 2.0 scopes. Learn more [here](https://devcommunity.x.com/t/announcement-oauth2-0-support-added-to-account-activity-api-v2/254633).
### Introducing X API Playground
Today, we introduced the [X API Playground](https://github.com/xdevplatform/playground) — a self-hosted local server that emulates X API v2 endpoints. Develop and test integrations without making real API calls or hitting rate limits. Includes realistic mock data, state persistence, OpenAPI validation, rate-limit simulation, and a web UI. Install with `go install github.com/xdevplatform/playground/cmd/playground@latest`. Learn more [here](https://devcommunity.x.com/t/introducing-x-api-playground-local-development-tool-for-x-api-v2/253442).
### Launch of news endpoints
Today, we launched the new [News endpoints](https://docs.x.com/x-api/news/introduction) in the X API v2:
* `GET /2/news/search` — returns trending news stories matching a search query
* `GET /2/news/{id}` — looks up a specific news story by ID
Both endpoints support `news.fields` for selecting fields like `name`, `summary`, `contexts`, `cluster\_posts\_results`, and `last\_updated\_at\_ms`. Learn more [here](https://devcommunity.x.com/t/announcing-the-news-endpoints-in-the-x-api-v2/251833).
### Launch of the Python and TypeScript XDKs
Today, we launched the official first-party [Python](https://docs.x.com/xdks/python/overview) and [TypeScript](https://docs.x.com/xdks/typescript/overview) XDKs (X Developer Kits) for the X API v2. The XDKs handle authentication (Bearer Token, OAuth 2.0 PKCE, OAuth 1.0a), automatic pagination, real-time streaming with reconnect handling, and comprehensive coverage of all v2 endpoints. Install with `pip install xdk` or `npm install @xdevplatform/xdk`. Learn more [here](https://devcommunity.x.com/t/announcing-the-python-and-typescript-xdks-for-the-x-api-v2/250860).
### Keyword filtering for X Activity API subscriptions
Today, we added keyword filtering to X Activity API subscriptions. In addition to filtering by User ID, subscribers can now narrow event delivery further by keyword — useful for News events and other event types where high event volumes warrant additional filtering.
### Verified badge, affiliate badge, and handle update events in the X Activity API
Today, we expanded the [X Activity API](https://docs.x.com/x-api/activity/introduction) to deliver additional profile-related event types:
* `profile.update.verified` — when a user's verification status changes
* `profile.update.affiliate` — when a user's affiliate badge changes
* `profile.update.screenname` — when a user changes their @handle
### X API Pay-Per-Use pricing pilot
Today, we announced a limited closed pilot for a new credit-based, usage-based pricing model. Developers buy credits upfront and are charged per request — no fixed subscription fees and no monthly object caps. Initial pilot rates: $0.005/Post Read, $0.01/User Read, $0.01/DM Event Read, $0.01/Content Create, $0.01/DM Interaction, $0.015/User Interaction. Learn more [here](https://devcommunity.x.com/t/announcing-the-x-api-pay-per-use-pricing-pilot/250253).
### Launch of the X Activity API open beta
Today, we launched the open beta of the [X Activity API](https://docs.x.com/x-api/activity/introduction) — a new suite of endpoints for subscribing to real-time activity events on X with sub-second latency. Subscribe to profile event types (`ProfileBioUpdate`, `ProfilePictureUpdate`, `ProfileBannerUpdate`, `ProfileGeoUpdate`, `ProfileUrlUpdate`), filter by User ID, and receive matching events via persistent HTTP stream (`GET /2/activity/stream`) or webhooks. Subscriptions are managed via `POST /2/activity/subscriptions`. Learn more [here](https://devcommunity.x.com/t/announcing-the-x-activity-api-open-beta/250099).
### Post editing via the X API
Today, we launched the ability to programmatically edit recent Posts via the X API. Use the existing `POST /2/posts` endpoint with a new `edit_options` object containing `previous_post_id`. Requirements: the authenticated user must have X Premium, the Post must be your own, and it must have been created within the last hour. See the updated [Create or Edit Post](https://docs.x.com/x-api/posts/create-post) docs. Learn more [here](https://devcommunity.x.com/t/announcing-post-editing-via-the-x-api/249534).
### Connections API for managing active streaming connections
Today, we launched the [Connections API](https://docs.x.com/x-api/connections/introduction) for managing active streaming connections programmatically:
* `GET /2/connections` — list active and historical streaming connections
* `DELETE /2/connections/all` — terminate all active streaming connections for the app
* `DELETE /2/connections/{endpoint_id}` — terminate connections for a specific streaming endpoint
* `DELETE /2/connections` — terminate specific connections by UUID
This helps developers resolve "TooManyConnections" errors and clean up stale connections without waiting for timeouts.
### Community Notes: evaluate note endpoint
Today, we added the `POST /2/evaluate_note` endpoint to the [Community Notes API](https://docs.x.com/x-api/community-notes/introduction). AI Note Writers can now evaluate a drafted note before submission to receive signals about its potential helpfulness, claim/opinion alignment, and other model feedback.
### Launch of the Filtered Stream Webhooks API
Today, we launched the [Filtered Stream Webhooks API](https://docs.x.com/x-api/webhooks/stream/introduction), which delivers matching public Posts asynchronously to a registered webhook instead of requiring a persistent connection. Rules are managed using the existing `/2/tweets/search/stream/rules` endpoints, and matching Posts (including edit history) are delivered as JSON to your webhook. Available to Enterprise developers; supports 25,000+ rules per project with rules up to 2,048 characters. Learn more [here](https://devcommunity.x.com/t/announcing-the-filtered-stream-webhooks-api/248464).
### Removal of like and follow endpoints from Free tier
To combat abuse, platform manipulation, and fake engagement, we removed `POST /2/users/:id/likes` and `POST /2/users/:id/following` from the X API Free tier, effective immediately. Paid tiers (Basic, Pro, Enterprise) are unaffected. Learn more [here](https://devcommunity.x.com/t/update-to-x-api-free-tier-removal-of-like-and-follow-endpoints/247646).
### PowerStream rules lookup endpoint
Today, we added the `GET /2/powerstream/rules` endpoint, allowing PowerStream customers to programmatically retrieve the rules configured against their PowerStream instances.
### Broadcasting community posts via `share_with_followers`
Today, we added a new optional `share_with_followers` boolean parameter to `POST /2/tweets`. When posting with a `community_id` and `share_with_followers: true`, the community Post is also broadcast to the authenticated user's followers' timelines — matching the "Also share with followers" checkbox on x.com.
### Launch of the Community Notes API
Today, we launched the [Community Notes API](https://docs.x.com/x-api/community-notes/introduction) — a new suite of endpoints for AI Note Writers to programmatically participate in Community Notes:
* `GET /2/notes/search/posts_eligible_for_notes` — search Posts eligible to receive a Community Note
* `GET /2/notes/search/notes_written` — retrieve notes previously written by the authenticated AI Note Writer
* `POST /2/notes` — submit a Community Note
Access requires X Developer AI enrollment and Community Notes AI Note Writer approval.
### Change to DM events behavior
Today, we made a change to X API V2 DM Events behavior. With the new change participant\_ids array will only be included for ParticipantsJoin and ParticipantsLeave events, and it will list only the participants who joined or left at the time of the event. The MessageCreate event will no longer include the participant\_ids array. Learn more [here](https://devcommunity.x.com/t/upcoming-change-to-x-api-dm-events-endpoints-behavior/241841).
### Launch of Account Activity API endpoints
Today, we launched new X API v2 [Account Activity API endpoints](/x-api/webhooks/introduction). Learn more [here](https://devcommunity.x.com/t/account-activity-api-is-now-available-in-v2/242895).
### Improvements to media upload endpoint
We made a few improvements to media upload endpoint to improve the developer experience. We introduced Dedicated Endpoints for Chunked Media Upload [Media Upload endpoints](/x-api/media/introduction). Learn more [here](https://devcommunity.x.com/t/media-upload-endpoints-update-and-extended-migration-deadline/241818).
### Support for email address retrieval with OAuth 2.0
Today, we added support for email address retrieval with OAuth 2.0 in X API V2. Learn more [here](https://devcommunity.x.com/t/announcing-support-for-email-address-retrieval-with-oauth-2-0-in-the-x-api-v2/240555).
### Changes to user affiliation data
Today, we made changes to X API V2 User Affiliation Data. With the new change affiliation.user\_id will return an array of user\_ids. Earlier it used to return a single user\_id as a string, even if a user had multiple affiliations. Learn more [here](https://devcommunity.x.com/t/change-to-x-api-user-affiliation-data/237164).
### Launch of media upload endpoints
Today, we launched new X API v2 [Media Upload endpoints](/x-api/media/introduction). Learn more [here](https://devcommunity.x.com/t/announcing-media-upload-endpoints-in-the-x-api-v2/234175/3).
### Launch of new documentation site
Today, we launched our new X Developer Platform documentation site, [https://docs.x.com](https://docs.x.com).
### Launch of xurl tool
Today, we launched [xurl](https://github.com/xdevplatform/xurl), a new tool that simplifies API testing for X developers, which now supports OAuth 2.0.
### Addition of community ID tweet field
Today, we added the `community_id` Tweet Field to the X API v2. Learn more about it [here](https://x.com/tapshah21/status/1860061806653317126).
### Addition of DM blocking endpoints
Today, we added the DM blocking and DM unblocking endpoints to the X API v2.
### Support for longform posts
Today, we added the ability to create longform Posts with a length of 25k instead of 4k.
### Support for long form posts
Today, we added the ability to create long form Posts using the X API v2
### Retrieve user affiliation
Today, we added the ability to retrieve a User's affiliation programmatically using the X API v2
### Get article metadata
Today, we added the ability to get Article metadata using the X API v2
### Get profile image and cover picture
Today, we added the ability to get profile Image and cover picture URL via the X V2 API
### Addition of connection status field
Today, we added the connection\_status field in the X API v2. Learn more about it [here](https://devcommunity.x.com/t/announcing-connection-status-field-in-the-user-object-in-the-x-api-v2/212588).
### Addition of trends lookup endpoint
Today, we added the Trends lookup endpoint in the X API v2. Learn more about it [here](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567).
### Addition of users search endpoint
Today, we added the Users Search endpoint in the X API v2. Learn more about it [here](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567).
### Get DM permissions
Today, we added the ability to the get DM permissions via the X API v2. Learn more about it [here](https://devcommunity.x.com/t/dm-permissions-available-in-the-x-api-v2/209688).
### Launch of subscription type field
Today, we launched a subscription\_type field on the User object in the X API v2. Learn more about it [here](https://devcommunity.x.com/t/new-subscription-type-field-is-available-in-the-twitter-api-v2/209219/2).
### Get posts usage endpoint
Today, we launched an endpoint to programmatically get your posts usage in the X API v2. Learn more about it [here](https://developer.x.com/en/docs/twitter-api/usage/tweets/api-reference/get-usage-tweets).
### Launch of reposts lookup endpoint
Today, we launched an endpoint to lookup reposts of a post in the X API v2. Learn more about it [here](https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweets).
### Deprecation of search endpoints
Today, we are deprecating the search/tweets, users/search, and geo/search endpoints in the X API v1.1. Learn more [here](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features).
### Deprecation of Replay API endpoint
Today, we are deprecating the Replay API endpoint from the enterprise X API. You can use the [recovery](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features) feature instead.
### Deprecation of historical Powertrack endpoints
Today, we are deprecating the Historical Powertrack and Insights track endpoints from the enterprise X API.
### Removal of follows endpoints from Basic and Pro Tiers
Today, we are removing the Follows and List Follows endpoints from the Basic and Pro tiers of the X API v2.
### Removal of manage blocks endpoint
Today, we are removing the Manage Blocks endpoint from X API v2.
### Support for Bookmarks count and long posts
Today, we added support for retrieving bookmarks count and the ability to retrieve posts with more than 280 characters in the X API v2.
### Deprecation of Statuses/Filter endpoint
Today, we are deprecating the statuses/filter endpoint in the X API v1.1 Developers can use the filtered stream endpoint in the X API v2.
### Support for view counts
Today, we are adding support for view counts in the X API v2. A new field called impression\_count is made available in the public\_metrics of the post payload.
### Addition of verified type field
Today, we are adding a verified\_type user field to the X API v2 that indicates the type of verification a user account has (blue, business, government or none).
### Removal of source field
Today, we are removing the source field from the post payload in the X APIs.
### Addition of Direct Messages endpoints
Today, we are adding six v2 Direct Messages endpoints. This release includes three GET methods for retrieving Direct Message conversation events and three POST methods for creating new Direct Messages. These methods support group conversations for the first time.
Please visit our [blog post](https://developer.x.com/en/blog/product-news/2022/new-v2-direct-messages-endpoints) to learn more about this update.
### Support for edited post metadata
Today, we are adding the ability for developers to retrieve edited post metadata using the X API v2.
Please visit our [blog post](https://developer.x.com/en/blog/product-news/2022/supporting-edit-tweet-functionality) to learn more about this update.
### Addition of filtering operator aliases
Filtering/query operator "aliases" were added to search and filtered stream endpoints, across enterprise, premium, and v2. In many cases, the operator refers to posts instead of statuses, e.g. "in\_reply\_to\_tweet\_id" as an alias for "in\_reply\_to\_status\_id." In other cases, the new operator alias adds more clarity to the matching performed. For example., since posts can only have one video attachment, a new "has:video\_link" alias is provided for "has:videos." Check out the [v2 filtered stream operator table](https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule#list) to see more examples.
### Updates to reverse chronological home timeline
Beginning today, the reverse chronological home timeline v2 endpoint can return every post created on a timeline over the last 7 days and the most recent 800 regardless of the creation date.
### New filtering operators for Filtered Stream
Today, 10 new v2 filtering operators are now available to all developers building with the filtered stream endpoints, and another 10 are now more widely available.
Please visit our [blog post](https://developer.x.com/en/blog/product-news/2022/twitter-api-v2-filtered-stream) to learn more about this update.
### Updates to streaming endpoints latency
Today, we’re making updates to the streaming endpoints in the X API v2 to reduce the latency by 50%.
### Enabling v1.1 media endpoints in Essential Access
Today, we're enabling the v1.1 media endpoints in Essential access of the X API v2.
Please visit our [forum announcement](https://devcommunity.x.com/t/v1-1-media-endpoints-available-for-essential-access-in-the-twitter-api-v2/171664) to learn more about this update.
### Launch of Reverse Chronological Home Timeline endpoint
Today, we’re launching a new endpoint that enables you to retrieve a collection of the most recent posts and reposts posted by who you follow.
Please visit our [forum announcement](https://devcommunity.x.com/t/reverse-chronological-home-timeline-in-the-twitter-api-v2/171549) to learn more about this launch.
Along with the new endpoints, the variants field is now available for the [media object](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/media). This will give you the type of content attached with the URL.
### Launch of Bookmarks endpoints
Today, we’re launching new endpoints that enable you to manage and lookup Bookmarks using the X API v2. The Bookmarks feature has long been available in the X app, but until now, there hasn’t been an endpoint that allows you to retrieve, create or build solutions to manage your Bookmarks via the API.
Please visit our [forum announcement](https://devcommunity.x.com/t/build-with-bookmarks-on-the-twitter-api-v2/168804) to learn more about this launch.
### Launch of quotes lookup endpoint
Today, we’re launching the [quotes lookup endpoint](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) that lets you get the quotes for a post ID.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/introducing-the-quote-tweets-lookup-endpoint-to-the-twitter-api-v2/168370) to learn more about this launch.
### Updates to documentation navigation
We’ve heard your feedback. Finding content in our documentation could be difficult, and it was confusing when you clicked on a link and were taken to an entirely different side navigation.
Today, we’ve released an updated docs navigation that enables you to browse the full offering of the X Developer Platform from a single side navigation. With this launch, we eliminated redundant pages, removed confusing icons, and improved how you can interact with the different elements within the navigation.
If you have any feedback, please let us know via our [feedback channel](https://twitterdevfeedback.uservoice.com/forums/930250-twitter-api).
### Improvements to reposts and likes lookup endpoints
Today, we’re launching improvements to the [reposts lookup](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) and the [Likes lookup](https://developer.x.com/en/docs/twitter-api/tweets/likes/introduction) endpoints, allowing you to get back the complete list of accounts who have Liked or reposted a post, not just the last 100 accounts to do so.
To learn more about this launch, please visit our forum announcement to learn more about this launch.
### Support for OAuth 2.0 authentication
Today, all developers can now authenticate using OAuth 2.0 by selecting OAuth 2.0 as an authentication method in the Developer Console. We’ve added support for confidential and public clients and all relevant v2 endpoints to use this authentication method as part of this release.
OAuth 2.0 is an industry-standard authorization protocol that provides developers more control over an application’s scopes and improves authorization flows across multiple devices. In other words, developers building applications for people on X will have more control over the information their App requests from its users, so that you only have to ask your end-users for the data and information you need.
This modern authorization protocol will allow you to present your end-users with a more streamlined consent flow for authorizing your app, which only displays the specific scopes you have requested from them.
To learn more about this launch, please visit our forum announcement.
### Major platform updates to X API v2
**Major platform updates: X API v2 is now the primary version, new Essential and Elevated access, and Policy changes**
Today, we are announcing that X API v2 is now the primary version of the X API. We have launched enough endpoints and functionality into X API v2 to satisfy the needs of 90% of all existing Apps built on the X API.
We are launching the following changes today to further improve upon the X API v2 developer experience:
* Fast and free Essential access to the API, and free Elevated access to developers who have had their use cases approved. We have a lot more details on these access levels available on our About the X API page.
* We are removing language in our Developer Policy that restricted how you build with X’s core features, and limited the number of users you can support through your app.
* We are opening up our platform to encourage you to build tools and products that make X better, healthier, and extend the public conversation. [See a list of solutions we’d love to see you build](https://developer.x.com/en/docs/twitter-api/what-to-build).
* Specifically, we’ve removed terms that restricted replication of the X experience, including X’s core features as well as terms that required permission to have high numbers of user tokens.
* We know that building solutions that help people on X often means a developer has to build (or replicate) some of the things that are available on X. These changes to our Developer Policy are intended to drive clarity for the developer ecosystem and provide an open API platform that makes it easier for developers to build, innovate, and make an impact on the public conversation.
We go into a lot more detail on this launch and the X API launches that led to this moment in our [forum post](https://devcommunity.x.com/t/ushering-in-a-new-era-for-the-twitter-developer-platform-with-the-twitter-api-v2/162087).
In addition to exploring earlier changelog entries, we’ve put together some key resources that you can review to understand what all has released to X API v2 to-date:
* [X API endpoint map](/x-api/migrate/x-api-endpoint-map)
* [About the X API](/x-api/getting-started/about-x-api)
### Launch of list lookup endpoints
Today, we’re launching the new List lookup endpoints to X API v2. These endpoints will allow users to retrieve details on specified Lists such as followers, members, posts and more. The data retrieved can be used to build solutions that solve for curation, analysis and discoverability use cases and needs. In addition to new List endpoints, a new list: operator has been made available at the Academic Research access level. This will be available to use on search posts and post counts.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-list-lookup-endpoints-for-the-twitter-api-v2/161965).
### Additions to Spaces endpoints
We are adding functionality to the Spaces endpoint to return the list of people who purchased a ticket to a Space, as well as support for Topics.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/adding-new-functionality-to-spaces-endpoints/161959).
### Launch of manage posts endpoints
Today, we’re launching new manage posts endpoints to the X API v2. In addition to post and post delete functionality, we’ve added the ability to post polls, tag people in images, create posts with reply settings, and post to Super Followers.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-manage-tweets-endpoints-for-the-twitter-api-v2/161501).
### Changes to embedded buttons
Today, we're making some changes to X's embedded buttons. Buttons are now more rounded to match X.com buttons and we've (very slightly) updated our color palette.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/embedded-buttons-have-a-new-look/160528).
### Launch of lists endpoint group
Today, we’re launching the new Lists endpoint group to X API v2. These endpoints will allow you to build solutions that curate and organize posts based on preferences, interests, groups, or topics.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-manage-list-endpoints/159980).
### Launch of mutes lookup endpoint
Today, we’re launching the new [mutes lookup](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) endpoint to the X API v2. This endpoint will allow authenticated users to retrieve and get information on the accounts they have muted.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-new-mutes-lookup-endpoint-for-the-twitter-api-v2/159680).
### Launch of OAuth 2.0 beta
Today, we’re launching a beta of OAuth 2.0 and fine-grained scopes on the X API v2. Developers interested in shaping the future of OAuth 2.0 on the X Developer Platform, can request access to the OAuth 2.0 beta.
OAuth 2.0 is the industry standard for authentication and will allow for a more modern authorization experience.
The OAuth 2.0 beta lets you test this new functionality in a v2 Project and associated App and give us feedback before a General Availability release. However, since this implementation of OAuth 2.0 is currently in development, we strongly recommend that you refrain from testing on a public, production environment, or app.
To learn more about this launch, please visit our forum announcement.
### Launch of Batch Compliance endpoints
Today, we’re launching the new [batch compliance endpoints](https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/introduction) to the X API v2 to make it easier for developers using the X API to keep their X data in compliance with our [Developer Agreement and Policy](https://developer.x.com/en/developer-terms/policy). These endpoints allow developers and researchers to batch upload large amounts of post or User IDs and understand what action is needed to ensure that their datasets reflect user intent and the current state of the content on X.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/new-batch-compliance-endpoints-available-on-the-twitter-api-v2/158534).
### Launch of Spaces endpoints
Today, we’re launching the new [Spaces endpoints](https://developer.x.com/en/docs/twitter-api/spaces/overview) and a [new top-level Spaces data dictionary](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/space) to the X API v2. The Spaces endpoints enable you to lookup Spaces by Space ID or user ID, or using keywords, hashtags, or usernames of people mentioned in a title. The new data dictionary contains relevant information about a Space such as its title, ticketed status, and participant metrics; all user IDs can be expanded into full objects.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/introducing-new-spaces-endpoints-on-the-twitter-api-v2/158213).
### New object for video views limitation
Previously, when you requested video view metrics using the enterprise [Engagement API](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api) on posts that are older than 1800 days old, we delivered a zero value without much context. Today, we will start delivering a new object in these cases called unsupported\_for\_video\_views\_tweet\_ids, which will include a comma-separated list of post IDs that are older than 1800 days old. You will still receive all other requested metrics for these posts in a separate object.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/new-engagement-api-video-views-object-to-clarify-limitation/158163).
### Addition of alt text field
Today, we are making the alt\_text field available in the X API v2 media object, in order to enable developers to build more consciously for accessibility.
To request this field, you must pass the expansions=attachments.media\_keys parameter, as well as the media.fields=alt\_text parameter. If included in your request, this field will return the alt text for any posts that include images with alt text.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/media-alt-text-field-now-available-in-twitter-api-v2/157939).
### Launch of reposts endpoints
Today, we’re launching new [reposts](https://developer.x.com/en/docs/twitter-api/tweets/retweets) endpoints to X API v2. Developers can now use these endpoints to repost or undo a repost on behalf of an authenticated user, or to look up who reposted a given post.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-retweets-endpoints/156827).
### Launch of manage mutes endpoints
Today, we’re launching new [manage mutes](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) endpoints to the X API v2. These endpoints will allow authenticated users to mute or unmute accounts.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-new-manage-mutes-endpoints-for-the-twitter-api-v2/156261).
We have now reduced the `max_results` that can deliver with the [full-archive search](/x-api/posts/full-archive-search) endpoint when you are requesting the `context_annotations` field with the `tweet.fields` parameter to 100, meaning that you can only pull up to 100 posts with the field per page.
### Reliability features for streaming endpoints
Today, we are launching two reliability streaming features for X API v2’s filtered stream and sampled stream called backfill and redundant connections, which are now available on the Academic Research product track.
The redundant connections feature enables you to connect to a given stream two times, which can help to ensure that you maximize streaming up-time in case one of your streams experiences a disconnection.
Backfill can be utilized by adding the backfill\_minutes parameter and a whole number between one and five to your streaming request, and allows you to request missed data that might have resulted from a disconnected stream.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/new-reliability-and-recovery-functionality-available-for-twitter-api-v2-streaming-endpoints/156244/2).
### Launch of post counts endpoints
Today, we’re launching the new [post counts endpoints](/x-api/posts/counts/introduction) to the X API v2. This includes two different endpoints: Recent post counts, which is available to all product tracks, and full-archive post counts, which is currently only available to the Academic Research Product Track. You can use these endpoints to receive the count of posts that matches a specified query.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/introducing-new-tweet-counts-endpoints-to-the-twitter-api-v2/155997).
### Improvements to teams
Today, we’re launching key improvements to the functionality of teams based on feedback we’ve heard from the community. We have updated the style and design of the team page. We also made changes to the invitation flow to make it easier to invite team members or to learn more about why an invitation might have failed. If you have a team account you can check out the changes by viewing the [teams page](https://developer.x.com/en/portal/teams) of the Developer Console. To learn more about teams check out our [documentation on the subject](https://developer.x.com/en/docs/Developer%20Console/overview#team) and related [FAQ](https://developer.x.com/en/docs/Developer%20Console/faq#dev-portal-management-faq).
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-improvements-to-the-functionality-of-teams/155447/2).
### Retirement of configuration endpoint
Today, we retired the standard v1.1 GET /help/configuration endpoint.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/retiring-the-1-1-configuration-endpoint/153319).
### Consolidation of oembed endpoint
Today, we’re sharing that the v1.1 oEmbed endpoint will be retired and removed on November 23, 2021, so that new features can be supported in a consistent manner. After that date, the only official and supported API endpoint for X oEmbeds (embedded posts and timelines) will be via publish.x.com/oembed.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/consolidating-the-oembed-functionality/154690/2).
### Launch of blocks and likes lookup endpoints
Today, we’re launching the new [blocks](/x-api/users/blocks) and [Likes](/x-api/posts/likes) lookup endpoints to the X API v2. These endpoints enable you to use the v2 API to get information about which posts an account has liked, what users have liked a post, and who you or an authenticated user has blocked.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-twitter-api-v2-likes-lookup-and-blocks-lookup/154353).
### Launch of manage likes endpoints
Today, we’re launching the new [manage Likes](https://developer.x.com/en/docs/twitter-api/tweets/likes) endpoints to the X API v2. These endpoints enable you to use the v2 API to like and unlike posts.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-new-manage-likes-endpoints-for-thetwitter-api-v2/152780).
### Launch of manage blocks endpoints
Today, we’re launching the new [manage blocks](/x-api/users/blocks) endpoints to the X API v2. These endpoints enable you to block or unblock accounts on behalf of a user using user IDs.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/announcing-manage-blocks-for-twitter-api-v2/152358/2).
### Removal of support for embedded timelines
Today we’re sharing our plans for the future of [embedded timeline widgets](https://developer.x.com/en/docs/x-for-websites/timelines/overview). On June 23rd 2021, we plan to retire the Likes, Collections, and Moments timelines. We recommended you use the [Profile](https://developer.x.com/en/docs/x-for-websites/timelines/guides/profile-timeline) and [Lists](https://developer.x.com/en/docs/x-for-websites/timelines/guides/list-timeline) timelines, which we’re updating to become faster, easier to use, and more up-to-date with X features and functionality.
You can learn more about this change in our [forum announcement](https://devcommunity.x.com/t/removing-support-for-embedded-like-collection-and-moment-timelines/150313).
### Launch of manage follows endpoints
Today, we’re launching the new [manage follows](/x-api/users/follows) endpoints to the X API v2. These endpoints enable you to follow or unfollow accounts on behalf of a user using their user ID. This launch comes just a few months after the launch of the [follows lookup](/x-api/users/follows) endpoints, which allow you to retrieve an account’s followers and who they are following.
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/introducing-the-new-manage-follows-endpoints-to-the-twitter-api-v2/149465).
### Introduction of Academic Research product track
Today, we are introducing the new [Academic Research product track](/resources/fundamentals/developer-apps) to [X API v2](/x-api/introduction). This update introduces a new application process for Academic Researchers that will provide those that are approved with an Academic Research [Project](/resources/fundamentals/developer-apps) that will unlock greater access and advanced functionality.
With the new Academic Research product track, you will be able to access the following:
* The new X API v2 [full-archive search endpoint](/x-api/posts/full-archive-search), which is only available to the Academic Research product track at this time.
* An increased [post cap](/x-api/fundamentals/post-cap) of 10 million, up from the 500,000 that is available to the [Standard product track](/resources/fundamentals/developer-apps) at the Basic [access level](https://developer.x.com/en/products/x-api/early-access/guide#na_2).
* New filter operators available to [recent search](/x-api/posts/recent-search), [full-archive search](/x-api/posts/full-archive-search), and [filtered stream](/x-api/posts/filtered-stream), including `$` (aka cashtag), `bio` (only available via filtered stream), `bio_name` (only available via filtered stream), `bio_location` (only available via filtered stream), `place`, `place_country`, `point_radius`, `bounding_box`, `-is:nullcast`, `has:cashtags` and `has:geo`.
* An increased rule limit for filtered stream of 1,000 concurrent rules, up from the 25 that is available to the Standard product track at the Basic access level.
* An increased query and rule character limit of 1,024 characters long, up from the 512 character limit that is available to the Standard product track at the Basic access level
To learn more about this launch, please visit our [forum announcement](https://devcommunity.x.com/t/introducing-the-new-academic-research-product-track/148632).
### Addition of reply settings field
Today we are launching a new field in the post object called reply\_settings. This field is available on all X API v2 endpoints that return posts including post lookup, hide replies, recent search, sampled stream, filtered stream, follows lookup, user post timeline, and user mention timeline endpoints or by [expanding](/x-api/fundamentals/expansions) the post object in any endpoint.
This field indicates how the post author has allowed others to reply to their posts, whether it’s everyone, just the people they mention in the post, or those they follow. The field values returned by the `reply_settings` field include `everyone`, `mentionedUsers`, and `following`. If no conversation controls are set for the post, this will still show up in the post object with `everyone` value for the field.
### Launch of user post and mention timeline endpoints
Today, we’re launching the new [user post timeline and user mention timeline endpoints](/x-api/posts/timelines) to the X API v2. These endpoints enable you to request the posts composed by, or mentioning, a specified account on X. Learn more in the forum post announcement.
### Launch of follows lookup endpoints
Today, we’re launching the new [follows lookup endpoints](/x-api/users/follows) to the X API v2. These endpoints enable you to retrieve an account’s followers and who they are following using their user ID. Learn more in the forum post announcement.
### Retirement of Labs v2 endpoints
Retired Labs v2 recent search and hide replies endpoints
We have retired the following endpoints. If you were using the Labs versions of these endpoints, you can use the linked migration guides to update your integration to start using the new X API v2 versions:
* [Recent search v2](/x-api/posts/search/migrate/overview)
* [Hide replies v2](/x-api/posts/hide-replies/migrate)
We also have additional details about migration to the new X API v2 via our [migration hub](/x-api/migrate/overview).
If you have any questions, please reach out to our [Labs forum category](https://devcommunity.x.com/c/labs/57).
### Retirement of Labs v1 endpoints
On August 12th, 2020, we launched the new X API v2: Early access. With this release, we graduated several endpoints to X API v2 from the Labs program, and announced that the Labs version of the endpoints would remain in a deprecated state for 60 days before retiring them.
Today marks 60 days since the launch, meaning that we have retired the following endpoints. If you are using the Labs versions of these endpoints, you can use the linked migration guides to update your integration to start using the new X API v2 versions:
* post metrics v1
* Filtered stream v1
* Sampled stream v1
We also have additional details about migration to the new X API v2 via our [migration hub](/x-api/migrate/overview).
If you have any questions, please reach out to our [Labs forum category](https://devcommunity.x.com/c/labs/57).
### Addition of post consumption status bar
In the [main dashboard page](https://developer.x.com/en/portal/dashboard) of the new Developer Console, you can now check your usage towards the [post cap](/x-api/fundamentals/post-cap) of 500,000 posts per month. This cap is applied at the Project level, across the following v2 endpoints in Basic access: filtered stream, and recent search.
In order to see this feature and use the new v2 endpoints, you will need to activate the [new Developer Console experience](https://developer.x.com/en/portal/opt-in.html).
### Launch of Hide Replies endpoint
Today, we’re launching the new hide replies endpoint into the v2 X API. This endpoint enables you to hide abusive, distracting, or misleading replies to posts – a crucial piece to improving the health of the public conversation. Learn more in the forum post announcement.
The same endpoint in X Developer Labs is now deprecated, and it will be retired in 90 days. Learn how to [migrate to the v2 endpoint.](/x-api/posts/hide-replies#comparing-twitter-apis-hide-replies-endpoints)
### Early access to X API v2 endpoints
Today we announced [Early Access to the first endpoints of the new X API](https://blog.x.com/developer/en_us/topics/tools/2020/introducing_new_twitter_api.html)!
The new X API features a new API foundation which will allow us to deliver new functionality faster; an updated data format and new functionality that gives you more control over which fields you receive; new post, user, and media fields; and a set of updated endpoints that enable you to listen to and analyze posts, including the following:
* [post lookup](/x-api/posts/post-lookup-by-post-ids)
* [User lookup](/x-api/users/user-lookup-by-id)
* [Recent search](/x-api/posts/recent-search)
* [Filtered stream](/x-api/posts/filtered-stream)
* [Sampled stream](/x-api/stream/stream-sampled-posts)
You can find a full list of the new functionality available, and find migration resources on our [X API v2: Early Access docs page](https://developer.x.com/en/docs/x-api/early-access).
Learn more about what we have planned in our “[Guide to the future of the X API](https://developer.x.com/en/docs/x-api/early-access)”.
### Deprecation of Labs endpoints
We are deprecating certain Labs endpoints due to the launch of their X API v2 replacements in this release.
The following Labs v1 endpoints will be retired 60 days from today's release:
* post metrics v1
* Filtered stream v1
* Sampled stream v1
The following Labs v2 endpoint will be retired 90 days from today’s release:
* Recent search v2
### Improvements to hide replies
We added the ability to unhide a reply. Additionally, previously unhidden replies can now be hidden again via this endpoint.
Get more details in the [Hide replies documentation](https://developer.x.com/en/docs/labs).
### Retirement of Labs v1 endpoints
Today we are retiring the Labs v1 posts and users, hide replies, and recent search endpoints.
You can read more about our Labs v1 plan in our [forum announcement](https://devcommunity.x.com/t/update-on-labs-v1-endpoints/138641).
### Addition of quote tweets metric
Today, the `quote_tweets` metric is now available for 'unowned' posts via the [/totals](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api#post-insights-engagement) endpoint. This means that you can access the quote count for all posts by using app-only authentication.
You can read more about this change in our [forum post](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131).
### Addition of new post metrics
Today we are adding two new non-public metrics subfields, `user_profile_clicks` and `url_link_clicks`, to the post object in the X Developer Labs post lookup endpoints. They will be returned when using the `tweet.fields` parameter with any of the following values: `non_public_metrics`, `organic_metrics`, or `promoted_metrics`.
To learn more, please visit the [post lookup API reference](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets-id)
### Changes to repost counts
Starting today, X web, iOS and Android will be showing the total 'reposts and comments' count per post. Using the X API, the total 'reposts and comments' number matching the X interface can be calculated by adding the `retweet_count` and `quote_count` when available. Additionally `quote_count` will be the total unique accounts that have quoted the post, rather than the total posts quoting the post. For more details, please see our [forum post](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131/2).
### Organic and promoted metrics groupings
We are adding `organic_metrics` and `promoted_metrics` to the post and media objects in the post lookup endpoints.
### Addition of metrics to endpoints
We are adding metrics to the post and media objects in the post lookup and recent search endpoints.
You can read more about these changes in our [forum announcement](https://devcommunity.x.com/t/adding-metrics-to-the-tweets-and-recent-search-endpoints-in-labs/135315)
### Launch of COVID-19 endpoints
Today we are launching a new COVID-19 stream endpoint and an accompanying compliance endpoint.
You can read more about these changes in our [forum announcement.](https://devcommunity.x.com/t/new-covid-19-stream-endpoint-available-in-twitter-developer-labs/135540)
### Updates to Replay API user profiles
Starting today, the Replay API will deliver user profile objects that reflect the referenced user at the time the Replay API is running. This change to deliver current user profile objects is similar to the recent Historical PowerTrack update below from Nov. 25, 2019.
### Addition of post annotations
We are adding annotations to the post object in the posts and recent search endpoints.
You can read more about this change in our [forum announcement](https://devcommunity.x.com/t/adding-annotations-to-tweets-and-recent-search-endpoints-in-labs/135193).
### Updates to developer policy
Today, we announced a significant [update to the Developer Policy](https://developer.x.com/en/developer-terms/policy). We encourage you to read more about this via our [forum](https://devcommunity.x.com/t/a-new-easier-to-understand-twitter-developer-policy/135038) and [blog](https://blog.x.com/developer/en_us/topics/community/2020/twitter_developer_policy_update.html) posts, and to review the revised policy. The Developer Policy is one of the foundations for your use of the X API and it is important to understand your commitments.
### Launch of Hide Replies endpoint
We want to help people feel safe and comfortable having conversations on X. As part of that, today we’re excited to give post authors more control over the conversations they start by supporting the hide replies feature with a new [endpoint](/x-api/posts/hide-replies).
You can read more about this new endpoint in our [forum announcement](https://devcommunity.x.com/t/introducing-the-hide-replies-endpoint/134683).
### Release of v2 Labs endpoints
Today, we are bringing our posts and Users, Recent Search and Hide Replies endpoints to v2 of Labs. We are deprecating Labs v1 endpoints and will fully retire them 90 days after this initial release. We will also keep our v1 documentation available for this duration. You can provide us feedback on this versioning strategy via our [feedback channel](https://twitterdevfeedback.uservoice.com/).
We're releasing the following changes to posts and Users:
* Introduce [fields](/x-api/fundamentals/fields) as a query parameter
* Remove [formats](https://developer.x.com/en/docs/labs#payload) as a query parameter
* Add path variable for single ID [lookup](https://developer.x.com/en/docs/labs/overview/versioning/migration-guide#id-lookup-path) in posts and Users
* Adjusting the path and query parameters for single and multi-username [lookup](/x-api/migrate/overview#username-lookup-path) in GET /users
* Change field name `stats` to `public_metrics`
Other changes include:
* Remove the `most_recent_tweet_id` expansion in Users
* Remove HTML tags from the `source` field in posts to make that field easier to parse
The core search, pagination and other functionality of Recent Search will stay the same.
We have put together some [migration materials](/x-api/migrate/overview) for when you update from v1 to v2.
You can read more about this change in our [forum announcement](https://devcommunity.x.com/t/releasing-a-new-version-of-labs-endpoints/134219).
### Addition of drop/undrop events to Compliance Firehose
Today we added new drop/undrop event types to the Compliance Firehose API. You can read more about them in our [documentation.](/x-api/enterprise-gnip-2.0/fundamentals/firehouse)
### Changes to access token management
Today, we're making changes to the way that Access Tokens and Access Token Secrets are presented and managed within the [applications Dashboard on developer.x.com](https://developer.x.com/content/developer-twitter/en/apps).
In order to make API integrations more secure, we will no longer show the Access Token and Access Token Secret on the Dashboard beyond the first time that these values are generated.
After the first time, these credentials can not be retrieved. You will be able to regenerate the tokens on the Dashboard, but this will invalidate your current token and secret.
You can read more about this change in our [forum announcement](https://devcommunity.x.com/t/upcoming-changes-to-access-token-and-secret-management/130851).
### Removal of SPDY support
Starting January 15, 2020, all connections to the X API (and all other X domains) will no longer support SPDY connections.
You can read more about this change in our [forum announcement](https://devcommunity.x.com/t/removing-support-for-spdy-protocol-on-twitter/132530).
### Launch of recent search endpoint in Labs
Today, we are releasing a new endpoint to [search for posts posted in the last 7 days](/x-api/posts/recent-search).
Learn more about this launch via our [forum announcement.](https://devcommunity.x.com/t/new-recent-search-endpoint-available-in-labs/133076)
### Update to Twurl CLI
A new updated major release of our X API CLI, `[twurl](https://github.com/twitter/twurl)`, is now available. This release includes a number of bug fixes and enhancements and introduces Bearer Token support which helps to add functionality around the Premium and X Developer Labs endpoints. Read more in our [forum post](https://devcommunity.x.com/t/twurl-0-9-5-released/132966).
### Addition of post annotations in streams
Today in X Developer Labs, we are releasing new metadata elements to the default post payload. These new fields, rendered as part of the post payload, will provide more contextual information about the post.
Learn more about this launch via our [forum announcement](https://devcommunity.x.com/t/tweet-annotations-added-to-the-tweet-object-for-the-sampled-stream-and-filtered-stream-endpoints-in-labs/132407).
### Updates to Historical PowerTrack user profiles
Today, we’re updating our "batch historical posts" endpoint (Historical PowerTrack) to provide user profile location, bio description, and display name information that reflects values in place at the time of the job processing. When the updated user objects are delivered, there will be a new "updated" string array in the User/Actor object.
There are up to three possible values: name, description, location:
`"updated": ["name", "description", "location"]`
See the [documentation on Historical PowerTrack's data format](https://aem-author-production-version-6-3.twitter.biz/content/developer-twitter/en/docs/tweets/batch-historical/guides/powertrack-data-format.html) for more details.
### Addition to Account Activity API
Today, we’re releasing a new feature to the Account Activity API that will provide developers with the ability to view whether an account that mentions your subscribed user is blocked.
You can read more about the `user_has_blocked` [data object structure](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure) and check out our [forum announcement](https://devcommunity.x.com/t/new-release-account-activity-api-user-has-blocked-field/131157) for more details.
### Launch of sampled stream endpoint in Labs
Today, we are releasing a new endpoint to [stream a sample of all public posts](/x-api/posts/recent-search) in real-time, as they are posted.
Learn more about this launch via our [forum announcement.](https://devcommunity.x.com/t/new-sampled-stream-endpoint-available-in-labs/130958)
### Launch of Filtered Stream endpoint in Labs
Today, we are releasing a [new streaming endpoint](/x-api/posts/filtered-stream) to retrieve posts, and an endpoint to manage your filters in X Developer Labs. With these endpoints, you will be able to retrieve up to 500,000 posts per month (maximum 50 posts per second); you can set up to 10 filter rules on your stream (these can be applied at the same time).
Learn more about this launch via our [forum announcement](https://devcommunity.x.com/t/new-filtered-stream-endpoints-available-in-labs-and-the-future-of-statuses-filter/129888).
Requests parameters documented in the API reference pages are now clearly marked as either optional or required. Additionally, API reference pages will describe a JSON body payload when this is allowed by a request.
### Launch of post metrics in Labs
You can now retrieve engagement data for any post or list of posts from owned/authorized accounts. The posts you query must be no older than 30 days and cannot be reposts.
[GET /tweets/metrics/private](https://developer.x.com/en/docs/labs/tweet-metrics/overview.html) supports the following metrics:
* `impressions`
* `reposts`
* `quotes`
* `likes`
* `replies`
* `video views`
* `video view quartiles` (where the requester is also the author of the media)
Learn more about this launch via our [forum announcement](https://devcommunity.x.com/t/new-twitter-developer-labs-release-metrics-endpoint/129122).
### Changes to DM permissions
Starting today, applications that need to create Direct Messages will be required to have "Read, Write, and Direct Messages" app permissions (RW+DM). Applications attempting to create Direct Messages with only the RW app permission will receive the following error:
`{"code": 93,"message": "This application is not allowed to access or delete your direct messages."}`
You can learn more about this change via our [forum announcement](https://devcommunity.x.com/t/updates-to-app-permissions-direct-message-write-permission-change/128221).
### Addition of pinned post expansion
`pinned_tweet_id` will expand a user’s pinned post through our user object expansion.
### Addition of quote counts metadata
Developers can use the new Labs endpoints to pull counts of quotes.
### Addition of most recent post expansion
`most_recent_tweet_id` will expand a user’s most recent post through our user object expansion.
Learn more about this launch via our [forum announcement](https://devcommunity.x.com/t/update-to-twitter-developer-labs/128060).
### Requirement for TLS 1.2
Today, all connections to the X API (and all other X domains) will require TLS 1.2.
You can read more about this change in our [forum announcement](https://devcommunity.x.com/t/removing-support-for-legacy-tls-versions-1-0-1-1-on-twitter/126648/2).
### New Account Activity API endpoint
Starting today, we are introducing the new [Account Activity API endpoint](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference) to deactivate user subscriptions using application-only OAuth.
This new endpoint offers developers the convenience of only having to provide a bearer token to deactivate a subscription, without requiring the subscribed user’s access token.
We are immediately marking the existing enterprise Account Activity API endpoint used to deactivate user subscriptions with 3-Legged OAuth as deprecated. The endpoint will be retired and no longer be available starting from January 15, 2020.
Developers can learn more about this API in our [documentation](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference).
### New expansions for tweets endpoint
We added two new expansions to the [GET /tweets](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets.html) endpoint:
entities.mentions.username will expand the username of any recognized user mention in a post into a full user object.
`referenced_tweets.id.author_id` expands the ID of the author of any referenced post, when one of the posts requested is a repost, Quoted post or Reply. This expansion will also expand the referenced post ID into a full object.
### Support for tweets and users endpoints in Labs
The first two endpoints are now available via the Labs portal. Make sure you have an approved developer account and have applied for Labs access to get started with these endpoints.
[Key differences](https://developer.x.com/content/developer-twitter/en/docs/labs/overview/whats-new) from equivalent v1.1 functionality include:
* Single endpoint for single object "show" function and batch "lookups"
* Expansion parameters support the inclusion of additional objects as part of one request (e.g. mentioned users, referenced posts, e.g.)
* Format parameters support different data projections with more or less verbose payloads
* Rate limiting is at the app level, regardless of auth method (user context or bearer token)
Learn more about this launch via our [forum announcement](https://devcommunity.x.com/t/twitter-developer-labs-is-open-to-all-developers/126717).
### Retirement of terms and privacy endpoints
We have fully retired the Terms of Service and Privacy Endpoints. The current status of our [Privacy Policy](https://x.com/en/privacy) and [Terms of Service](https://x.com/en/tos) is best served by our up-to-date web pages.
You can learn more about this change via our [forum announcement](https://devcommunity.x.com/t/terms-of-service-and-privacy-endpoints-will-no-longer-serve-content-after-june-10/125714).
### Changes to user object fields
Today some user object fields, including user.lang, will start returning 'null' for updated metadata fields previously announced in our [forum post](https://devcommunity.x.com/t/upcoming-changes-to-user-object-and-get-users-suggestions-endpoints/124732).
Developers can learn about this change through our [documentation.](/x-api/fundamentals/data-dictionary/reference#user)
### Launch of Account Activity Replay API
Starting today, we are introducing the [Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity), a data recovery tool available with the enterprise tier of the [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)
The [Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) allows you to retrieve events from as far back as five days. It should be utilized to recover data in scenarios where your [webhook](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference) server misses events
Developers can learn more about this API in our [documentation](/x-api/enterprise-gnip-2.0/fundamentals/account-activity).
### Support for native media in quotes
Starting today, native media (photos, videos, and GIFs) can be added to quotes on X, which will be shown as additional media metadata in the entities sections of quote payloads.
Developers can learn more about this in our [documentation](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/tweet).
### Addition of is:reply operator
Today, the operator is:reply becomes available to use with the [enterprise search APIs](/x-api/enterprise-gnip-2.0/fundamentals/search-api) and the paid version of the [premium search endpoints](https://developer.x.com/content/developer-twitter/en/docs/tweets/search/api-reference/premium-search).
The is:reply Boolean operator can be used to filter all replies to posts, or to filter out explicit replies that match a rule. This operator functions in the same way as the is:quote operator.
Remember that, with the Search API, all ‘is:’ and ‘has:’ operators must be used in conjunction with a standalone operator like a keyword or hashtag.
You can learn more about this operator in the [documentation](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering).
### Changes to expanded URL enrichment
Today, the expanded URL enrichment will no longer contain the unwound URL object and metadata (including the title and description fields) for URLs linking to posts, Moments, or profiles. Please note that other URLs (to websites, etc.) will continue to be enriched with this metadata, and the url, expanded\_url, and `display_url` will still be available. This change applies to [Decahose](/x-api/enterprise-gnip-2.0/fundamentals/decahose-api), [PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api), [Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview), and the [Search APIs](https://developer.x.com/en/docs/x-api/v1/tweets/search/overview).
### Addition of is:reply operator in PowerTrack
Today, we are introducing a new operator, is:reply, to help you narrow conversations to those you care about most. You can now filter out replies from your results (in addition to the pre-existing ability to filter out reposts, is:retweet, and Quoted posts, is:quote). This new operator is available today within [PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api), [Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview), and [Replay](/x-api/enterprise-gnip-2.0/powertrack-api#replay-api).
The is:reply Boolean operator can be used to filter all replies to posts, or to filter out explicit replies that match a rule. This operator functions in the same way as the is:quote operator.
You can learn more about this operator in the [documentation](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering).
### Access to apps in Developer Console
Today, we've added the ability for developers to view and edit their existing [X apps](/resources/fundamentals/developer-apps) via the [X app dashboard](https://developer.x.com/content/developer-twitter/en/apps) on developer.x.com as long as they're logged into their X account. Previously, you could only view and edit your existing X apps on developer.x.com if you had applied or been approved for a [developer account](/resources/fundamentals/developer-portal).
You still must have an approved developer account to be able to create new X apps.
### Support for video subtitles
Today, we are announcing that advertisers and publishers are now able to add subtitle files (SRT) to their videos via ads.x.com, Media Studio and our publisher upload API. Subtitles will be viewable on auto-playing video (when no sound is available) on Android and Web. We will release the functionality for iOS in the coming weeks.
To read more about the new subtitles endpoints, please review their respective API reference pages:
* [POST media/subtitles-create](/x-api/media/create-media-subtitles)
* [POST media/subtitles-delete](/x-api/media/delete-media-subtitles)
### Update to Account Activity API endpoint
Today we are announcing an update to the [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) endpoint, [GET subscriptions/count](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count). To enable greater visibility into your billing details and use of the API, beginning today, you can programmatically pull the number of provisioned subscriptions associated with your Account Activity API instance within the JSON. This means you can now see both what your provisioned number of subscriptions are, and how close you are to hitting that limit via the GET subscriptions/count API endpoint.
This update has been documented with the [Account Activity API documentation](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count).
### New rate limits on POST endpoints
Today we are implementing new app-level rate limits on several of our standard POST endpoints:
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet/:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweets-id)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
You can read more about this change in our [forum announcement](https://devcommunity.x.com/t/new-post-endpoint-rate-limit-enforcement-begins-today/115355).
### Update to twitter-text library
Today, we are announcing an update to the [twitter-text](https://github.com/twitter/twitter-text) library to account for the recent changes to the way that X counts emojis. If an emoji previously counted as more than two characters, its count will now be reduced to just two characters to allow for users to make the most out of their 280 characters.
You can read more about this change in our [forum announcement](https://devcommunity.x.com/t/new-update-to-the-twitter-text-library-emoji-character-count/114607).
### Retirement of legacy DM endpoints
We have fully retired the legacy Direct Message endpoints. You can find a list of the retired DM endpoints, as well as their replacements on [this page](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference).
You can learn more about this update via our [forum announcement](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746).
### Changes to DM media access
Today, we are implementing some changes to the process where you [retrieve attached media from Direct Messages](https://developer.x.com/en/docs/x-api/v1/direct-messages/message-attachments/overview). We will no longer support accessing `media_url` or `media_url_https` via an authenticated [www.x.com](http://www.x.com) session. The request to fetch `media_url_https` MUST always be signed with the user’s access token using OAuth 1.0A.
You can learn more about this update via our [forum announcement](https://devcommunity.x.com/t/direct-message-api-change-to-how-apps-can-access-images-sent-in-direct-messages/112722).
### Retirement of user and site streams
We have fully retired [User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) and [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction).
You can learn more about this update via our [forum announcement](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746).
### New version of Usage API
Today we are launching a new version of the Usage API. With this update, we’re making the API more stable by moving to a new system.
With the system update, users will experience a data "hole" as developers will only be able to pull data back to May 1, 2018. Therefore for the upcoming year, they will be missing out on a few months of historical data (until June 2019).
A product name is changing within the Usage API from Historical PowerTrack Subscription to Historical PowerTrack 2.0 which will make the product naming consistent with the rest of our user-facing wording. Customers will receive the exact same data in the same format with the update. You will see this change within the products.type JSON object.
If you have any questions, please reach out to your account manager.
### API deprecations
The [Account Activity API DM Beta](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) product was fully retired today.
The following services and endpoints will experience degraded service starting today:
* [User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [GET direct\_messages](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/list-events)
* [GET direct\_messages/sent](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message)
* [GET direct\_messages/show](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-message)
* [POST direct\_messages/new](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/new-message)
* [POST direct\_messages/destroy](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message)
User Streams and Site Streams will be fully retired on August 23rd.
The legacy Direct Messages endpoints will be fully retired on September 17th.
You can learn more about this update via our [forum announcement](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746).
### Changes to app creation and rate limits
As of today, you will no longer be able to create new [X apps](/resources/fundamentals/developer-apps) via [apps.x.com](https://apps.x.com/). You will now be redirected to either your [Developer Console](/resources/fundamentals/developer-portal) account or, if you don't have a Developer Console account yet, to the page where [you can apply](https://developer.x.com/content/developer-twitter/en/apply-for-access).
We also announced that we will be implementing new app-level rate limits to the following POST endpoints on September 10th, 2018.
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-retweet-id)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-favorites-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
Finally, we are introducing a new option for people to report suspected violations of our platform policies to you for review.
You can learn more about all of these updates via our [blog post](https://cli.re/g32qKr).
### App management in Developer Console
If you have a [Developer Console](/resources/fundamentals/developer-portal) account, you can now create and manage your [X apps](/resources/fundamentals/developer-apps). Please read our [forum post](https://devcommunity.x.com/t/app-creation-and-management-now-available-in-the-Developer%20Console/107723) for more details.
### Changes to Sign in with X and Account Activity
Today, we started requiring that you register the [callback URLs](/resources/fundamentals/developer-apps#callback-urls) that you use with the Sign in with X process. You can read more about this update [here](https://devcommunity.x.com/t/action-required-sign-in-with-twitter-users-must-whitelist-callback-urls/105342).
We also announced the addition of the tweet\_delete\_events activity to the Account Activity API. This new activity will be sent for those corresponding deleted events to enable developers to more easily provide a compliant experience for their customers and application users. You can read more about this new activity in our [forum post](https://devcommunity.x.com/t/adding-delete-events-to-the-account-activity-api/106783) or on our [documentation](/x-api/enterprise-gnip-2.0/fundamentals/account-activity).
### Updates to terms and policies
Today, we made some changes to our [Terms of Service](https://x.com/en/tos), [Privacy Policy](https://x.com/en/privacy), and [X Developer Agreement](https://developer.x.com/en/developer-terms/agreement-and-policy) that include privacy, security, and data protection updates. Please read our [forum post](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) for more details.
### Timezone fields made private
Today, the timezone values in X user objects became private fields. From here on out, all\* time\_zone and utc\_offset data objects will return as null. Please read our [forum post](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) for more details.
\* They will continue to be available on the account/settings endpoint, for authenticated users only.
### Removal of Klout data
Today, we removed all Klout data from post payloads as part of our GDPR updates.
### Changes to profile background and Account Activity
Today, we are changing all instances of profile\_background\_image\_url and profile\_background\_image\_url\_https to their default values. Please read our [forum post](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) for more details.
In addition to the above change, we are adding a new field to the [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) payloads to reference which subscription the activity was delivered for. This JSON object is called for\_user\_id and will include the subscribed user's ID who produced that activity as its value. You can see some examples of this new JSON object in our [account activity objects](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure) page.
### Changes to quote payload rendering
Today, we are adding a change to the way that URLs will be rendered in the quote payload.
We’re adding a new entity called the "quoted\_status\_permalink" entity to ensure the quoted post can be referenced and we will be removing the t.co link from the quoted post "text" field.
With the new format, the t.co link is no longer appended to the "text" field of the quoted post in the "quoted\_status" object.
Further, we will no longer put the quoted post t.co url, expanded\_url, and display\_url in the ‘urls’ entity. Instead, these will be added to a new "quoted\_status\_permalink" object with "url", "expanded", and "display" URL attributes. This means that the "quoted\_status\_permalink" object will be reserved for the t.co link back to the quoted post, whereas the "entities.urls" array can be used to identify any links shared within the original post or quote.
Please read our [forum post](https://devcommunity.x.com/t/updating-how-urls-are-rendered-in-the-quote-tweet-payload/105473) and [updated documentation](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) for more details.
### Deprecation of X Kit
The announcement of [X Kit](https://developer.x.com/en/docs/x-for-websites) deprecation, after October 31, 2018 X Kit will no longer be actively maintained. Please read our [blog post](https://blog.x.com/developer/en_us/topics/tools/2018/discontinuing-support-for-twitter-kit-sdk.html) for more details.
### Platform updates for GDPR
Today we announced several updates to the platform related to GDPR. Please read our [forum post](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) for more details.
### Addition of additional media info object
The addition of a new object to the post payload – additional\_media\_info object – and also restricting some video details (video\_info) for promoted posts where advertisers have requested we limit video playback to X owned clients. You can find additional information about this change at the following link: [Extended Entities Objects > post with native video](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities).
### Launch of premium full-archive search
Launch of the [premium full-archive search endpoint](https://blog.x.com/developer/en_us/topics/tools/2018/access-the-full-history-of-tweets.html).
### Launch of Account Activity APIs
Launched both ([All Activities](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)) and ([Direct Messages](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)) Standard beta Account Activity APIs, read more about this launch [on our blog](https://blog.x.com/developer/en_us/topics/tools/2017/announcing-more-functionality-to-improve-customer-engagements-on-twitter.html). Announced User streams & Site streams deprecation and sunset date of Tuesday June 19, 2018.
### Update to twitter-text library
Version 2.0 of twitter-text is now available [on GitHub](https://github.com/twitter/twitter-text). This update addresses the change in our character limit that was rolled out on November 7th, 2017. To learn more about this update, please [visit our forum](https://devcommunity.x.com/t/shipped-twitter-text-2-0/98577).
### Launch of premium APIs
Launched the Premium APIs.
These new APIs build on the quality and stability of our enterprise data platform, and make it available more widely via a tiered pricing model. For the first time, you can start to search across 30 days of posts (instead of the limited 7 days of data on the standard endpoint), and optionally, you can also access our premium enrichments for profile geo, URL expansion, and poll data. Here’s a taste of some of the new features:
* More posts per request (Sandbox + Premium)
* A far more rich query language enabling more complex queries (Sandbox + Premium)
* A counts endpoint that returns time-series counts of posts (Premium)
* Metadata enrichments, such as expanded URLs and Profile Geo (Premium)
Read more about this launch [on our blog](https://blog.x.com/developer/en_us/topics/tools/2017/introducing-twitter-premium-apis.html).
### Launch of 280 character posts
Official launch of 280 character posts in languages where cramming was an issue. Please see our [forum announcement](https://devcommunity.x.com/t/updating-the-character-limit-and-the-twitter-text-library/96425) or official [blog post](https://blog.x.com/official/en_us/topics/product/2017/tweetingmadeeasier.html) for further reference.
### Removal of DM commands in Statuses/Update
The ability to send Direct Messages via the statuses/update API endpoint has been completely removed, and the `enable_dm_commands` and `fail_dm_commands` parameters will no longer have any effect. Read more about this update [on our forum](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653 "on our forum").
### Changes to OAuth login flow
A change was made to X’s backend OAuth API endpoints which altered the behaviour of the /oauth/authenticate endpoint to match that of the /oauth/authorize endpoint. Read more about this update [on our forum](https://devcommunity.x.com/t/recent-changes-to-twitter-s-oauth-login-flow-and-api-endpoints/94943).
### Updates to Engagement API metrics
The Engagement API was updated to use the same metrics aggregation methodology in use by the X analytics dashboard. Read more about this update [on our forum](https://devcommunity.x.com/t/changes-to-the-engagement-api/94523).
### Changes to DM commands failure
The default value of the `fail_dm_commands` parameter within the DM statuses/update endpoint has been switched to *true*. All status updates intended as Direct Messages will start to return errors (unless `enable_dm_commands` is *false*, in which case the post will be posted). Read more about this update [on our forum](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653).
### Treatment of 280 character tweets
The response payload for 280 character tweets will be treated the same way as long tweets. Read more about this update [on our forum](https://devcommunity.x.com/t/testing-280-characters-for-certain-languages/94126).
### Addition of additional media info
Adding new data to the post payload (`additional_media_info object`) and also restricting some video details (`video_info`) for promoted posts where advertisers have requested we limit video playback to X owned clients. You can find additional information about this change at the following link: [Extended Entities Objects > post with native video](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities)
### End of support for url\_contains operator in 30-Day Search
30-Day and Full-Archive Search ended support for url\_contains: operator. Deprecation of this operator was announced as part of the Gnip 2.0 migration in August 2016. Any Search query using the url\_contains: Operator will be rejected as invalid.
### Upcoming removal of url\_contains operator in search APIs
The 30-Day Search API (both 30-Day and Full-Archive) will no longer support the url\_contains: operator beginning 30 days from today, or after August 4, 2017 (Support of url\_contains: will actually end with the first deploy after that date). Deprecation of this operator was announced as part of the Gnip 2.0 migration in August 2016. When Operator support is ended, any query using the url\_contains: will be rejected as invalid.
### Retirement of xAuth
The xAuth authentication mechanism has been removed from all X APIs. Read more about this update [on our forum](https://devcommunity.x.com/t/retirement-of-xauth/88022).
### HTTP headers forced to lowercase
All HTTP headers have been forced into lowercase (`content-type`, `x-rate-limit-remaining`, `x-access-level` etc). Read more about this update [on our forum](https://devcommunity.x.com/t/upcoming-http-header-changes/86715).
### Optional parameters for DM commands
The optional `enable_dm_commands` parameter to statuses/update will enable applications to remove DM command support early, before the transition period ends. The default value is *true* (i.e. current legacy behavior), but this may be set to *false* to get the new, post-November 1 behavior. The optional fail\_dm\_commands parameter to statuses/update will make DM commands return HTTP 403 (error code 151) from the API when set to *true*. The default value is *false*. Read more about this update [on our forum](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653).
### Support for emojis in rules
Rules with emojis are now available in the enterprise Search APIs
### Wider availability of Direct Message APIs
Access to several new Direct Message APIs are now more widely available. Read more about this update [on our blog](https://blog.twitter.com/developer/en_us/topics/tools/2017/new-apis-to-power-the-future-of-customer-engagement-in-direct-me.html).
### Retirement of MPEG-DASH video support
MPEG-DASH URLs (.mpd) has been removed from the payload of a post that contains video. Read more about this update [on our forum](https://devcommunity.x.com/t/retiring-mpeg-dash-video-support-on-march-9th-2017/82761).
### New enrichments and payload changes
New Enrichment! Poll Metadata is now available through our enterprise APIs. See the [documentation](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) for more details.
New payload field: Image Alt-Text (description) field may be present in the entities.media\[] and extended\_entities.media\[] section of the payload if a user chooses the "Add description" option when adding a photo to a post. This is available in enriched native format only.
Default payload format: Newly created streams on Gnip products will now default to original format JSON.
### Updates to Historical PowerTrack and Replay API
Historical PowerTrack API & Replay API
* quote filtering is now supported
* Quoted posts are now fully rehydrated within HPT and Replay post payloads
### New payload fields for counts
New payload fields: quote\_count and reply\_count are now available in native enriched format payloads across Realtime and Historical APIs
### Support for geo operators in Full-Archive Search
Full-Archive Search API (FAS):
* Added support for additional geo operators:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
### Rule management by ID in PowerTrack
Rule management (GET and DELETE) by Rule ID is now available for PowerTrack 2.0 and PowerTrack Replay 2.0
### Support for geo operators in 30-Day Search
30-Day Search API:
* Added support for additional geo operators:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
# Developer Guidelines
Source: https://docs.x.com/developer-guidelines
Developer policies and guidelines for the X API, covering allowed use cases, restricted behaviors, compliance requirements, and best practices for apps.
**Violations can result in app suspension, API access revocation, or permanent account bans.** Always review the official policies before building.
Binding legal terms for API access
Rules for building on X
Specific rules for bots
Prohibited activities
***
## Quick check: is my app allowed?
Before building, ask yourself these questions. If you answer **"no"** to any of them, your app likely violates X's policies.
For interactions, did the user **explicitly request** it?
Is your app's purpose and behavior **clear to users**? (Automated accounts must be labeled.)
Can users **easily opt out** of any ongoing interactions?
Does it provide **real value** beyond self-promotion?
Are you **only using the official API** (not scraping/browser automation)?
Are you **within rate limits** and respecting usage policies?
When in doubt, ask: "Would a user be happy with this experience?" If not, reconsider your approach.
***
## Common scenarios: allowed or not?
Real-world examples to help you understand what's permitted. **These rules apply to all apps**—whether you're building a bot, mobile app, web integration, browser extension, analytics dashboard, or any other tool that uses the X API.
| Scenario | Allowed? | Why |
| --------------------------------------------------------------------- | :--------------------------: | -------------------------------------------------- |
| Automated account posts scheduled content (news, weather, quotes) | | Informational, no unsolicited mentions |
| App posts RSS feed updates on behalf of user | | Helpful broadcasting |
| Alert service posts earthquake/disaster notifications | | Public safety value |
| Sports app posts game updates to user's timeline | | Informational |
| App posts stock/crypto prices on schedule | | Informational, no manipulation |
| App posts identical content across multiple accounts | | Spam / platform manipulation |
| App posts to trending topics to gain visibility | | Trend manipulation |
| Multiple city-specific alert accounts (e.g., @WeatherNYC, @WeatherLA) | | Allowed—non-duplicative, location-specific content |
| Scenario | Allowed? | Why |
| ------------------------------------------------------ | :----------------------------------: | --------------------------------------------------------------------------- |
| App responds to @mentions asking for help | | User-initiated request |
| App auto-replies to anyone mentioning a keyword | | Unsolicited interaction |
| App auto-replies to users who reply to your post | | User engaged first—limit 1 reply. [Conditions apply](#gray-areas-explained) |
| AI-powered app generates and posts replies | | Requires **prior approval** from X |
| App replies with "follow me for more!" to random users | | Spam, unsolicited |
| Utility app that unrolls threads when mentioned | | User-initiated utility |
| Scenario | Allowed? | Why |
| --------------------------------------------------------- | :--------------------------: | ----------------------------------------------------------------------- |
| App responds to DMs with helpful info | | User-initiated |
| App sends affiliate links when user DMs first | | User-initiated—must disclose. [Conditions apply](#gray-areas-explained) |
| App auto-DMs new followers with welcome message | | Unsolicited, even to followers |
| App bulk-DMs users about a product launch | | Spam |
| Support integration asks "How can I help?" after user DMs | | User-initiated conversation |
| Scenario | Allowed? | Why |
| ----------------------------------------------------- | :--------------------------: | -------------------------------------------------------------------------------------- |
| Third-party app lets user tap a like button on a post | | User-initiated through the app |
| App auto-likes posts containing a hashtag | | Automated, not user-initiated |
| Mobile app has "auto-like" feature for selected users | | Automated, not user-initiated |
| Service sells likes or offers "bulk like" packages | | Selling engagement is prohibited |
| App reposts content from a curated list | | OK for informational purposes, no bulk spam. [Conditions apply](#gray-areas-explained) |
| Growth tool bulk-follows accounts to grow audience | | Manipulation |
| App follows back anyone who follows it | | Bulk/aggressive following |
| App adds users to lists in bulk | | Indiscriminate list manipulation |
**Likes must be directly initiated by the authenticated user.** Automated, bulk, or indiscriminate liking — including auto-liking by keyword, hashtag, user, or schedule — is prohibited. Apps may not offer "auto-like" features or sell likes as a service. This applies to all apps—bots, mobile apps, browser extensions, or any integration.
| Scenario | Allowed? | Why |
| ---------------------------------------------------- | :----------------------------------: | ------------------------------------------------------------------------------------------- |
| App sends product recommendations when asked | | User-initiated |
| App replies to random posts with affiliate links | | Unsolicited spam |
| Giveaway app that requires follows/retweets to enter | | Risky—can be seen as engagement manipulation |
| Service selling likes/follows/retweets | | Strictly prohibited |
| Tip service that sends crypto when user requests | | User-initiated—comply with financial regulations. [Conditions apply](#gray-areas-explained) |
| Scenario | Allowed? | Why |
| ------------------------------------------------- | :--------------------------: | --------------------------------- |
| App tracks brand mentions for analytics dashboard | | Valid use case |
| App scrapes X via browser automation (not API) | | **Permanent suspension**—API only |
| App stores X data to train AI/ML models | | Prohibited (except Grok) |
| App redistributes >1.5M posts in 30 days | | Exceeds redistribution limits |
| App benchmarks X performance vs competitors | | Prohibited competitive analysis |
| Academic research on public conversation trends | | Valid with proper data handling |
**Non-API automation (scraping, browser automation) results in permanent suspension.** Always use the official X API.
***
## Prohibited activities
These activities will get your app suspended or permanently banned. There are no exceptions.
| Category | Examples |
| ----------------------------- | ------------------------------------------------------------------------------------ |
| **Spam & Manipulation** | Identical content across accounts, fake engagement, trend manipulation, bulk posting |
| **Unsolicited Outreach** | Auto-replies to random users, bulk DMs, uninvited @mentions |
| **Deceptive Bots** | Impersonating humans, hiding bot identity, misleading links/redirects |
| **Engagement Selling** | Apps that sell likes, follows, retweets, or views |
| **Rate Limit Abuse** | Exceeding limits, designing apps that encourage overuse |
| **Non-API Automation** | Browser scripting, scraping, any automation outside official API |
| **Account Farms** | Multiple accounts for same duplicative purpose |
| **Surveillance** | Profiling, tracking, or monitoring users without consent |
| **Unauthorized AI Training** | Using X data to train ML models (Grok excepted) |
| **Sensitive Data Derivation** | Inferring health, political, religious, or other sensitive attributes |
| **Excessive Redistribution** | Sharing >1.5M Post IDs per 30-day period |
***
## Automation rules
This section applies specifically to **automated accounts** (bots) that post, reply, or interact on behalf of users. If you're building an analytics dashboard, research tool, or other non-automated app, these labeling requirements don't apply to you—but the technical restrictions still do.
### Requirements for automated accounts
All automated accounts using the X API must meet these requirements:
This label appears under your bot's name/handle on its profile. Enable it in your app settings to ensure transparency.
State clearly that it's a bot and who operates it. Example: *"Bot by @yourcompany"* or *"Automated account managed by Example Inc."*
For accountability and contact purposes, your bot must be associated with a human-managed account.
If a user says "stop," stop. Implement keyword detection for common opt-out phrases.
No scraping, browser automation, or unofficial methods. Violations result in permanent suspension.
Don't try to circumvent or abuse rate limits. Design your app to handle limits gracefully.
### Automated actions: what's allowed?
| Action | Allowed? | Rules |
| ------------------- | :----------------------------------: | -------------------------------------------------------------------------------------------- |
| **Post tweets** | | No unsolicited @mentions. No identical cross-posting. |
| **Reply to users** | | Only if user engaged first. Max **1 reply per interaction**. |
| **Send DMs** | | Only after user DMs you first. Easy opt-out required. |
| **Like posts** | | Must be directly user-initiated. Auto-liking, bulk liking, and selling likes are prohibited. |
| **Repost** | | OK for informational/entertainment. No bulk spam. |
| **Quote tweet** | | Same rules as repost—no spam or manipulation. |
| **Follow/Unfollow** | | No bulk, aggressive, or automated following. |
| **Add to Lists** | | No bulk or indiscriminate additions. |
| **Bookmark** | | Fine for personal/automated use. |
| **Search/Read** | | Standard use within rate limits. |
***
## Gray areas explained
Many developers have questions about edge cases. Here's guidance on common gray areas.
**Allowed if:**
* User explicitly requests it (e.g., DMs asking for a recommendation)
* You clearly disclose the affiliate/sponsored relationship
* Links are not misleading (no deceptive redirects)
**Not allowed if:**
* You auto-reply to random posts with affiliate links
* You DM users who didn't ask
* You hide the commercial relationship
* **Requires prior approval from X** before deployment
* Must still follow all rules (no unsolicited mentions, properly labeled)
* Contact X via the [Policy Support form](https://help.x.com/forms/platform) before launching
* Even with approval, cannot impersonate humans
Deploying AI-generated replies without approval is a violation, even if the content itself is helpful.
**Not allowed** as automated DMs—this counts as unsolicited contact, even though they followed you.
**Alternatives:**
* Pinned tweet welcoming new followers
* Bio with intro info and links
* Auto-reply only if they DM you first
**Allowed if:**
* Each account serves **non-duplicative** purposes (e.g., @EarthquakeJP, @EarthquakeCA)
* Content is meaningfully different (location-specific, language-specific)
* Not used to bypass limits or amplify the same message
**Not allowed if:**
* Posting identical/similar content across accounts
* Created to evade suspensions or rate limits
**Allowed if:**
* User initiates (mentions you, DMs you, or explicitly opts in)
* Clear opt-out mechanism exists
* Responses are helpful, not promotional
* Includes privacy policy link in DMs
**Not allowed if:**
* You reach out to users who complained publicly (unsolicited)
* Responses are primarily promotional
**Proceed with caution:**
* Requiring follows/retweets as entry can be seen as engagement manipulation
* Must comply with [X's contest guidelines](https://help.x.com/en/rules-and-policies/x-contest-rules)
* Don't use multiple accounts to amplify
* Ensure prizes are real and delivered
Consider entry methods that don't require engagement actions, like replying with a specific phrase.
***
## Data handling and display requirements
These requirements are legally binding under the Developer Agreement. Non-compliance can result in termination and legal action.
### Content deletion
You must delete X Content from your systems when requested:
| Trigger | Deadline |
| --------------------------------- | --------------------------------------------- |
| X requests deletion | **24 hours** |
| User requests deletion | **24 hours** |
| Content is suspended/removed on X | **24 hours** |
| Your API access is terminated | **10 business days** (must delete all X data) |
Use [Compliance Firehose](https://docs.x.com/x-api/compliance/streams) to receive real-time deletion events and stay compliant automatically.
### Off-X matching
**Off-X matching** means associating X data (username, user ID, posts) with off-platform identifiers (your customer database, email lists, device IDs, etc.).
**Allowed with express opt-in consent:**
* User explicitly agrees to link their X account with your service
* Clear disclosure of what data will be matched and why
**Without consent, you may only match:**
* Information the user directly provided to you
* Publicly available X data (posts, bio, display name, username)
* Public resources like professional directories
**Never match if it would surprise the user.**
### Sensitive data
You **cannot** derive, infer, or store information about X users in these categories:
| Category | Examples |
| ------------------------------- | -------------------------------------------- |
| **Health** | Medical conditions, pregnancy, disabilities |
| **Financial status** | Negative financial condition, credit issues |
| **Political** | Party affiliation, political beliefs, voting |
| **Racial/Ethnic** | Origin, ethnicity |
| **Religious/Philosophical** | Beliefs, affiliations |
| **Sex life/Sexual orientation** | Any inference about sexuality |
| **Trade union** | Membership or affiliation |
| **Criminal** | Alleged or actual criminal activity |
**Exception:** Aggregate analysis without storing personal identifiers (no user IDs, usernames, or linkable data) may be allowed for research purposes, subject to applicable laws.
### Displaying X content
| Requirement | Details |
| -------------------- | -------------------------------------------------------------------------------------------------------- |
| **Attribution** | Use proper X branding. Follow [Brand Guidelines](https://about.x.com/en/who-we-are/brand-toolkit). |
| **No alterations** | Only modify for display formatting (resizing). Don't edit content, remove timestamps, or strip metadata. |
| **No iframes** | Don't display X Content in iframes. Use official embeds or render directly. |
| **Respect removals** | Remove content within 24 hours if deleted on X. |
***
## Technical restrictions
These limits apply to all developers. Exceeding them can result in rate limiting or suspension.
| Restriction | Limit |
| ----------------------------------- | ------------------------------------------------------------------------- |
| **Post ID redistribution** | Max 1.5M Post IDs per 30-day period to any single entity |
| **Hydrated content redistribution** | Max 50,000 hydrated Posts or Users per recipient per day |
| **Rate limits** | Vary by endpoint and tier—[see API docs](/x-api/fundamentals/rate-limits) |
| **AI/ML training** | Prohibited (except for Grok) |
| **Non-API access** | Prohibited—scraping and browser automation = permanent ban |
| **Competitive benchmarking** | Prohibited—can't measure X performance vs. competitors |
| **Multiple apps for same use case** | Prohibited—don't create duplicate apps to bypass limits |
### Special use cases
| Use Case | Requirement |
| ------------------------------------ | ---------------------------------------------------------------- |
| **Government use** | Requires Enterprise tier |
| **Commercial use** | Requires appropriate paid tier; free tier is non-commercial only |
| **Academic research** | May have different redistribution limits; contact X for details |
| **EU Digital Services Act research** | Specific non-commercial research provisions available |
***
## Security and compliance
Your obligations as a developer:
* Use **industry-standard security** practices to protect X data
* Never share your API credentials or tokens
* Store credentials securely (environment variables, secret managers—not in code)
* Implement proper authentication in your apps
If you experience a security breach involving X data:
* **Notify X immediately**
* Take steps to mitigate the breach
* Cooperate with X's investigation
* Treat any non-public information from X as confidential
* Don't disclose API rate limits, internal X data, or non-public features
* Don't use confidential info for competitive purposes
* X may audit your compliance **up to once per year**
* You must provide reasonable access and documentation
* Keep records of how you use X data
***
## Summary: do's and don'ts
**For Automated Accounts:**
* Enable "Automated" profile label
* Disclose operator in bio
* Wait for users to initiate interaction
* Provide easy opt-out
* Get approval for AI-generated replies
**For All Apps:**
* Use only the official X API
* Respect rate limits and redistribution limits
* Delete content within 24 hours when requested
* Get opt-in consent for off-X matching
* Use proper attribution when displaying X Content
* Secure your credentials and notify X of breaches
* Keep records of your X data usage
**For Automated Accounts:**
* Hide automated nature
* Send unsolicited DMs, replies, or @mentions
* Ignore "stop" requests
* Post identical content across accounts
* Auto-like, bulk-like, or sell likes (likes must be user-initiated)
**For All Apps:**
* Scrape or use browser automation
* Train AI/ML models on X data (except Grok)
* Derive sensitive user data (health, politics, religion, etc.)
* Match X data to off-platform IDs without consent
* Display X Content in iframes
* Redistribute more than limits allow
* Create multiple apps for the same use case
* Use X data for surveillance or user tracking
# Policies and agreements
Source: https://docs.x.com/developer-terms
X developer policies, agreements, and display requirements, covering the Developer Agreement, Developer Policy, Ads API agreement, and restricted use cases.
## Overview
Developer use of X materials and content is subject to and governed by our Developer Policy and agreements.
# Ads API Agreement
Source: https://docs.x.com/developer-terms/ads-api-agreement
The X Ads API Agreement governs use of X advertising endpoints, including allowed integrations, restrictions, and obligations for advertising partners.
We have updated our Ads API Agreement. The changes below are effective as of February 23, 2025.
## X Ads Products and Services Agreement
**Effective: February 23, 2025**
This X Ads Products and Services Agreement (the “**Agreement**”) is made and entered into by and between the entity identified in the “X Ads API Program” application form submitted to X by such entity (or its authorized representative) (referred to herein as “**Company**”) and X Corp., if Company is outside of the European Union, EFTA States, or the United Kingdom, including if your Company is in the United States of America, or X Internet Unlimited Company, if Company is in the European Union, EFTA States, or the United Kingdom, on behalf of itself and its Affiliates (as defined below) (in either case, “**X**”) and governs Company’s access to and use of the Ad Products (as defined below). As used herein, “**Affiliate**” means any other entity that directly or indirectly controls, is controlled by, or is under common control with X.
PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY, INCLUDING, WITHOUT LIMITATION, ALL EXHIBITS ATTACHED HERETO AND ANY LINKED TERMS AND CONDITIONS APPEARING OR REFERENCED BELOW, WHICH ARE HEREBY MADE PART OF THIS AGREEMENT. BY CHECKING THE BOX LABELED “Yes, I Agree” AND CLICKING “SUBMIT” (OR LANGUAGE THAT IS THE EQUIVALENT OF “Yes, I Agree” SUCH AS, FOR EXAMPLE ONLY, “I Accept”) OR USING THE X MATERIALS, COMPANY IS AGREEING THAT COMPANY HAS READ, AND THAT COMPANY AGREES TO COMPLY WITH AND TO BE BOUND BY, THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF COMPANY DOES NOT AGREE TO BE BOUND BY THIS AGREEMENT, THEN COMPANY MAY NOT ACCESS OR OTHERWISE USE THE X MATERIALS. THIS AGREEMENT IS EFFECTIVE AS OF THE EARLIER OF: (I) THE DATE COMPANY CHECKS “Yes, I Agree” AND CLICKS “SUBMIT” TO ACCEPT THIS AGREEMENT, OR (II) THE FIRST DATE THAT COMPANY ACCESSES THE X MATERIALS (“**EFFECTIVE DATE**”). IF AND TO THE EXTENT, HOWEVER, THAT COMPANY’S APPLICATION TO ACCESS AND USE THE X MATERIALS IS NOT APPROVED BY X (IN ITS SOLE AND ABSOLUTE DISCRETION), THIS AGREEMENT WILL BE NULL, VOID AND OF NO EFFECT. IF YOU ARE AN INDIVIDUAL REPRESENTING COMPANY, YOU ACKNOWLEDGE, REPRESENT, AND WARRANT, THAT YOU (A) HAVE READ AND UNDERSTAND THIS AGREEMENT, (B) HAVE THE APPROPRIATE AUTHORITY TO ACCEPT THIS AGREEMENT ON BEHALF OF COMPANY, AND (C) YOU AGREE, ON BEHALF OF COMPANY, TO THE TERMS OF THIS AGREEMENT. YOU MAY NOT USE THE X MATERIALS AND MAY NOT ACCEPT THIS AGREEMENT IF YOU DO NOT HAVE THE LEGAL AUTHORITY TO BIND COMPANY, ARE NOT OF LEGAL AGE OR ARE OTHERWISE UNABLE TO FORM A BINDING CONTRACT WITH X, OR YOU ARE BARRED FROM USING OR RECEIVING THE X MATERIALS UNDER APPLICABLE LAW.
### 1. Introduction; Scope; Individual Product Terms.
**1.1 Introduction.** X maintains, operates, and offers a suite of products and services that enable various functionalities for X’s advertising partners. The specific products, services and programs (each, an “**Individual Product**”) that enable or are related to these functionalities are: (i) the X Ads API Program (as further described in [Exhibit A](#Exhibit-A)); and (ii) X’s Custom Audiences Program (as further described in [Exhibit B](#Exhibit-B)). Collectively, these Individual Products are referred to herein as the “**Ads Products**”. This Agreement governs the use of, and/or access to, the Ads Products collectively, and the Individual Products individually. In addition, to the extent that Company participates in the X Marketing Partner (“**TMP**”) program in connection with an Ads Product covered under this Agreement, the terms and conditions set forth in [Exhibit C](#Exhibit-C) will apply to Company.
**1.2 Scope.** Subject to this Agreement, during the Term, Company may access and use the specific Individual Products to which X has granted or provided Company with access. Company is under no obligation to use any or all of the Individual Products to which X has granted or provided Company with access, and X is under no obligation to provide (nor continue to provide) Company with the use of, and/or access to, any given Individual Product or feature of the Ads Products. X may grant or deny use of and/or access to any given Individual Product, or any feature thereof, at any time at X’s sole discretion. To the extent that Company accesses or uses any feature of the Ads Products, the terms of this Agreement will govern any such access or use. For the avoidance of doubt, this Agreement shall solely govern Company’s use of the Ads Products described herein. Access and use by Company of any data, content or other materials provided (directly or indirectly) by X to Company under a separate agreement and/or in connection with a separate X program shall be governed wholly by the terms and conditions of such separate agreement and/or program (and not the terms and conditions of this Agreement), unless otherwise mutually agreed in writing by X and Company.
**1.3 Individual Product Terms.** Each Individual Product may include specific terms and conditions that, in addition to and without limitation of the terms of this Agreement, will be applicable to the extent that Company accesses or uses the given Individual Product. Company’s access to any given Individual Product and/or the associated X Materials (as defined below) is conditioned upon Company’s acceptance of, and compliance with, the Individual Product Terms and any technical limitations on access, calls, and use of the Individual Products. The Individual Product Terms are attached hereto as [Exhibit A](#Exhibit-A) and [Exhibit B](#Exhibit-B). X may establish and modify such Individual Product policies or terms in X’s sole discretion, as set forth in Section 15.15 below.
### 2. Definitions.
**2.1** "**Campaign**" means a desktop, mobile website, or mobile application advertising campaign, or fraction thereof.
**2.2** "**Client**" means a X advertiser (who is also a Company customer) that utilizes one (1) or more of the Ads Products, as approved by X in each instance.
**2.3** "**Company Marks**" means Company’s name and any Company logos, trademarks and/or service marks supplied by Company to X for use hereunder (or otherwise authorized by Company for X’s use hereunder).
**2.4** "**Company Materials**" means any Company data, deliverables, or user content provided by Company to X via the Ads Products.
**2.5** "**Company Service**" means Company’s websites, applications and other offerings that display or otherwise use X Materials or aspects thereof.
**2.6** "**Data**" means metrics, data and any other information and/or content X makes available to Company, including any results, usage statistics, data or other information (in the aggregate or otherwise) derived from analyzing or using any of the foregoing.
**2.7** "**End Users**" means an employee or authorized agent of a Client who uses the Ads Products on behalf of such Client.
**2.8** "**Marks**" means the X Marks and/or Company Marks, as the case may be (based on context).
**2.9** "**Materials**" means X Materials and/or Company Materials, as the case may be (based on context).
**2.10** "**Personal Data**" means data relating to a living individual who is or can be identified either from the data or from the data in conjunction with other information that is in, or is likely to come into, the possession of the data controller.
**2.11** "**X Ads**" means X advertising products and services, including the placement of advertisements on the X Network.
**2.12** "**X Code**" means computer code that will call (at a minimum) a X server, developed by X and provided to Company.
**2.13** "**X Marks**" means X’s name and any X logos, trademarks and/or service marks supplied by X to Company for use hereunder (or otherwise authorized by X for Company’s use hereunder).
**2.14** "**X Materials**" means any X data, deliverables, or user content (including derivatives thereof) generated by X, and any X data, deliverables, or user content (including derivatives thereof) generated, collected or developed by X, or that is provided or made available to Company by X pursuant to this Agreement, including any data derived from, based upon, or arising out of, Company’s partnership with X, or any device-level data, or any conversion, engagement, tracking or targeting data that Company or any X-approved third party collects, infers, derives, or obtains from or in connection with Company’s X advertising campaigns. For clarity and without limitation, “X Materials” includes the X Ads API (as defined in [Exhibit A](#Exhibit-A)), X Code, Data, the Ads Products, and any X user ID used to create a Custom Audience (defined below).
**2.15** "**X Network**" means the network of advertising channels, including all forms of media, applications, and devices, through which X may distribute ads, in any medium now known or hereafter developed.
**2.16** "**X Marketing Partners Program**" means the partnership and branding program offered by X, as further described in [Exhibit C](#Exhibit-C).
**2.17** "**X Service**" means: (i) real-time content and information services operated by X, (ii) the technology and systems that enable such services, which includes, collectively, the consumer and advertising products and services currently provided by X or at its websites, and X-owned, operated and/or controlled mobile applications and social plug-ins and APIs, including, without limitation, the Measurement Code, any HTML tags or other codes, internet portals, dashboards, systems and analytic tools and related services, and (iii) all other products or services offered by X and its Affiliates, including (without limitation and for example only) the X Audience Platform and Data & Enterprise Solutions.
### 3. X Ads/Campaign Management; Liability Assumption.
**3.1 X Ads/Campaign Management.** Company may have access to one or more Individual Products that will allow Company, in Company’s sole discretion and/or at the direction of Company’s Clients, to optimize, modify, manage, initiate or manipulate X Ads on the X Network, or otherwise make ad management and targeting decisions (referred to herein as “**Campaign Management**”). If Company accesses or uses any such Individual Products: (a) Company must promptly provide any advertising materials it intends to post to the X Network; and (b) Company authorizes X to place Company and/or Client’s advertising materials on any content or property available through the applicable Individual Product, whether such content or property is provided on the X Network or through a third party. Company will obtain the necessary licenses and authorizations from the applicable Client for Company to use such advertising materials on behalf of such Client. Company is not required to use any Individual Product that permits Campaign Management, but if Company uses any such products, services or features, then Company hereby assumes any and all risk, and accepts any and all responsibility and liability arising out of or in connection with Company’s Campaign Management, including but not limited to: (i) audience creation and selection, data entry errors, tactic selection, and associated inventory, data, and other third-party costs; (ii) properties to which any ads provided by Company directs viewers (e.g. landing pages) and any redirects therefrom; (iii) services and products advertised in any landing pages; and (iv) any associated Company Materials including without limitation, the advertising materials, technology, and/or creative provided to X. Company hereby acknowledges and agrees that X shall bear no responsibility or liability in connection with Company’s Campaign Management. Without limiting the generality of the foregoing, X shall not be responsible, and Company shall be solely responsible, for training Company’s personnel in Campaign Management and the Ads Products functionality.
**3.2 Binding of Clients to these Terms; Liability Assumption.** If Company accesses or uses the Ads Products (or any aspect thereof, including by Campaign Management) on behalf of Clients or any other third parties, Company warrants that it: (i) is authorized to act on behalf of such Clients or other third parties, and has bound such Clients or other third parties to the applicable Our Policies (as defined in Section 6 below), including the applicable X Master Services Agreement (“**MSA**”), which shall govern all purchases of X Ads made by Company, and the terms of this Agreement that apply to the access and use of the applicable Ads Products (or any aspect thereof) and (ii) will be responsible for their compliance with, and liable for their breach thereof.
### 4. Privacy.
**4.1 Direct Data Gathering.** Company represents and warrants that (i) in the event Company is collecting data from users directly (including, without limitation, on or through the Company Service), it has provided such users with legally-sufficient notice (including, without limitation, by conspicuously posting a legally-sufficient privacy policy from all websites, mobile applications, and other services from which data from users are collected and/or made available to X that complies with all applicable laws and regulations, discloses the fact that third parties collect information about users’ activities on or through the relevant websites, mobile applications, and other services (e.g., browsing or shopping) for interest-based advertising purposes, and provides users with legally sufficient instructions for such users to opt out of interest-based advertising); (ii) it has obtained all legally-required informed consent from such users, including regarding Company’s use of cookies and/or tracking pixels in connection with such data collection; and (iii) the Company Materials do not contain or relate to, and any audience data provided, made accessible, or imported by Company to X does not contain or relate to, any data pertaining to any user(s) or data subject(s) who has or have exercised an option to opt-out of receiving interest-based advertising.
**4.2 Personal Data.** Company represents and warrants that Company will not, and will not attempt to, connect or combine any X Materials either directly or indirectly with any Personal Data or to identifiers that are themselves directly or indirectly associated with any Personal Data. In addition, Company will put reasonable safeguards in place to prohibit X Materials from being linked to any Personal Data (whether directly or by inference).
**4.3 Privacy Compliance.** Company represents and warrants that (i) it will not provide X with Company Materials relating to sensitive information, including alleged or actual commission of a crime, health, negative financial status or condition, political affiliation or beliefs, racial or ethnic origin, religious or philosophical affiliation or beliefs, sex life, or trade union membership, or collected from websites, mobile applications, or other services where the product, message, or service that is being offered is prohibited by X’s Ads policies ([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies)), and (ii) it will not (1) provide X with any Company Materials regarding children under the age of thirteen (13), or (2) send X any Company Materials or other data from a website, mobile application or online service directed to children, as defined in the Children’s Online Privacy Protection Act, currently at 16 CFR 312. Company acknowledges and agrees that it will at all times comply with the terms of the X Data Processing Addendum located at [https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa).
**4.4 Third Party Data.** Company represents and warrants that, in the event Company is obtaining data about users indirectly from one or more third parties (including, without limitation, data partners and/or advertisers, including, without limitation, Clients) to support Company’s performance obligations vis-à-vis X under this Agreement, it has contractually bound each such third party to the requirements contained in this Agreement including, without limitation, in this Section 4.
### 5. Ownership; License; Limitations and Restrictions.
**5.1 Ownership.** As between Company and X, Company retains all worldwide right, title and interest in and to the Company Materials, Company Marks, and the Company Service, excluding any X Materials, X Marks and X Service (and any derivative works or enhancements of any of the foregoing) incorporated therein, including but not limited to all intellectual property rights therein. Any rights not expressly granted herein are withheld. As between Company and X, X owns all worldwide right, title and interest in and to the X Materials, X Marks, and X Service and all future improvements, developments, enhancements, derivative works, and related rights based upon, related to, arising from, or associated with the (i) X Materials, (ii) the X Marks, and (iii) the X Service, including where such improvements, developments, enhancements or derivative works are created by using or referencing data, insights, information, or learnings derived from any Company Materials in accordance to the terms of this Agreement, or data related to the Company advertising activity on the X Service), including but not limited to all intellectual property rights therein.
**5.2 License to Company.** During the Term (including, any Wind-Down Period), to the extent that Company uses, or has access to, the Ad Products (or any aspect thereof), X hereby grants to Company a limited, royalty-free, non-exclusive, non-sublicensable, non-transferrable right and license to use and maintain any X Materials and X Marks that X may provide to Company under this Agreement solely if and as necessary to use the Ads Products (or any Individual Product) which X provides or makes accessible to Company, and to exercise its rights and fulfill its obligations under this Agreement, in each instance in accordance with the terms of this Agreement (including without limitation the restrictions and/or limitations on the use of X Materials). Company agrees that its use of the X Marks will at all times comply with the X Trademark Guidelines (defined below in Section 6).
**5.3 License to X.** During the Term (including, any Wind-Down Period), if Company uses, or has access to, the Ad Products (or any aspect thereof), Company grants to X a royalty-free, non-exclusive, sublicensable, non-transferable right and license to use, copy, display, maintain, transfer, modify, duplicate, and transmit the Company Materials and the Company Marks as necessary to fulfill Company instructions (including without limitation via the purchase and/or placement of ads on any ad inventory accessible on the X Network), to operate the Ad Products (or any Individual Product), and to exercise its rights and fulfill its obligations under this Agreement, in each instance in accordance with the terms of this Agreement.
**5.4 Limitations and Restrictions.**
5.4.1 X Materials are being provided to Company, and Company Materials are being provided to X, solely for the use of and/or provision of the Ads Products and for any other purpose expressly permitted under this Agreement.
5.4.2 Except as expressly permitted under this Agreement or unless otherwise mutually agreed in writing in advance by X and Company, Company shall not, nor allow any other party (including Clients) to, exploit, duplicate, copy, modify, derive, and/or re-use any X Materials, or any information, data, or insights derived from X Materials for any internal or external purpose (including, but not limited to, ad targeting, ad optimization, remarketing, behavioral targeting, retargeting, redirecting, or creating or augmenting in any manner groupings of users or devices segments, or creating or appending end user profiles, including those associated with any mobile device identifier or other unique identifier connected to any end user, computer, browser or device, or redirecting a user with advertising via advertising networks or exchanges, data brokers or any other advertising or monetization services). Further, Company will not use X Materials for identifying or re-identifying users in any way whatsoever (including by combining X Materials or data derived therefrom with data derived from third party sources).
5.4.3 Company may not, nor allow any other party (including Clients) to, incorporate any X Materials (including, without limitation, computer code, pixels, tags, or any other digital products provided by X to Company) into another product or service (except as necessary for the performance of this Agreement and permitted by the terms and conditions of this Agreement), translate, modify, reverse engineer or reverse compile, disassemble, make derivative works of, or otherwise attempt to discover any source code, underlying ideas, or algorithms of any X Materials without X’s express written permission.
5.4.4 Company will not, nor allow any other party (including Clients) to, interfere with, modify, disrupt or disable features or functionality of any X Materials, including without limitation any mechanism used to restrict or control the functionality, or defeat, avoid, bypass, remove, deactivate or otherwise circumvent any software protection or monitoring mechanisms of the X Materials.
5.4.5 Company will not, nor allow any other party (including Clients) to, sell, rent, lease, sublicense, distribute, redistribute, syndicate, create derivative works of, assign or otherwise transfer or provide access to, in whole or in part, the X Materials to any third party except as expressly permitted herein.
5.4.6 Company will not, nor allow any other party (including Clients) to, remove or alter any proprietary notices or marks in or on the X Materials.
5.4.7 Company will not, nor allow any other party (including Clients) to, provide use of the X Materials on a service bureau, rental or managed services basis or permit other individuals or entities to create links to the X Materials or "frame" or "mirror" the X Materials on any other server, or wireless or Internet-based device, or if applicable, otherwise make available to a third party, any token, key, password or other login credentials to the X Materials.
5.4.8 Company will not, nor allow any other party (including Clients) to, use the X Materials for any illegal, unauthorized or other improper purposes.
5.4.9 Company may not, nor allow any other party (including Clients) to, share the X Materials (including, without limitation, Data) with any third party (whether verbally or in writing), including any of Company’s clients or business partners or any Company personnel unrelated to the Ads Products, except if and as explicitly outlined herein, or as permitted by X in advance in writing (email accepted).
5.4.10 Company may not, nor allow any other party (including Clients) to, co-mingle or otherwise create any combined display of X Materials with Company Materials, data, content or other materials received from X under a separate agreement, or any other third-party materials or across advertising campaigns, except if and as expressly detailed herein or as approved by X in writing in advance.
5.4.11 Company may not, nor allow any other party (including Clients) to, offer or provide the Company Service and/or the X Materials as part of an advertising network and may not enable any programmatic export or otherwise enable machine consumption of X Materials by or to any third party (including, without limitation, Clients) without X’s prior written consent.
5.4.12 Company may not, nor allow any other party (including Clients) to, encourage or require users to engage with any Ads Products in such a fashion that may be misleading or deceptive to the user accessing the X Network, which may include methods such as offering incentives, points, rewards, cash, prizes, or anything else of monetary value, or any other methods that are malicious or fraudulent.
### 6. Incorporated Terms.
Company’s access to any given Individual Product and/or the associated X Materials is conditioned upon Company’s acceptance of, and compliance with, the following policies (collectively, the "**X Policies**"), each solely to the extent applicable to the Individual Product and X Materials that Company is accessing and/or using:
**6.1** Privacy Policy ([https://x.com/privacy](https://x.com/privacy))
**6.2** Terms of Service ([https://x.com/tos](https://x.com/tos))
**6.3** Applicable X Master Services Agreement ([https://legal.x.com/ads-terms/us.html](https://legal.x.com/ads-terms/us.html)) ([https://legal.x.com/ads-terms/international.html](https://legal.x.com/ads-terms/international.html)) or other such X Master Services Agreement referenced on an insertion order.
**6.4** Ads Policy Guidelines ([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies)), including the Policies for Conversion Tracking and Custom Audiences ([https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences))
**6.5** Developer Agreement and Policy ([https://docs.x.com/developer-terms/agreement](/developer-terms/agreement))
**6.6** X Trademark and Brand Guidelines ([https://about.x.com/who-we-are/brand-toolkit](https://about.x.com/who-we-are/brand-toolkit))
Company agrees to the X Policies to the extent that Company accesses or uses Individual Products to which the individual policies apply. Company accepts and agrees that the X Policies may be modified by X from time to time in X’s sole discretion. In the event of a material modification to the X Policies that impacts Company, X will provide Company notice (such as by email or as may be posted on the X Service) of any such change. Company’s continued access or use of the X Materials and X Marks following any such updates or modifications will constitute binding acceptance of the updates and modifications.
### 7. Term; Termination Rights; Suspension Rights.
**7.1 Term.** This Agreement will commence on the Effective Date and will remain in effect for one (1) year (the “**Initial Term**”) and automatically continue thereafter for additional, successive one (1) year terms (each a “**Renewal Term**”), unless either party provides written notice of non-renewal at least thirty (30) days prior to the expiration of the Initial Term or terminates this Agreement in accordance with Section 7.2 below. The Initial Term and all Renewal Terms will collectively constitute the (“**Term**”).
**7.2 Termination; Suspension.** Upon completion of the Initial Term and the commencement of a Renewal Term, either party may terminate this Agreement for convenience upon provision of thirty (30) days’ prior notice to the other party. X may immediately terminate this Agreement upon written notice to Company if Company: (a) merges or is acquired, in whole or in part, by any third party, whether voluntarily or involuntarily, and/or by operation of law (including, without limitation, in connection with a merger, acquisition, or sale of assets, whether Company is the surviving or disappearing entity); or (b) has a receiver or similar party appointed for its property, becomes insolvent, acknowledges its insolvency in any manner, ceases to do business, makes an assignment for the benefit of its creditors, or files a petition in bankruptcy. Without limiting any other remedy in this Agreement or available at law or in equity, X may immediately suspend Company’s access to, or use of, the Ads Products, any given Individual Product, and/or the X Materials (or any part thereof) or terminate any and all license(s) granted to Company under this Agreement or this Agreement in its entirety, at any time and without notice, if X, in its sole discretion, believes or determines that: (i) Company is in violation of any of the Our Policies, or has breached or attempts to breach or is in non-compliance with any term or condition of this Agreement, and/or (ii) Company’s continued access to the Ads Products, a given Individual Product, and/or the X Materials will or may cause liability for X and/or X’s Clients or otherwise harm X or X’s Client’s service, business, or reputation.
**7.3 Effect of Termination.** Upon expiration or termination of this Agreement: (a) all rights and licenses granted hereunder will immediately cease and Company shall immediately cease accessing and using the X Materials; (b) within thirty (30) days of such expiration or termination, Company will remove, delete and securely erase all X Materials (including all copies and portions thereof) in all forms and types of media from the Company Service or otherwise in Company’s possession or control; and (c) within thirty (30) days of such expiration or termination, Company will delete and securely erase all copies of any Confidential Information (as defined below in Section 9) in Company’s possession or control. X will not be liable for any costs, expenses, or damages as a result of its termination of this Agreement.
**7.4 Wind Down Period.** Notwithstanding the foregoing, in the event that either party terminates this Agreement pursuant to this Section 7, the terms and conditions of this Agreement, and the respective rights and obligations of the parties hereto, shall, at X’s sole election (and upon X’s written notification to Company of such election), continue to apply during a Wind-Down Period (as defined below) solely with respect to any and all Client advertising campaigns that are then ongoing at the time of such termination (which shall include, without limitation, circumstances in which X and/or the applicable Client have elected to run an advertising campaign, even if such advertising campaign has not actually commenced at the time of termination). As used herein, “**Wind-Down Period**” shall mean a period commencing upon the termination of the Term and continuing until the earlier of: (i) ninety (90) days following such termination date; or (ii) the completion of all Client advertising campaigns that were then ongoing (as described above) as of such termination date.
**7.5 Survival.** Those terms that by their nature should survive either expiration or termination of this Agreement, shall survive, including, but not limited to, Sections 3-15.
### 8. Security; Security Breaches; Regulatory Notice; Data Deletion; Audit.
**8.1 Security.** Company will use industry-standard security measures in connection with its performance under this Agreement, including, but not limited to, administrative, technical, and physical security measures for data transmission and storage at least as restrictive as industry-standard security measures for the transmission and storage of the types of data included in the X Materials. Company will also use reasonable technical and organizational security measures (including, at a minimum, password protection and access protocol restrictions), and in no event less care than it uses in connection with transmitting and securing Company’s own data of the same or similar nature, to restrict access to X Materials and Confidential Information to only those individual Company personnel who need to access such X Materials in order to exercise Company’s rights and/or fulfill Company’s obligations pursuant to this Agreement.
**8.2 Security Breaches.** Company shall notify X in writing (which may include email) within twenty-four (24) hours of becoming aware of any security breach or other improper access that resulted, may have resulted, or had the potential to result, in exposure of any X Materials and/or data related to, based upon, or arising from, this Agreement. Company will consult and cooperate with X in any investigations, provide any required notices and/or provide any information reasonably requested by X.
**8.3 Regulatory Inquiries.** Company shall notify X in writing (which may include email) within twenty-four (24) hours of Company’s receipt of notice of any inquiry from a government or regulatory agency concerning a security breach (or similar incident), Company’s alleged misuse of consumer data, or any other aspect of Company’s operations that are reasonably related, either directly or indirectly, to this Agreement.
**8.4 Data Deletion.** Company shall delete and securely erase any and all X Materials from its systems when Company no longer has a legitimate business need to retain such X Materials in order to exercise Company’s rights and/or fulfill Company’s obligations under this Agreement (including, without limitation, in the event that the applicable Client ceases to use the Ads Products or otherwise ceases to use the Company Services), but in no event later than the earlier of: (a) ninety (90) days from the date that Company first receives the applicable Data, or (b) thirty (30) days following the expiration or termination date of the Agreement. In addition, at any time, Company agrees to delete and securely erase, immediately upon X’s written request (which may be delivered via email), any X Materials that X deems necessary or desirable to delete and securely erase (in X’s sole and absolute discretion).
**8.5 Audit.** Upon reasonable prior written notice (of no less than ten (10) days), no more than twice each calendar year during the Term and once during the six (6) month period after the date that this Agreement terminates or expires, at X’s expense, X shall be provided access to Company facilities to audit the processes, methodologies, practices and systems used by Company in performance of its obligations and exercising its rights under this Agreement. For clarity, Company acknowledges and agrees that (i) X may engage a third-party auditor to perform any such audit on its behalf; and (ii) notwithstanding anything to the contrary herein, X may share any relevant Confidential Information concerning Company (including, without limitation, the terms and conditions of this Agreement) with such third-party auditor solely as required to facilitate any such audit.
### 9. Confidential Information.
Each party agrees that all business, technical and financial information that is designated as “confidential” or “proprietary,” or that is disclosed in a manner that a reasonable person would understand the confidential nature of the information being disclosed by the disclosing party (“**Confidential Information**”). For clarity, all proprietary information provided by X to Company pursuant to this Agreement, which includes, without limitation, information (tangible or intangible) regarding X’s technology, designs, techniques, research, know-how, specifications, product plans, pricing, customer information, user data, current or future strategic information, current or future business plans, policies or practices, employee information, and other business and technical information (including, without limitation, results, analysis or data regarding uptime, reliability, traffic and growth metrics, network quality, and other usage statistics of the X Service, in the aggregate or otherwise, derived from Company’s use of the X Materials or the X Service and/or access to technical documentation, developer newsletters and/or online portals or forums) is X Confidential Information and proprietary to X. Without limiting the foregoing, the terms and conditions of this Agreement, the X Materials, any product requirements, and any other documentation, onboarding processes or other materials provided by X to Company under this Agreement shall be deemed X Confidential Information. Except as expressly allowed herein, the receiving party will hold in confidence and not use or disclose (except in connection with the performance of such party’s obligations under this Agreement) any Confidential Information of the disclosing party. The receiving party shall not be obligated under this Section with respect to information that the receiving party can document through writing or testimony that such information: (i) is or has become readily publicly available through no fault of the receiving party or its employees or agents; (ii) is received from a third party lawfully in possession of such information, and the receiving party has no knowledge of any disclosure restrictions on such third party to disclose such information; (iii) is disclosed to a third party by the disclosing party without restriction on disclosure; (iv) was rightfully in the possession of the receiving party without restriction prior to its disclosure by the other party; or (v) was independently developed by employees or consultants of the receiving party without reliance on such information. The receiving party may make disclosures required by law or court order, provided that the receiving party notifies the disclosing party of the issuance of such order and allows the disclosing party to participate in the proceeding.
### 10. Representations and Warranties.
Company represents and warrants that: (i) it has all requisite legal and corporate power to enter into this Agreement; (ii) it has taken all action required to make this Agreement a legal, valid and binding obligation; (iii) it has no agreement or understanding with any third party that interferes with or will interfere with its performance of its obligations under this Agreement; (iv) it has obtained and shall maintain all permissions, consents, rights, approvals and licenses necessary to perform its obligations and grant all rights and licenses granted under this Agreement including, without limitation, all rights necessary for Company to grant X a license to use Company Materials to place ads on any advertising inventory available or accessible to X on the X Service or otherwise and provide the Company Service; (v) the Company Service and Company Materials do not, and will not, infringe, misappropriate or otherwise violate any third party rights; and (vi) its business and performance under this Agreement, including its provision of the Company Service, is and shall be in compliance with all applicable foreign, federal, state and local laws and government rules and regulations. Company further represents and warrants that: (a) it has no knowledge of any actual, pending, or threatened claims, lawsuits, actions, or charges pertaining to the Company Service, any Company Materials or other deliverables related to this Agreement or Company’s practices regarding data security, data use, or privacy; and (b) in the event that Company is accessing or using the Ads Products (or any aspect thereof) on behalf of a Client, Company has the authority as agent to such third party to use such Company Materials on such third party’s behalf, to convey the rights to such third party materials as may be provided to X in the Company Materials, and to bind such third party to the terms of this Agreement.
### 11. Feedback. Beta Services.
If and to the extent that X provides (in its sole and absolute discretion) Company with any access to any features and functionality that are designated private, unreleased, in development, or in “alpha” or “beta” (collectively, “**Beta Services**”), Company acknowledges and agrees that Beta Services are not supported by X, and Beta Services (or any portion thereof) may be launched publicly or made unavailable at any time (in each case, in X’s sole and absolute discretion). Beta Services are provided “AS IS” to the fullest extent of the law, and Company’s use of such Beta Services is at Company’s own risk and consent. All Beta Services will be considered X Confidential Information. Company agrees that participation in any Beta Service will assist X in research, analyzing and validating some existing and/or prospective programs, products and/or tools, and that if Company provides X with any comments, feedback or other information to assist X in evaluating and improving such programs, products and/or tools (“**Feedback**”), X and its designees will be free to copy, modify, create derivative works, publicly display, disclose, distribute, license and sublicense, incorporate, and otherwise use the Feedback, including derivative works thereto, for any and all commercial and non-commercial purposes with no obligation or compensation of any kind to Company or any third party. For clarification, Feedback does not include and X will not use Company’s name or publicly disclose Company’s Beta Services performance results. Feedback will also include any Company comments concerning the X Materials, the Ads Products, and/or Company’s evaluation and use thereof. Company agrees that nothing in this Agreement will prevent X from developing products or services that may be competitive with Company’s or any Clients’ or End Users’ products or services.
### 12. Warranty Disclaimer.
THE X MATERIALS, THE ADS PRODUCTS, AND ANY OTHER X PRODUCTS AND SERVICES (INCLUDING, WITHOUT LIMITATION, ANY BETA SERVICES) AND ANY X MARKS PROVIDED HEREUNDER ARE PROVIDED “AS IS” AND ON AN “AS AVAILABLE” BASIS, WITHOUT WARRANTY OF ANY KIND. X DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR CONDITIONS ARISING OUT OF COURSE OF DEALING OR USAGE OF TRADE. X DOES NOT WARRANT THAT THE X MATERIALS, THE ADS PRODUCTS, AND ANY OTHER X PRODUCTS AND SERVICES (INCLUDING, WITHOUT LIMITATION, ANY BETA SERVICES) OR ANY X MARKS PROVIDED HEREUNDER WILL MEET COMPANY’S REQUIREMENTS OR THAT USE OF SUCH X MATERIALS, OTHER X PRODUCTS AND SERVICES AND/OR ANY X MARKS WILL BE ERROR-FREE, UNINTERRUPTED, VIRUS-FREE, OR SECURE. THIS DISCLAIMER OF WARRANTY MAY NOT BE VALID IN SOME JURISDICTIONS, AND COMPANY MAY HAVE WARRANTY RIGHTS UNDER LAW WHICH MAY NOT BE WAIVED OR DISCLAIMED. ANY SUCH WARRANTY EXTENDS ONLY FOR THIRTY (30) DAYS FROM THE EFFECTIVE DATE OF THIS AGREEMENT (UNLESS SUCH LAW PROVIDES OTHERWISE).
### 13. Indemnification.
Company will defend, at its own expense, any claim, suit or action against X brought by a third party to the extent that such claim, suit or action is based upon an allegation that (i) the Company Materials, the Company Service, the Company Marks, X’s use of the Company Materials or Company Marks, or the technology used to generate the Company Materials and/or the Company Service infringes any rights of any third party (including, without limitation, any intellectual property rights, privacy rights or publicity rights); (ii) Company has breached any of its obligations, representations or warranties hereunder, including Company’s data security, data use, and privacy obligations or (iii) Company’s unauthorized use of the X Materials and/or X Marks in violation of the terms, conditions and restrictions set forth in the Agreement. Company will indemnify and hold X harmless from and against any losses, damages, liabilities, penalties, costs and expenses attributable to any such claim. Company is responsible for defending any claim against X, subject to X’s right to participate with counsel of its own choosing, and for payment of all judgments, settlements, damages, losses, liabilities, costs, and expenses, including reasonable attorney’s fees, resulting from all claims against X, provided that Company will not agree to any settlement related to any claims without X’s prior express written consent regardless of whether or not such settlement releases X from any obligation or liability. X will give Company prompt notice of an indemnification obligation (provided that failure to do so will only relieve Company of its obligation to the extent it can demonstrate material prejudice from the failure).
### 14. Limitation of Liability.
IN NO EVENT WILL X BE LIABLE TO COMPANY OR ANY CLIENTS OR END USERS FOR ANY SPECIAL, INCIDENTAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR FOR LOST REVENUE, LOST PROFITS, COSTS OF REPLACEMENT OF GOODS OR SERVICES, LOSS OF TECHNOLOGY, GOODWILL, RIGHTS OF SERVICES, LOSS OF DATA OR INTERRUPTION OR OF LOSS OF USE OF SERVICE ARISING OUT OF OR IN CONNECTION WITH THIS AGREEMENT, OR FOR COMPANY’S OR CLIENT’S OR END USER’S USE OF THE X MATERIALS, X MARKS OR ANY X PRODUCTS AND/OR SERVICES (INCLUDING, WITHOUT LIMITATION, THE ADS PRODUCTS) PROVIDED HEREUNDER, WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, OR OTHERWISE, AND WHETHER OR NOT X HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. INSOFAR AS APPLICABLE LAW PROHIBITS ANY LIMITATION ON LIABILITY HEREIN, THE PARTIES AGREE THAT SUCH LIMITATION WILL BE AUTOMATICALLY MODIFIED, BUT ONLY TO THE EXTENT SO AS TO MAKE THE LIMITATION COMPLIANT WITH APPLICABLE LAW. THE PARTIES AGREE THAT THE LIMITATIONS ON LIABILITIES SET FORTH HEREIN ARE AGREED ALLOCATIONS OF RISK AND WILL APPLY NOTWITHSTANDING THE FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY. IN ANY CASE, X’S AGGREGATE LIABILITY UNDER THIS AGREEMENT WILL NOT EXCEED FIFTY U.S. DOLLARS (U.S. \$50).
### 15. Miscellaneous.
**15.1 Publicity.** Company may not issue any press release, blog post or otherwise make any public announcement or disclosure concerning this Agreement, any of the activities contemplated hereunder, or concerning the relationship between Company and X without X’s prior written consent (which may be provided by email).
**15.2 User Protection.** Company will not (a) knowingly allow or assist any government entities, law enforcement, or other organizations to conduct surveillance on the X Service or the X Materials or obtain information on X’s users or their posts that would require a subpoena, court order, or other valid legal process, or that would otherwise have the potential to be inconsistent with X’s users’ reasonable expectations of privacy; or (b) display, distribute or otherwise make available X Materials to any person or entity that Company reasonably believes will use such data to violate the Universal Declaration of Human Rights (located at [https://www.un.org/en/universal-declaration-human-rights/index.html](http://www.un.org/en/universal-declaration-human-rights/index.html)), including without limitation Articles 12, 18, or 19. Any law enforcement personnel seeking information about X users will be referred to X’s Guidelines for Law Enforcement located at [https://help.x.com/rules-and-policies/x-law-enforcement-support](https://help.x.com/rules-and-policies/x-law-enforcement-support).
**15.3 Government Use.** The X Materials may be “commercial items” as that term is defined at 48 C.F.R. 2.101, consisting of “commercial computer software” and “commercial computer software documentation” as such terms are used in 48 C.F.R. 12.212. Any use, modification, derivative, reproduction, release, performance, display, disclosure or distribution of the X Materials by any government entity is prohibited, except as expressly permitted by the terms of this Agreement. Additionally, any use by U.S. government entities must be in accordance with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4. Contractor/manufacturer is X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
**15.4 Compliance with Laws; Export/Import.** Each party will comply with all applicable foreign, federal, state, and local laws, rules and regulations. Company shall not export or re-export X Services or X Data in violation of the Our Policies (as defined herein) or applicable law. The X Materials may be subject to U.S. export laws and may be subject to import and use laws of the country where it is delivered or used. Company agrees to abide by these laws. Under these laws, the X Materials may not be sold, leased, downloaded, moved, exported, re-exported, or transferred across borders without a license, or approval from the relevant government authority, to any country or to any foreign national restricted by these laws, including countries embargoed by the U.S. Government; or to any restricted or denied end-user including, but not limited to, any person or entity prohibited by the U.S. Office of Foreign Assets Control; or for any restricted end-use.
**15.5 Modifications.** X may update or modify the Our Policies, Analytics Data Display Requirements (attached as [Exhibit A-2](#Exhibit-A-2)), the “X Marketing Partner” program-related terms and conditions (attached as [Exhibit C](#Exhibit-C)) and any other technical documentation and any other guidelines or policies related to the X Materials from time to time, at X’s sole discretion, by posting the changes, as applicable, on X’s developer site, located at: [https://developer.x.com](https://developer.x.com) (as may be amended from time to time), the URL where the applicable X Policy is posted or by otherwise notifying Company (such notice may be via email). If any change is unacceptable to Company, Company’s only recourse is to cease all use of the X Materials and X Marks.
**15.6 Notices.** Except as otherwise stated in Sections 6 and 15.5, any notice required or permitted by this Agreement shall be in writing and shall be delivered as follows, with notice deemed given as indicated: (a) by personal delivery when delivered personally; (b) by overnight courier upon written verification of receipt; (c) by certified or registered mail, return receipt requested, upon verification of receipt; or (d) by electronic mail when the recipient acknowledges having received the applicable email. Notice shall be sent to the addresses set forth below or such other address as either party may specify in writing. Notices for breach sent by Company to X must be sent via overnight courier or certified or registered mail only. Notices to Company will be sent to the Company address on record with X. Notices to X Corp. will be delivered to: X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA, Attn: Legal Department, with a compulsory copy to: Head of Ads API and [legalnotices@x.com](mailto:legalnotices@x.com). Notices to X Internet Unlimited Company will be delivered to: Legal Department, X Internet Unlimited Company, One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland.
**15.7 Assignment.** Company may not assign this Agreement or any of the rights or obligations granted hereunder, in whole or in part, to any third party, whether voluntarily, involuntarily and/or by operation of law (including, without limitation, in connection with a merger, acquisition, or sale of assets, whether Company is the surviving or disappearing entity), except with the express written consent of X, and any attempted assignment in violation of this paragraph is null and void, and X may immediately terminate this Agreement. This Agreement will bind and inure to the benefit of each party’s permitted successors and assigns.
**15.8 No Subcontractors.** Company may not use a third party to perform or fulfill any of Company’s obligations or duties under this Agreement, unless approved in advance by X in writing, which approval may be provided by email.
**15.9 No Partnership.** This Agreement does not create or imply any partnership, agency or joint venture. No waiver by either party of any covenant or right under this Agreement will be effective unless memorialized in a writing duly authorized by such party.
**15.10 No Third-Party Beneficiaries.** There shall be no third-party beneficiaries to this Agreement.
**15.11 Severability.** If any part of this Agreement is determined to be invalid or unenforceable by a court of competent jurisdiction, that provision will be enforced to the maximum extent permissible and the remaining provisions of this Agreement will remain in full force and effect.
**15.12 Waiver.** The waiver by either party of a breach of any provision of this Agreement by the other party shall not operate or be construed as a waiver of any other or subsequent breach by that party. No waiver by X of any covenant or right under this Agreement will be effective unless memorialized in a writing duly authorized by X.
**15.13 Class Action Waiver.** To the extent permitted by law, you also waive the right to participate as a plaintiff or class member in any purported class action, collective action or representative action proceeding.
**15.14 Governing Law and Jurisdiction.** If X Corp. is the contracting entity hereunder, the terms of the Agreement and any dispute relating thereto or between Company and X will be governed by the laws of the State of Texas, without regard to conflict/choice of law principles. The United Nations Convention on Contracts for the International Sale of Goods does not apply to the Agreement. If a dispute, claim or controversy arising out of or relating to this Agreement or the breach, termination, enforcement, interpretation or validity thereof, including the determination of the scope or applicability of this agreement to arbitrate arises, Company agrees to provide X with notice of the dispute, and to provide a ten (10) business day resolution period in which X and Company may attempt to work out the dispute informally. If, after the ten (10) business day resolution period, X and Company cannot resolve the dispute, Company agrees to bring any dispute or claim arising out of this Agreement in the U.S. District Court for the Northern District of Texas or state courts located in Tarrant County, Texas, United States, and you consent to personal jurisdiction in those forums and waive any objection as to inconvenient forum. Without prejudice to the foregoing, you agree that, in its sole discretion, X may bring any claim, cause of action, or dispute we have against you in any competent court in the country in which you reside that has jurisdiction and venue over the claim.
If you are a federal, state, or local government entity in the United States acting in your official capacity and legally unable to accept the controlling law, jurisdiction or venue clauses above, then those clauses do not apply to you. For such U.S. federal government entities, this Agreement and any action related thereto will be governed by the laws of the United States of America (without reference to conflict of laws) and, in the absence of federal law and to the extent permitted under federal law, the laws of the State of Texas (excluding choice of law).
If X Internet Unlimited Company is the contracting entity hereunder, the terms of the Agreement and any dispute relating thereto or between Company and X will be governed by the laws of Ireland, without regard to conflict/choice of law principles. The parties agree that neither the United Nations Convention on Contracts for the International Sale of Goods, nor the Uniform Computer Information Transaction Act (UCITA) shall apply to this Agreement, regardless of the states in which the parties do business or are incorporated. Any dispute, claim or controversy arising out of or relating to this Agreement or the breach, termination, enforcement, interpretation or validity thereof will be brought exclusively before a competent court in Ireland without regard to conflict of law provisions and will be governed by Irish law, notwithstanding any agreement between you and us to the contrary. Without prejudice to the foregoing, you agree that, in its sole discretion, X may bring any claim, cause of action, or dispute we have against you in any competent court in the country in which you reside that has jurisdiction and venue over the claim.
YOU HAVE ONE YEAR TO BRING A CLAIM AGAINST X. You must bring any claim against X arising out of or related to this Agreement within one (1) year after the date of the occurrence of the event or facts giving rise to the dispute, unless applicable law provides that the normal statute of limitations for that claim may not be shortened by agreement. If you do not bring a claim within this period, you forever waive the right to pursue any claim or cause of action, of any kind or character, based on such events or facts, and such claims or causes of action are permanently banned, and X will have no liability with respect to such claim
**15.15 Injunctive Relief.** Each party agrees that money damages would be an inadequate remedy in the event of a breach or threatened breach of the provisions in this Agreement protecting X’s intellectual property (including, without limitation, the X Materials) and/or X’s Confidential Information, and that, in the event of such a breach or threat, X, in addition to any other remedies to which X is entitled, is entitled to such preliminary or injunctive relief (including an order prohibiting the other party from taking actions in breach of such provisions), without the need for posting bond, and specific performance as may be appropriate to preserve all of X’s rights.
**15.16 Updates.** X may update the terms of this Agreement and any policies referenced herein from time-to-time, at its sole discretion, and will provide email notice to Company or posting notice to the URL identified below. Such notice will indicate the effective date of any such updates. The terms of this Agreement will be available for Company to view at any time at [https://docs.x.com/developer-terms/ads-api-agreement](/developer-terms/ads-api-agreement). Company’s continued use of any Individual Product(s) after the effective date provided in the applicable notice will indicate Company’s acceptance of such updates.
**15.17 Entire Agreement.** This Agreement (including the Exhibits attached hereto) constitutes the entire agreement between the parties relating to this subject matter hereof and supersedes and replaces all prior or contemporaneous proposals, understandings, communications and agreements, oral or written, concerning such subject matter. Any amendments to this Agreement shall be made in writing and signed by a representative of the respective parties authorized to bind the parties.
## Exhibit A: Individual Product Terms/X Ads API
Capitalized terms not defined in these Individual Product Terms have the meaning set forth in the main body of the Agreement. To the extent that Company participates in the “X Ads API Program,” the following terms and conditions of this Exhibit A (including Exhibit A-1 and Exhibit A-2) will apply:
### 1. X Ads API Introduction; Access.
**1.1 Introduction.** The X advertising application programming interface (API), and the accompanying documentation, code and related materials (collectively, the “**X Ads API**”) that provides Company with “read/write” access that allows Company to engage in Campaign Management of X Ads and/or with “read” access to certain reporting of Data about the performance of X Ads Campaigns.
**1.2 API Access.** X will (in its sole and absolute discretion) decide if and whether to grant Company “read” or “read/write” X Ads API access. X may implement a review process for granting X Ads API access, but is not required to do so.
### 2. Ads API License.
On condition that X decides to provide Company X Ads API access, and subject to Company’s continuing compliance with terms and conditions of the Agreement, X grants Company a limited, non-exclusive, non-transferable, non-sublicensable, revocable license during the Term to: (a) use the X Ads API to implement the Company Service for the purpose of providing a Client’s End Users with access to Data related to such Client’s X Ads Campaigns (and, if Company has “read/write” API access, to enable Campaign Management of X Ads through the Company Service); (b) display the Data in aggregated format solely within the Company Service in accordance with the Analytics Data Display Requirements (defined below in Section 3 of this Exhibit A) to a Client’s End Users solely for the purpose of optimizing such Client’s X Ads Campaigns; (c) modify the Data only as necessary to format it for, and display it, within the Company Service; (d) enable the Company Service to export Data only in a format that X has approved in writing and that complies with the Analytics Data Display Requirements and via an export mechanism that is approved by X in writing; and (e) use and display the X Marks that X makes available for use in connection with the X Ads API and/or Data solely to attribute X as the source of the Data or as otherwise expressly permitted under the Agreement (in each instance, in accordance with the X Trademark Guidelines).
### 3. Display Requirements, Integration and Other Requirements.
Company’s implementation and use of the X Ads API and Data must at all times comply with: (a) the product requirements attached hereto as Exhibit A-1 (“**Product Requirements**”); (b) the display requirements attached hereto as Exhibit A-2 (“**Analytics Data Display Requirements**”); (c) all technical documentation for the X Ads API that has been, or will be, provided to Company by X (including, without limitation, any endpoint specifications or requirements); (d) any onboarding processes specified by X related to the X Ads API and Data; (e) the Our Policies; and (f) any other guidelines and policies applicable to the X Ads API and Data that may be provided to Company by X.
### 4. Compliance.
Company will abide by all instructions provided or communicated to Company by X, including, without limitation, the limitations on access, calls and use of the X Ads API and any additional limitations or restrictions related to tokens, rate limits, keys, passwords or other login credentials to the X Ads API. Any such instructions are determined by X in its sole and absolute discretion. Company shall comply with any X request to inspect and access the Company Service, including, without limitation, providing X with any Company Service code related to the implementation of the X Ads API, to ensure that the integration of the X Ads API into, and display of the Data within, the Company Service complies with the Product Requirements and Analytics Data Display Requirements, X quality controls and/or other terms and conditions of this Agreement. X may monitor Company’s use of the X Ads API to improve the X Services.
### 5. Control of Allocation of X Ads Inventory.
For clarity, and without limiting the generality of any other term or condition of this Agreement, nothing in this Agreement is meant to represent or imply that Company or the Company Service will have access, via the X Ads API, to any particular inventory or category of X Ads, and X may (in its sole and absolute discretion) elect from time to time, to limit, without restriction, the allocation of X Ads inventory to which Company or the Company Service has access (e.g., without limitation, due to X’s strategic decisions concerning sales channels, direct vs. non-direct client relationships, agency relationships, etc.).
### 6. Control of X Ads Features, API Calls and Functionality.
For clarity, and without limiting the generality of any other term or condition of this Agreement, nothing in this Agreement is meant to represent or imply that Company or the Company Service will have access, via the X Ads API, to any particular X Ads feature, API call or functionality, and X may (in its sole and absolute discretion) elect from time to time, to limit, without restriction, those X Ads features, API calls and/or functionalities to which Company or the Company Service has access (for any or no reason).
### 7. Geography Data.
Company will not (and will not allow others to) use or access the X Ads API to aggregate, cache or store place or other geographic location information contained in any Data or otherwise.
### 8. Removals.
When requested by X, through the X Ads API or otherwise, Company will promptly: (a) delete Data from the Company Service that X reports as deleted or expired; (b) change Company’s treatment of Data that X reports is subject to changed sharing options; and (c) modify Data on the Company Service that X reports has been modified. Company is responsible for the quality of X Ads transmitted to the X Service by the Company Service. X reserves the right to revoke access to the X Ads API and/or, if applicable, remove any specific X Ads from the X Service for any objectionable use by Company or Clients.
### 9. Updates.
Company acknowledges that X may update or modify the X Ads API, from time to time, and in X’s sole and absolute discretion (in each instance, an “**Update**”). Unless otherwise mutually agreed by X and Company in advance in writing (email to suffice), Company is required to implement and use the most current version of the X Ads API and to make any changes to the Company Service, at Company’s sole cost and expense, that are required as a result of such Update no later than thirty (30) days from the date that X notifies Company of the Update. Company will implement all tools (if any) provided by X to enable Updates, as applicable. Updates may adversely affect the manner in which the Company Service accesses or communicates with the X Ads API or displays Data. Company’s continued access or use of the X Ads API following any such Update will constitute binding acceptance of the Update.
### 10. Support.
Company is responsible for providing all support and technical assistance to Clients and their End Users regarding the use of the Company Service (including any issues related to any Ads Product). X is not obligated to provide support or technical assistance directly to Company or any Clients or any of their End Users, and Company will not represent to any Clients or any of their End Users that X is available to provide such support.
## Exhibit A-1: Product Requirements
The Company Service should enable marketers to more efficiently optimize X Ads campaigns, take advantage of X’s real-time conversation, and develop X Ads that improve the user experience.
Accordingly, the Company Service, at all times, will meet the following requirements:
### 1. Product Pricing. No Monetization.
Paid access to the Company Service must be priced on a fixed or variable percentage of spend fee structure. Company will not charge Clients a premium for access to X Ads and/or Data through the Company Service in excess of Company’s standard rates for the Company Service.
### 2. Transparency.
**2.1 Spend.**
2.1.1 Any pricing reports delivered by Company to Clients and their End Users must clearly state and itemize (i) the X Ads spend in X’s native metrics (e.g., as applicable, CPE/CPF) and (ii) the fees charged for use of the Company Service. In addition, Company must always include CPE or CPF metrics (or other applicable X native metrics) adjacent to last-click attribution metrics (e.g., CPC) or other reporting metrics (e.g. CPM).
2.1.2 Company Service will include a self-serve reporting dashboard that will include the capability for Company to report on all metrics provided via the X Ads API.
**2.2 Data.** Company will: (i) use commercially reasonable efforts to maintain up-to-date Data within the Company Service in connection with the X Integration (defined below in Section 6.3 of this Exhibit A-1) in accordance with the then-current Analytics Data Display Requirements; and (ii) clearly disclose to Clients and their End Users any material delay inherent in any information regarding Client’s X Ads Campaigns and/or related analytics data.
### 3. Accounts.
Each End User must be given a separate account to access the Company Service, including a unique user name and password.
### 4. Company Service.
Each customized version of the Company Service for a specific Client (including, without limitation, a white-labeled version of Company Service for a specific Client) must be approved by X in advance and in writing (email to suffice for such purposes).
### 5. Clients and Account Management.
**5.1** A Client must be given the ability to quickly and easily disassociate its X Ads Campaigns from the Company Service and regain exclusive, direct control of its X Ads account(s).
**5.2** Only a Client and its End Users may be allowed to view such Client’s account data or features via the Company Service.
### 6. Other Requirements.
**6.1** Any Company Service functionality that replicates a X feature will utilize X’s naming nomenclature and feature names, subject to any applicable X Trademark Guidelines.
**6.2** Unless otherwise mutually agreed by the parties in advance and in writing, Company will not provide Clients and their End Users or any other third party with access to Data except for the aggregated derivations of such material embodied in the user interface of the Company Service.
**6.3** Company may not commercialize, market or provide access to any X Materials to any third parties (including any Clients or their End Users) until the implementation of the X Ads API and integration and display of any Data within Company Service (collectively, the “**X Integration**”) has been approved in advance by X via the process described in this Section. Company will give X access to the Company Service so that X can review the X Integration. X will inform Company in writing (email being sufficient) if the X Integration is approved or rejected (in X’s sole discretion). Throughout the Term, Company will submit to X any changes to the Company Service that affect the X Integration, which X shall have the right to approve or reject in writing (email being sufficient), in X’s sole discretion.
## Exhibit A-2: Analytics Data Display Requirements
These Analytics Data Display Requirements govern how Company can display Data within the Company Service. Company agrees to abide by these Analytics Data Display Requirements at all times.
### Defined Metrics
All campaigns shown in the Company Service that display Data must include the specific X-defined metrics associated with various campaign objectives (each, a “**Campaign Objective**”), which metrics must be calculated by Company based on the endpoints and formulas located at: [https://docs.x.com/x-ads-api/analytics#metrics-by-objective](https://docs.x.com/x-ads-api/analytics#metrics-by-objective) (or any other successor URL that X may elect from time to time).
### Display Guidelines
**1.** The applicable defined metrics for a given Campaign Objective (as described above in the Defined Metrics section of this Exhibit A-2) must be shown every time a campaign is displayed within the Company Service.
**2.** If the Company Service displays any organic post analytics data, Company must comply with the X Developer Agreement & Policy located at: [https://docs.x.com/developer-terms/agreement](/developer-terms/agreement) as it relates to Company’s implementation, use and display of the organic post analytics data.
**3.** If the Company Service displays metrics about campaigns run on third party networks or by third party publishers (i.e., “cross-channel metrics”) side-by-side with Data, then the following requirements and restrictions apply:
**3.1** Any cross-channel metrics displayed alongside the Data in the Company Service can only include the same category of campaign objective metrics as the applicable X-defined Campaign Objective metrics for such campaign (as described above in the Defined Metrics section of this Exhibit A-2).
By way of example only - If an advertiser is running an app install campaign on a third-party network, only cross-channel metrics that are of the same category as the applicable X-defined metrics for the app install Campaign Objective can be shown alongside the Data.
**3.2** Aggregating data to display cross-channel metrics is not permitted unless the aggregated metrics can be referenced (across all third-party networks/publishers) against a category of metrics associated with a campaign objective that is the same to the applicable X-defined Campaign Objective metrics (as described above in the Defined Metrics section of this Exhibit A-2). By way of example only - Aggregating total engagements for network A, network B, and network C would not be permitted if engagement rates across all channels are not calculated using the same formulas.
**4.** If the Company Service displays any category of metrics sourced from third parties other than X (“**third-party-sourced metrics**”), then the following requirements and restrictions apply:
**4.1** The same requirements and restrictions that apply to displaying cross-channel metrics set forth above in Section 3 apply to the display of any third-party-sourced metrics.
**4.2.** Any third-party-sourced metrics that are displayed alongside Data for a campaign in the Company Service must be the same category of campaign objective metrics as the applicable X-defined Campaign Objective metrics for such campaign (as described above in the Defined Metrics section of this Exhibit A-2). By way of example only:
* If Company displays link click and click-rate metrics from a third-party source, Company will display X’s click and click-rate metrics alongside the third-party-sourced link click and click rate metrics.
* If Company or any of its Clients uses a third-party tracking solution to track website clicks from Promoted posts and such data is displayed in the Company Service, Company must show link clicks, click rate, cost per link click and CPA from X (if available) alongside such third-party-sourced data.
**4.3** Notwithstanding Section 4.2 of this Exhibit A-2, if the third-party-sourced metrics are from a third-party tracking solution provided by a X Conversion Tracking Partner (as defined below), then X requires that only the Data delivered through the X Ads API (and not any corresponding data delivered by the X Conversion Tracking Partner) is displayed in the Company Service, unless otherwise agreed by X in writing in advance (in each instance). For the avoidance of doubt, Company will not display any data sourced from a X Conversion Tracking Partner alongside, or in place of, any Data delivered through the X Ads API. As used in this Exhibit A-2, “**X Conversion Tracking Partner**” means an authorized X conversion tracking partner (as designated by X, in its sole and absolute discretion).
## Exhibit B: Individual Product Terms/Custom Audiences
Capitalized terms not defined in these Individual Product Terms have the meaning set forth in the main body of the Agreement. To the extent that Company uses or accesses the X Custom Audiences Program the following terms and conditions of this Exhibit B will apply:
### 1. Custom Audiences.
**1.1 Introduction.** The X Custom Audiences Program allows for the import and creation of specific segments of users (each a “**Custom Audience**”) for the targeting of advertising Campaigns on the X Service. The parties acknowledge that in order to utilize X Custom Audiences Program, Company, its Client, or a third party service provider approved by X (“**Data Partner**”) is required to provide X with a hashed set of users or devices (which may include email, cookies, device IDs, tracking pixels, etc.) in order for X to complete a match with X users and create Custom Audiences. The Custom Audiences created on behalf of a specific client(s) will be stored in each such Client’s X Ads account for use by Company or Client to target, or retarget, as applicable, advertising on the X Service.
**1.2 Data Usage and Opt-Out.** With respect to any data used in connection with the Custom Audiences Program, in addition to the obligations set out in the Data Protection Addendum found at [https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa), Company agrees and, if applicable, will ensure that its Data Partner(s) agree that (i) Company or such Data Partner (as applicable) have secured all necessary rights, consents, waivers, licenses for use of such data, and (ii) that Company or such Data Partner (as applicable) have provided any users from whom the data is collected with legally-sufficient notice that fully discloses the collection, use, and sharing of the data Company provides to X for purposes of serving ads targeting to users’ interests, and legally sufficient instructions on how users can opt out of X’s interest-based advertising through the methods described here ([https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads](https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads)). Data Company uses in connection with the Custom Audiences Program and/or to create a Custom Audience will not include any data from any user who has opted out of having his/her data used by Company, its Data Partner, or any third party on Company’s behalf. If Company receives a user opt-out after such user was included in an audience provided to X, Company must promptly, but no less frequently than once every twenty-four (24) hours, remove such user(s) from any Custom Audience in which such user was included. Company will provide the data in a format selected by X and acceptable to Data Partner (if/as applicable). In addition to the terms and conditions of this Agreement, Company’s use of X Custom Audiences program will be subject to the terms of the [X Master Services Agreement](https://legal.x.com/ads-terms.html) and Custom Audiences Program T\&Cs and applicable policies, including X’s Policies for Conversion Tracking and Custom Audiences, at [https://legal.x.com/ads-terms.html](https://legal.x.com/ads-terms.html) and [https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences).
**1.3 Additional Program Requirements.** Company’s access to, and use of, the X Custom Audience Program is additionally subject to its compliance with the technical instructions and program policies provided by X to Company (the “**Program Integration Spec**”). Company and X will mutually agree on a process for Company to import or upload Custom Audiences to X.
### 2. Shareable Audiences.
Notwithstanding anything to the contrary set forth in Section 1.1 hereinabove, as a service to Company, at Company’s request and in Company’s sole discretion, X may allow Company to “share” Custom Audiences created for Company amongst grouped X advertiser accounts and/or X @handles and/or otherwise with third parties on the X Service. As used herein, “sharing” an audience means that Company would instruct X to, without limitation, enable grouped X Advertiser Accounts and/or X @handles and/or third parties to access, use, and target advertising Campaigns against the “shared” Custom Audience. Company represents and warrants that it has all necessary rights and authority to share any such audience data in accordance with the instructions given to X by Company. If Company is providing the audience data, and/or managing the Custom Audiences on behalf of a third party (including, without limitation, a Client), Company represents and warrants that Company has the authority as agent for such party to use any such data on the third party’s behalf, to grant X the rights described herein, and to bind such third party to the terms of this Agreement. Notwithstanding the foregoing, nothing in this Section requires X to make the functionality that enables “sharing” Custom Audiences described herein (or any portion thereof) available at any time to Company or any other third party (including, without limitation, any Client).
## Exhibit C: Individual Product Terms/X Marketing Partner (TMP) Program
Capitalized terms not defined in these Individual Product Terms have the meaning set forth in the main body of the Agreement. To the extent that Company participates in the “X Marketing Partner program” (the "**TMP**"), the following terms and conditions of this Exhibit C (including Exhibit C-1) will apply:
### 1. X Marketing Partner Program.
If X approves Company’s application for “Advanced” classification status, and Company maintains such classification status throughout the Term, X may, at any time, choose, in X’s sole and absolute discretion, to qualify Company as part of the TMP (or any other successor program name that X may select from time to time). For clarity, X is not required to select Company to participate in the TMP, regardless of whether Company has achieved or maintains “Advanced” classification status. Furthermore, X may, at any time, choose, in X’s sole and absolute discretion, to terminate or suspend Company’s participation in the TMP for any reason upon notice to Company, in which case, Company’s eligibility to receive any benefits associated with participating in the TMP will immediately cease (without any additional notice from X of such election). In addition to the X Trademark Guidelines that govern Company’s use of any X Marks, Company must also comply with the terms and conditions set forth in Exhibit C-1 that govern use of Badges (as defined in Exhibit C-1) provided by X in connection with participation in the TMP. All Badges (as defined in Exhibit C-1) are deemed X Marks under the Agreement.
### 2. No Use of Badges Outside of the TMP.
For the avoidance of doubt, if Company is not currently qualified by X (in its sole and absolute discretion) as a member of the TMP, (i) Company is not eligible to receive any benefits associated with participating in the TMP, including, without limitation, use of any Badges (as defined in Exhibit C-1) and (ii) Company is prohibited from suggesting it participates in, or has any affiliation with, the TMP.
## Exhibit C-1: X Marketing Partner Program Terms
The X Marketing Partner Program Terms set forth below, including, without limitation, any linked terms and conditions appearing or referenced below, which are hereby incorporated by reference (collectively, “**TMP Partner Terms**”), govern participation in the “X Marketing Partner” program. To the extent that Company is qualified by X, in its sole and absolute discretion, to participate in the “X Marketing Partner” program, Company agrees to abide by the terms and conditions of the TMP Partner Terms at all times during Company’s participation in the “X Marketing Partner” program. These TMP Partner Terms are subject to, and governed by, the Agreement. Any capitalized terms used in this Exhibit C-1 and not otherwise defined in the TMP Partner Terms shall have the meanings ascribed to them in the Agreement.
### 1. TMP Program.
Upon X’s notification to Company that X has qualified Company as a “X Marketing Partner,” Partner will be a member of the “X Marketing Partner” program, as described at [https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners) and will be given access to the TMP badge(s) and any other associated marks that X makes available in connection with the TMP (collectively, the “**Badges**”), use of which is subject to the terms and conditions of this Agreement.
### 2. License from X.
Subject to the terms and conditions of these TMP Partner Terms, and conditioned upon Company’s continuing compliance with this Agreement, X hereby grants Company, and Company accepts, a non-exclusive, royalty free, non-transferrable, non-sub-licensable, revocable license to copy and display the Badges solely with, and to promote, Company’s qualification as a “X Marketing Partner” in the TMP.
### 3. Restrictions.
Strict compliance with this Agreement is required at all times, and any use of the Badges in violation of this Agreement will automatically terminate any license related to Company’s use of the Badges.
**3.1** Company may not alter the Badges in any manner, including, but not limited to, changing the proportion, color or font of the Badges, or adding or removing any elements to or from the Badges.
**3.2** Company may not use the Badges in any manner that implies a false sense of sponsorship or endorsement by X.
**3.3** Company may not use the Badges to disparage X, its products or services, or in a manner which, in X’s sole discretion, may diminish or tarnish X’s goodwill in the Badges.
**3.4** Company may not use the Badges to refer to any other product or service other than X’s or Company’s products and/or services related to Company’s participation in the TMP.
**3.5** The Badges must appear by themselves, with reasonable spacing between each side of the marks, and other visual, graphic or textual elements.
**3.6** The Badges should not be presented or placed in any way that interferes with the readability or display of the entirety of the Badges.
**3.7** Company must link all Badges to [https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners) (or any other successor URL that X may elect from time to time) or otherwise display the following attribution on any materials that display the Badges: “The ‘X Marketing Partner’ Program badge, X and the X logo are trademarks of X Corp. or its affiliates.”
### 4. Program Requirements.
Use of the Badges are further subject to, and governed by, at all times, without limitation, the [X Trademark Guidelines](https://about.x.com/who-we-are/brand-toolkit) and any other requirements communicated by X to Company in connection with participation in the TMP (collectively, the “**TMP Program Requirements**”). Company agrees to the TMP Program Requirements, which are hereby incorporated by reference and are available in hardcopy upon request to X. The TMP Program Requirements do not expand or extend the license to the Badges granted herein. Company may use the Badges solely for the purpose expressly authorized by X, and Company’s use must comply with the most up-to-date version of (i) these TMP Partner Terms, and (ii) the TMP Program Requirements. To the extent that there is any conflict or inconsistency between these TMP Partner Terms and the TMP Program Requirements, these TMP Partner Terms shall control.
### 5. License to X.
Company hereby grants X a fully paid up, non-exclusive, worldwide, sub-licensable license to: (i) use and display Company’s trademarks for use in connection with the TMP, (ii) use Company’s product(s) and/or service(s) related to the TMP for X’s non-commercial, internal evaluation, testing and auditing, (iii) develop and publish case studies or other materials that allow X to highlight Company’s qualification as a “X Marketing Partner” in the TMP (including, without limitation, Company’s product(s) and/or service(s) related to the TMP), and (iv) produce marketing materials in connection with the TMP related to Company’s qualification as a “X Marketing Partner” in the TMP (including, without limitation, Company’s product(s) and/or service(s) related to the TMP).
### 6. Program Qualification.
**6.1 Program Qualification.** X reserves the right, from time to time, to review Company’s membership in the TMP, and, in X’s sole and absolute discretion, to re-qualify or de-qualify Company from any given competency and/or the TMP as a whole.
**6.2 Changes to Company’s Products or Services.** In the event that Company plans to make any material change to Company’s product(s) and/or service(s) related to the TMP, Company will provide X with at least thirty (30) calendar days to review Company’s updated products or services prior to release of such change to determine whether they continue to qualify for the TMP. Updated products or services must be re-qualified by X before any further use of the Badges. X will use commercially reasonable efforts to respond to Company’s request for qualification in new competencies. If Company merges, is acquired or otherwise undergoes a change of control, in whole or in part, by any third party, whether voluntarily or involuntarily, and/or by operation of law (including, without limitation, in connection with a merger, acquisition, or sale of assets, whether the assigning party is the surviving or disappearing entity), Company must submit all of Company’s products and/or services related to the TMP to X for re-qualification before any further use of the Badges.
### 7. Suspension and Termination.
X may immediately terminate or suspend these TMP Partner Terms, any rights granted to Company herein, and/or Company’s participation in the TMP, at its sole discretion at any time, for any reason by providing notice to Company. Company may terminate Company’s participation in the TMP by providing ninety (90) calendar days’ notice to X. Upon termination of these TMP Terms and/or termination of Company’s participation in the TMP, all licenses granted herein immediately expire, and Company must cease use of all Badges. Neither party will be liable to the other for any damages resulting solely from termination of these TMP Partner Terms as permitted under this Agreement.
### 8. Modifications.
X reserves the rights, exercisable at its sole discretion, to modify the terms and conditions of these TMP Partner Terms and/or the Badges at any time and to take appropriate action against any unauthorized or non-conforming use of the Badges. If Company has any questions about usage of the Badges, please contact [trademarks@x.com](mailto:trademarks@x.com) for assistance, or write to us at: X Corp., Attention: Legal Department, 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
# X Developer Agreement
Source: https://docs.x.com/developer-terms/agreement
The X Developer Agreement sets the legal terms for using the X API and developer platform, covering licensing, restrictions, and compliance obligations.
Last Updated: April 27, 2026
By clicking “Accept & Subscribe”, continuing to pay the recurring subscription fee for Paid Services, or by otherwise accessing or using any Licensed Material, you agree to the terms of our Agreement. Subscriptions auto-renew until canceled, as described below. A verified phone number is required to subscribe. If you've subscribed through another platform, manage your subscription through that platform.
This X Developer Agreement (“**Agreement**”) is a binding legal agreement between you (referred to in this Agreement as “**you**”) and X and governs your access to and use of the Licensed Material (defined below), including any Paid Services (defined below).
By accessing or using any Licensed Material (defined below), or clicking on a button to accept the terms of this Agreement or recurring subscription payment for Paid Services, you agree to be bound by the terms of this Agreement. If you do not understand the terms herein or do not accept any part of them, then you may not use or access any Licensed Material. You may not use the Licensed Material or accept this Agreement if you are not of legal age to form a binding contract with X or if you are barred from using or receiving the Licensed Material under applicable law. To purchase and use a Paid Service you must: (i) be at least 18 years old or the age of majority as determined by the laws of the jurisdiction in which you live or (ii) have the express consent of your parent or guardian to purchase and use that Paid Service. If you are a parent or legal guardian and you allow your child (or a child that you are a guardian of) to purchase or use a Paid Service, you agree that the terms of this Agreement apply to you, you will abide by this Agreement, and you are responsible for the child’s activity on the Paid Services and for ensuring that the child also abides by the terms of this Agreement. In any case, as stated in the Who May Use the Services section of the [**X Terms of Service**](https://x.com/tos), you must be at least 13 years old to use the "Services" as defined in the X Terms of Service. If you are accepting this Agreement or using the Licensed Material on behalf of a company, organization, government, or other legal entity, you represent and warrant that you have the authority to bind such company, organization, government, or other legal entity to this Agreement, in which case the words “you” and “your” as used in this Agreement shall refer to such entity. If you do not agree to the terms of this Agreement, you may not (and you may not allow any of your personnel to) access or use the Licensed Material.
**I. Definitions.**
In this Agreement, the following definitions apply:
1. “**Developer Site**” means X’s developer site located at [**https://developer.x.com/**](https://developer.x.com/)
2. “**Direct Message**” means a private message that is sent on X Applications by one user to one or more other specific user(s) using X’s direct messaging function.
3. “**Intellectual Property Rights**” means all copyrights, moral rights, patent rights, trademarks, and any other intellectual property or similar rights (registered or unregistered) throughout the world.
4. “**Licensed Material**” means, individually or collectively, the X API and X Content.
5. "**Paid Service(s)**” means features or functionality of the Licensed Material that you access in exchange for payment of a recurring fee, as applicable to the relevant features or functionality and this Agreement. Unless otherwise set forth in this Agreement, all references to “Licensed Material” are intended to include the Paid Service(s).
6. “**Payment Portal**” means the online portal made available to you to opt-in to your use of the Licensed Material, manage subscriptions for Paid Services, manage payment methods for Paid Services, and update account information.
7. “**Services**” means your services, websites, applications, and other offerings (including research) that display X Content or otherwise use the Licensed Material.
8. “**Post**” means a short-form text and multimedia-based message distributed via the X Applications.
9. “**X**” means (a) X Corp. (865 FM 1209, Building 2, Bastrop, TX 78602, USA) if your principal place of business is outside the European Union, EFTA States, and the United Kingdom; or (b) X Internet Unlimited Company (One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland) if your principal place of business is in the European Union, EFTA States, or the United Kingdom.
10. “**X API**” means X Application Programming Interfaces (each, an **“API”**), Software Development Kits (each, an **“SDK”**), and the related tools, documentation, data, technology, code, and other materials provided by X through the Developer Site.
11. “**X Applications**” means X’s real-time information service, commonly referred to as “X,” which includes those services currently provided by X at its websites and X-owned, operated, or controlled mobile applications, social plug-ins, and application programming interfaces.
12. “**X Content**” means Posts, the unique identification number generated for each Post, X end user profile information, and any other data and information made available to you through the X API or by any other means authorized by X, and any copies and derivative works thereof.
13. “**X Marks**” means the X name, trademarks, and logos that X makes available to you, including via the Developer Site, solely for use in accordance with this Agreement.
14. “**Users**” means visitors, users, or customers of your Services.
**II. X API and X Content.**
**A. License from X.** Subject to your compliance with the terms of this Agreement and the applicable Incorporated Developer Terms (as defined below), X hereby grants you a non-exclusive, royalty free, non-transferable, non-sublicensable, and revocable license to solely:
1. Use the X API to integrate X Content into your Services or conduct analysis of the X Content, as explicitly approved by X;
2. Copy a reasonable amount of and display the X Content on and through your Services to Users, as permitted by this Agreement;
3. Modify X Content only to format it for display on your Services; and
4. Use and display X Marks to attribute X Applications as the source of the X Content, as set forth in this Agreement.
**B. License to X.** You hereby grant X a non-exclusive, royalty free, non-transferable, and non-sublicensable revocable license to access, index, and cache by any means, including web spiders and/or crawlers, any webpage or applications on which you display X Content using [**embedded Posts**](https://developer.x.com/docs/twitter-for-websites/embedded-tweets/overview) or [**embedded timelines**](https://developer.x.com/docs/twitter-for-websites/timelines/overview).
**C. Incorporated Terms.** Your access to and use of the Licensed Material is also subject to, and you shall comply with, the following additional terms and policies (collectively, “**Incorporated Developer Terms**”):
1. the [**X Developer Policy**](/developer-terms/policy);
2. the [**API Restricted Use Rules**](/developer-terms/restricted-use-cases);
3. the [**X Rules**](https://help.x.com/rules-and-policies/x-rules);
4. as it relates to your display of any of the X Content, the [**Display Requirements**](https://developer.x.com/developer-terms/display-requirements.html);
5. as it relates to your use and display of the X Marks, the [**X Brand Guidelines**](https://about.x.com/who-we-are/brand-toolkit); and
6. as it relates to taking automated actions on your account, the [**Automation Rules**](https://help.x.com/rules-and-policies/x-automation).
**III. Restrictions on Use.**
**A. Reverse Engineering and other Restrictions.** You shall not and you shall not attempt to (or allow others to): (a) reverse engineer, decompile, disassemble, or translate the X API or otherwise attempt to derive source code, trade secrets, or know-how in or underlying any X API or any portion thereof; (b) interfere with, modify, disrupt, or disable features or functionality of the X API or monitoring mechanisms of the X API; (c) use or access the Licensed Material to create or attempt to create a substitute or similar service or product to the X Applications; (d) sell, rent, lease, sublicense, distribute, redistribute, syndicate, create derivative works of, assign, or otherwise transfer or provide access to, in whole or in part, the Licensed Material to any third party except as expressly permitted in this Agreement; (e) provide use of the X API on a service bureau, rental or managed services basis, or permit other individuals or entities to create links to the X API or "frame" or "mirror" the X API on any other server, or wireless or Internet-based device, or otherwise make available to a third party any token, key, password, or other login credentials to the X API; (f) use the Licensed Material for any illegal, unauthorized, or other improper purpose; (g) use the Licensed Material to derive or obtain non-public information of individual X users; (h) interfere with or disrupt the integrity or performance of the X Applications, X API, or X Content contained therein; (i) remove or alter any proprietary notices or marks on the X Content; (j) attempt to gain unauthorized access to the X Applications, X API, X Content, or related systems or networks; (k) use the X API or X Content to fine-tune or train a foundation or frontier model; or (l) use X Content, by itself or bundled with third party data, or derivative analysis therefrom, to target or serve users with advertising outside of the X Applications.
**B. Commercial Use Restrictions.** If your Services are designated as ‘non-commercial,’ you shall not make Commercial Use (as defined below) of the Licensed Material. Commercial Use restrictions may not apply to officially registered non-profits or NGOs. “**Commercial Use**” means any use of the Licensed Material or access to the X API: (a) by or for a business (i.e. an entity whose primary purpose is to earn revenue through a product or service), or (b) as part of a product or service that is monetized (e.g., website advertising, licensing fees, in-app promotions, and sponsorships).
**C. No Monitoring or Measuring.** Notwithstanding anything to the contrary, you may use the following information only for non-commercial, internal purposes (e.g., to improve the functionality of the Services): (a) aggregate X Applications user metrics, such as number of active users or accounts on X Applications; (b) the responsiveness of X Applications; and (c) results, usage statistics, data, or other information (in the aggregate or otherwise) derived from analyzing, using, or regarding the performance of the X API. All such information is Confidential Information (as defined below).
**D. Rate Limits.** You will not attempt to exceed or circumvent limitations on access, calls, and use of the X API ("**Rate Limits**") or otherwise use the X API in a manner that exceeds reasonable request volume, constitutes excessive or abusive usage, or otherwise does not comply with this Agreement. If you exceed or X reasonably believes that you have attempted to circumvent Rate Limits, controls to limit use of the X APIs, or the terms of this Agreement, then your ability to use the Licensed Material may be temporarily suspended or permanently blocked. X may monitor your use of the X API to improve the Licensed Material and X Applications and to ensure your compliance with this Agreement and the Incorporated Developer Terms.
**E. Location Data.** You shall not, and you shall not allow others to, aggregate, cache, or store location data and other geographic information contained in the X Content except in conjunction with the X Content to which it is attached. You may only use location data and geographic information to identify the location tagged by the X Content.
**F. Use of X Marks.** You shall not include any of the X Marks in your registered corporate name(s), your logos, or your service or product names. You shall not create any derivative works of the X Marks or use the X Marks in a manner that creates or reasonably implies an endorsement, sponsorship, or association with X. All use of the X Marks and all goodwill arising out of the use will inure to X's benefit. You will not remove or alter any proprietary notices or X Marks on the Licensed Material.
**G. Security.** You will maintain the security of the X API and will not make available to any third party any token, key, password, or other login credentials to the X API. You will use industry standard security measures to prevent unauthorized access or use of any of the features and functionality of the X API, including access by viruses, worms, or any other harmful code or material. You shall keep X Content confidential and secure from unauthorized access by using industry-standard organizational and technical safeguards for such data, and with no less care than you use in connection with securing similar data you store. You will immediately notify X, consult and cooperate with investigations, assist with any required notices, and provide any information reasonably requested by X if you know of or suspect any breach of security or potential vulnerability related to the Licensed Material. You will promptly remedy such breach or potential vulnerability resulting from your access to the Licensed Material.
**H. Digital Services Act**. Notwithstanding anything to the contrary in this Agreement, to the extent you are provided access to the Licensed Material pursuant to the procedures described in Article 40 of the Digital Services Act (Regulation (EU) 2022/2065) (“DSA”), your access and use of the Licensed Material is limited solely to performing research that contributes to the detection, identification, and understanding of systemic risks in the European Union and only to the extent necessary for X to comply with its obligations under the DSA. Any such use of the Licensed Material is non-commercial as described in Section III(B) of this Agreement. You may not disclose, reproduce, license, or otherwise distribute the Licensed Material (including any derivatives thereof) that you retrieve through the X API to any person or entity outside the persons specified within your approved application unless (i) the information is disclosed to the Digital Services Coordinator or other party specifically permitted by the DSA pursuant to the “vetted researcher” status and procedures described in Article 40, or (ii) disclosure is required by law.
**I. Tokens.** X may limit the number of tokens that it provides to you, including but not limited to tokens that enable access and use of functionality or features on X Applications.
**J. Access Tiers.** X provides different tiers of access (as described at [developer.x.com](http://developer.x.com)) to the Licensed Material, and you shall subscribe to the tier that best fits your use case. X may, at any time, review your use of its Licensed Materials and require a change in the access tier to which you are subscribed, including but not limited to, application for Enterprise access (as described at [developer.x.com](http://developer.x.com)).
**K. Prohibition on I-Framing:** You shall not, under any circumstances, embed, display, or otherwise incorporate any Licensed Material, X Content, X API, or elements of the X Applications within an iframe, inline frame, or any similar embedding mechanism on your Services or any other platform. This prohibition is absolute and includes, but is not limited to, attempts to frame X Content for display, integration, or redistribution purposes. Violation of this clause may result in immediate termination of your Developer Agreement and your access to the Licensed Material (e.g., X API, X Data License, Developer Console) as outlined in Section VII.I.
**L. Self-Serve Use.** The Pay-Per-Use, Basic, and Pro plans (as described at [developer.x.com](https://developer.x.com)) are designed for hobbyists, commercial prototyping, initial development, early-stage X product integrations, and supporting applications with a limited number of end-users. If you use the X API beyond this scope, then you must apply (or already subscribe to) an Enterprise plan (as described at [developer.x.com](https://developer.x.com)).
**M. Commercial Use:** If you use the X API beyond the scope of hobbyist projects, commercial prototyping, initial development, early-stage X product integrations, or for applications with a limited number of end-users, then you must apply (or already subscribe to) an Enterprise plan (as described at developer.x.com).
**IV. Updates and Removals.**
**A. Updates.** X may update, modify or discontinue any features or function of the Licensed Material, in whole or in part, from time to time (in each instance, an “**Update**”). You shall implement and use the most current version of the Licensed Material and make any changes to your Services that are required as a result of the Update, at your sole expense. Updates may adversely affect the way your Services access or communicate with the X API or display X Content. X will not be liable for damages of any sort that result from any Update.
**B. Removals.** If X Content is deleted, gains protected status, or is otherwise suspended, withheld, modified, or removed from the X Applications (including removal of location information), you will make all reasonable efforts to delete or modify that X Content (as applicable) as soon as possible, and in any case within twenty four (24) hours after a written request to do so by X or by an X user with regard to its X Content unless prohibited by law or regulation and with the express written permission of X.
**V. Ownership, Betas, and Feedback.**
**A. Ownership.** Except to the extent expressly stated otherwise in this Agreement, neither party will acquire any right, title, or interest in any Intellectual Property Rights owned or licensed by the other party. The Licensed Material is licensed, not sold, and X (or its licensors or X Application users, as applicable) retains and reserves all rights, including all Intellectual Property Rights, not expressly granted in this Agreement. You shall not do anything inconsistent with X’s ownership, including without limitation, challenging X’s ownership of the X Marks, challenging the validity of the licenses granted in this Agreement, or otherwise copying or exploiting the X Marks except as specifically authorized in this Agreement. If you acquire any rights in the X Marks or any confusingly similar marks, by operation of law or otherwise, you will, at no expense to X, immediately assign those rights to X.
**B. Betas.** X may provide you with early access to non-generally available alphas, betas, research studies, pilots, marketing services, or other programs from time to time (each, a “**Beta**”). Betas will be considered Confidential Information. Your participation in any Beta is at your own risk, may be subject to additional requirements, and may assist X in research, analyzing, and validating existing or prospective programs, products and/or tools.
**C. Feedback.** X will be free to use any feedback, comments, or suggestions you provide X related to X, the Licensed Material, Betas, or any other of X’s products or services (“**Feedback**”) in any way without any compensation or obligation to you or any third party and Feedback will be deemed Confidential Information. You hereby irrevocably assign to X all right, title, and interest to Feedback.
**VI. Confidentiality.**
You may be given access to non-public information, software, and specifications relating to the Licensed Material (“**Confidential Information**”). You may use Confidential Information only as necessary in exercising your rights under this Agreement. You shall not disclose Confidential Information to any third party without X’s prior written consent. You shall protect Confidential Information from unauthorized use, access, or disclosure in the same manner that you would use to protect your own confidential information of a similar nature and in no event with less than a reasonable degree of care.
**VII. Term; Subscription Fees; Payment; Suspension, and Termination.**
**A. Term.** The term of this Agreement will start on the date (i) you accept the terms herein or (ii) start accessing or using any of the Licensed Material, whichever is earlier, and will continue until you stop accessing and using the Licensed Material unless terminated earlier as described below.
**B. Subscription Terms.** Paid Services provided as part of the Licensed Material are made available as a recurring subscription service that provides access to certain features, benefits, or services, as described on the Developer Site and the Payment Portal. If you purchase a Paid Service, you do so by paying a subscription fee in advance on a monthly basis in accordance with the payment terms set forth below. When you subscribe to access the Paid Service(s) via the Payment Portal, you expressly agree that you are authorizing recurring payments and that payments will be made by the payment method you have selected until the applicable Paid Service is canceled by you or by X or this Agreement is otherwise terminated. Your subscription to the Paid Service will automatically renew monthly until canceled in accordance with this Agreement. Your payment information will be automatically processed by the Payment Processor (as defined below) at the start of each subscription period applicable to the Paid Service(s). If your payment information is declined, your subscription may be canceled until you provide new payment information for the applicable Paid Service(s). If you provide new payment information and your payment account is successfully charged, your new subscription period will be based on the original renewal date and not the date the successful charge took place. Prices for Paid Services are subject to change from time to time. X will provide reasonable advance notice of any material change to the price of Paid Services, which notice may be provided via the Developer Site. For subscription fees, price changes will take effect at the start of the next subscription period following the date of the price change. If you do not agree with a price change, you have the right to reject the change by canceling your subscription to the applicable Paid Service(s) prior to the price change going into effect.
**C. Payment Terms.** X may offer payment options that vary by Paid Service, device, operating system, geographic location, or other factors, which may be updated from time to time. These payment options may include web payments using a third party payment processor (“**Payment Processor**”). When you access a Paid Service, you agree: (i) to pay the price listed for the Paid Service, along with any additional amounts relating to applicable taxes, surcharges, credit card fees, bank fees, foreign transaction fees, foreign exchange fees, and currency fluctuations, on a recurring basis during the applicable subscription period; and (ii) to abide by any applicable terms of service, privacy policies, or other legal agreements or restrictions (including additional age restrictions) imposed by the Payment Processor in connection with your use of a given payment method. The subscription fee will automatically be applied at the start of the renewal period for the applicable subscription period unless you cancel the Paid Service(s) on the Developer Site. It is your responsibility to make sure your banking, credit card, debit card, and/or other payment information is up to date, complete, and accurate at all times. If you make a payment for a Paid Service through a Payment Processor, X may receive information about your transaction such as when it was made, when a subscription is set to expire or auto-renew, what platform you made the purchase on, and other information. X will not be liable for any errors made or delays by the Payment Processor, your bank, your credit card company, or any payment network. All payments to X are non-refundable except as otherwise expressly provided in this Agreement or as required by law.
**D. Taxes and fees.** All fees exclude any and all taxes and similar fees now in force, enacted, or imposed in the future on the transaction, delivery of the Licensed Material, or the delivery of the X Content including any sales, use or value added taxes, goods and services tax, consumption tax, customs duties, tariffs, or similar charges. These taxes may include but are not limited to, VAT, GST, sales tax, withholding tax, and any other applicable taxes but exclude taxes solely based on X’s net income. You are responsible for the payment of all such taxes, duties, and charges and any related penalties and interest arising from the payment of such amounts. In addition, a surcharge may be charged to recover costs associated with Digital Services Tax ("DST") or similar jurisdiction-specific taxes or regulatory fees incurred by X in certain jurisdictions. This surcharge will appear as a separate line item on your invoice, where applicable, and will be calculated as a percentage of applicable charges as determined by X in its sole discretion. X may adjust this surcharge at any time, without prior notice, in response to increased tax or fee rates or related administrative costs. Depending on your location, X may be responsible for collecting and reporting information related to transaction taxes arising from your purchase of Paid Services. You grant X permission to provide your account and personal information to relevant tax authorities to fulfill our tax collection and reporting obligations.
**E. Canceling Your Subscription for Paid Services.** Your subscription for Paid Services will automatically renew monthly unless you cancel your subscription at least 24 hours before the end of your current subscription period. There are no refunds or credits for any partial subscription periods, including in a situation where certain features, benefits, and/or services are modified or discontinued. SUBSCRIPTION PLANS ARE PREPAID, NON-REFUNDABLE (UNLESS REQUIRED BY LAW), AND AUTOMATICALLY RENEW AT THE END OF EACH SUBSCRIPTION PERIOD UNLESS THE SUBSCRIPTION IS CANCELED FOLLOWING THE CANCELLATION PROCEDURES HEREIN. You may cancel your subscription for Paid Services at any time via the Developer Site and you will no longer have access to the Paid Services (or any features or functionality thereof) at the end of your then-current subscription term. When you cancel the Paid Services, your subscription will remain active from the time you cancel until the end of your current subscription period. You will not receive a refund or credit for any remaining days in your current subscription period unless required by law. All payments for Paid Services are final and not refundable or exchangeable except as required by applicable law. X makes no guarantee as to the nature, quality, or value of a Paid Service or the availability or supply thereof. Refunds or credits are not provided for any unused or partially used Paid Service (for example, a partially used subscription period). **All transactions are final** unless you have a right to withdraw pursuant to law, such as provided below.
1. **Withdrawal Right & Refunds for Users Living in EU or UK.** When you purchase any Paid Services on subscription, you expressly agree to do so on a subscription basis and that the subscription will commence immediately on your date of purchase. If you are a consumer in an EU Member State or the UK, you agree you have fourteen (14) days after your purchase to withdraw from your contract for purchase for any reason.
2. **No Withdrawal Right for Users Living in Taiwan.** When you purchase Paid Services, you do so on a subscription basis, the subscription will commence immediately on your date of purchase, and the Paid Service is fully performed once started. If you are a consumer in Taiwan, you agree that you can cancel your subscription for any Paid Services in accordance with Section VII.E above, but that there is otherwise no right to rescind your subscription and no refund will be issued.
**F. Paid Services Are Non-Transferable between X Accounts.** Each purchase of a Paid Service applies to a single X account, meaning that your purchase will apply solely to the account you were using when you purchased the Paid Service and will not apply to other accounts that you may have access to or control over. If you have or control multiple accounts and you want access to Paid Services on each account, you must purchase the Paid Service on each account individually. You may not allow others to use your X account to access any Licensed Material that such person did not order. You may not purchase a Paid Service or use any Licensed Material if you are a person with whom U.S. persons are not permitted to have dealings pursuant to economic sanctions, including, without limitation, sanctions administered by the United States Department of the Treasury's Office of Foreign Assets Control or any other applicable sanctions authority ("**Prohibited Person**"). This includes, without limitation, persons located in, a citizen of, or ordinarily resident in the following countries and regions: Cuba, Iran, the Crimea Region of Ukraine, North Korea and Syria. You represent and warrant that you are not a Prohibited Person.
**G. Restrictions and Obligations.** You may only purchase and use a Paid Service or use the Licensed Material if you are legally allowed to use the Licensed Material in your country and you live in a country supported by X for the applicable Paid Service or Licensed Material. X may, in its discretion, restrict the ability to access the Licensed Material or purchase a Paid Service in certain countries. X reserves the right to modify the list of supported countries from time to time. X reserves the right to refuse Paid Services transactions or to cancel or discontinue the sale or use of a Paid Service or the use of any Licensed Material in its sole discretion.
**H. Suspension.** X may suspend your use of and access to the Licensed Material immediately without notice (a) if X reasonably believes that (i) your use of the Licensed Material would cause damage to, or an inordinate burden upon, the Licensed Material, (ii) you have violated this Agreement, (iii) you create risk or possible legal exposure for X, (iv) X’s provision of the Licensed Material to you is no longer commercially viable; (b) for prolonged inactivity; (c) if X is requested or directed to do so by any competent court of law, regulatory authority, or law enforcement agency; or (d) for failure to pay for the Paid Services. X will not be liable for damages of any sort that result from any such suspension.
**I. Termination.** X may terminate this Agreement for any reason at X’s sole discretion. Except where such early termination is the result of your breach of this Agreement, such early termination by X shall be effective at the end of the then-current subscription period. If you violate the terms of this Agreement, X may terminate this Agreement for cause immediately upon notice to you and you will not receive a prorated refund for any Paid Services. You may cancel your subscription for the Paid Services or your use of the Licensed Material on the Developer Site. Upon termination of this Agreement: (a) all licenses granted in this Agreement immediately expire and you must cease use of any Licensed Material; and (b) you shall permanently delete all Licensed Material in all forms and types of media, and copies thereof, in your possession. Upon the request of X for any reason, you will promptly (and in any event within ten (10) business days of such request) provide evidence (e.g., screenshots of deletion confirmation) of compliance with the provisions of the aforementioned subpart (b) of this Section. The parties to this Agreement will not be liable to each other for any damages resulting solely from termination of this Agreement as permitted under this Agreement.
**VIII. Compliance Audit.**
X or a mutually agreed upon third party agent subject to obligations of confidentiality will be entitled to inspect and audit any records related to the performance of this Agreement in your control or possession upon reasonable notice to you, and at a reasonable time during normal business hours, for the purpose of verifying compliance with this Agreement and the fees payable to X for the two (2) year period preceding the audit. X may exercise its audit right no more than once every twelve (12) months unless it has reasonable cause for noncompliance, and such audit shall not unreasonably interfere with your business activities. You will provide your full cooperation and assistance with such audit and provide access to all Licensed Material in your possession, applicable agreements, and records. Without limiting the generality of the foregoing, as part of the audit, X may request, and you agree to provide, a written report, signed by an authorized representative, listing your then-current deployment of the Licensed Material. You will pay X within thirty (30) business days after the completion of the audit the amount of any underpayment revealed by any such audit. In addition, if any such audit reveals an underpayment by you of five percent (5%) or more, then you will also reimburse X for the reasonable costs and expenses of such audit. The requirements of this Section will survive for one (1) year following the termination of this Agreement.
**IX. Disclaimer.**
TO THE MAXIMUM EXTENT PERMISSIBLE BY APPLICABLE LAW, THE LICENSED MATERIAL IS PROVIDED TO YOU “AS IS”, “WHERE IS”, WITH ALL FAULTS, AND X DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING WITHOUT LIMITATION WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR CONDITIONS ARISING OUT OF THIS AGREEMENT, COURSE OF DEALING OR USAGE OF TRADE. X DOES NOT WARRANT THAT THE LICENSED MATERIAL OR ANY OTHER X PRODUCT OR SERVICE PROVIDED HEREUNDER WILL MEET ANY OF YOUR REQUIREMENTS OR THAT USE OF SUCH LICENSED MATERIAL OR OTHER PRODUCTS OR SERVICES WILL BE ERROR-FREE, UNINTERRUPTED, VIRUS-FREE, OR SECURE. YOU ARE RESPONSIBLE FOR YOUR USE OF THE LICENSED MATERIAL AND ANY CONTENT YOU PROVIDE. THIS DISCLAIMER OF WARRANTY MAY NOT BE VALID IN SOME JURISDICTIONS AND YOU MAY HAVE WARRANTY RIGHTS UNDER LAW WHICH MAY NOT BE WAIVED OR DISCLAIMED.
**FURTHER YOU UNDERSTAND AND AGREE THAT THE PAID SERVICES ARE PROVIDED TO YOU ON AN “AS IS” AND “AS AVAILABLE” BASIS.**
**X. Indemnification.**
You shall defend X against any and all proceedings, demands, claims, and suits (including without limitation product liability claims), and indemnify X from any and all liabilities, damages, and costs (including without limitation reasonable attorneys' fees) to the extent arising out of (a) your use of the Licensed Material in any manner that is inconsistent with this Agreement or (b) the performance, promotion, sale, or distribution of your Services. If X seeks indemnification or defense from you under this Section, X will promptly notify you in writing of the claim(s) brought against X for which it seeks indemnification or defense. X may assume full control of the defense of claims with legal counsel of its choice. You shall not enter into any third-party agreement that would affect the rights of X, constitute an admission of fault by X, or bind X in any manner without the prior written consent of X. If X assumes control of the defense of such claim, X shall not settle any such claim requiring payment from you without your prior written approval.
**XI. Limitation of Liability.**
IN NO EVENT WILL X BE LIABLE TO YOU OR ANY USERS FOR ANY INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL DAMAGES OR ANY LOSS OF OR DAMAGE TO USE, DATA, BUSINESS, GOODWILL OR PROFITS ARISING OUT OF OR IN CONNECTION WITH THIS AGREEMENT. IN ANY CASE, X'S AGGREGATE LIABILITY FOR ANY AND ALL CLAIMS UNDER THIS AGREEMENT WILL NOT EXCEED FIFTY DOLLARS (\$50.00). THE FOREGOING LIMITATIONS, EXCLUSIONS AND DISCLAIMERS SHALL APPLY REGARDLESS OF WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON CONTRACT, WARRANTY, TORT, STRICT LIABILITY OR OTHERWISE, AND WHETHER OR NOT X HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. IF APPLICABLE LAW PROHIBITS ANY LIMITATION ON LIABILITY HEREIN, THE PARTIES AGREE THAT THE LIMITATION WILL BE DEEMED TO HAVE BEEN MODIFIED TO CONFORM TO APPLICABLE LAW. THE PARTIES AGREE THAT THE LIMITATIONS ON LIABILITIES SET FORTH HEREIN ARE AGREED ALLOCATIONS OF RISK AND SUCH LIMITATIONS WILL APPLY NOTWITHSTANDING THE FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY.
**XII. Agreement Updates.**
X may update or amend this Agreement or any of the Incorporated Developer Terms from time to time. You will check the Developer Site regularly for updates. X will alert you of material revisions to these terms by posting the updated terms on these sites, via a service notification, or by other suitable means (e.g., via email to an email address associated with your account). The changes will not be retroactive and the most current version of this Agreement, available at the Developer Site, will govern your access to and use of the Licensed Material and any corresponding transactions. Your continued access or use of the Licensed Material will constitute binding acceptance of such updates and modifications.
**XIII. Dispute Resolution and Class Action Waiver.**
**A. THIS SECTION APPLIES TO YOU ONLY IF YOU LIVE OUTSIDE THE EUROPEAN UNION, EFTA STATES, OR THE UNITED KINGDOM, INCLUDING IF YOU LIVE IN THE UNITED STATES. PLEASE READ THIS SECTION CAREFULLY – IT MAY SIGNIFICANTLY AFFECT YOUR LEGAL RIGHTS, INCLUDING YOUR RIGHT TO FILE A LAWSUIT IN COURT.**
1. **Choice of Law and Forum Selection.** The laws of the State of Texas, excluding its choice of law provisions, will govern this Agreement and any dispute that arises between you and X, notwithstanding any other agreement between the parties to the contrary. All disputes related to this Agreement, including any disputes, claims, or controversies arising out of or relating to this Agreement, the marketing of the Licensed Material, and/or your participation in the Licensed Material will be brought exclusively in the U.S. District Court for the Northern District of Texas or state courts located in Tarrant County, Texas, United States, and you consent to personal jurisdiction in those forums and waive any objection as to inconvenient forum. Without prejudice to the foregoing, you agree that, in its sole discretion, X may bring any claim, cause of action, or dispute it has against you in any competent court in the country in which you reside that has jurisdiction and venue over the claim.
If you are a federal, state, or local government entity in the United States using the Licensed Material in your official capacity and legally unable to accept the controlling law, jurisdiction, or venue clauses above, then those clauses do not apply to you. For such U.S. federal government entities, this Agreement and any action related thereto will be governed by the laws of the United States of America (without reference to conflict of laws) and, in the absence of federal law and to the extent permitted under federal law, the laws of the State of Texas (excluding choice of law).
2. **YOU HAVE ONE YEAR TO BRING A CLAIM AGAINST X.** You must bring any claim against X arising out of or related to this Agreement within one (1) year after the date of the occurrence of the event or facts giving rise to the dispute unless applicable law provides that the normal statute of limitations for that claim may not be shortened by agreement. If you do not bring a claim within this period, you forever waive the right to pursue any claim or cause of action, of any kind or character, based on such events or facts, and such claims or causes of action are permanently banned and X will have no liability with respect to such claim.
3. **Class Action Waiver.** To the extent permitted by law, you also waive the right to participate as a plaintiff or class member in any purported class action, collective action, or representative action proceeding.
4. **Changes to this Section.** This Dispute Resolution Section survives the end of the relationship between you and X, including cancellation of or unsubscribing from any services or communications provided by X.
5. **Injunctive Relief.** Notwithstanding the foregoing, you agree that money damages would be an inadequate remedy for X in the event of a breach or threatened breach of this Agreement protecting X's intellectual property or Confidential Information, and that in the event of such a breach or threat, X, in addition to any other remedies to which it is entitled, is entitled to preliminary or injunctive relief (including an order prohibiting you from taking actions in breach of such provisions), without the need for posting bond, and specific performance as may be appropriate. The parties agree that neither the United Nations Convention on Contracts for the International Sale of Goods nor the Uniform Computer Information Transaction Act shall apply to this Agreement, regardless of the states in which the parties do business or are incorporated. No waiver by X of any covenant or right under this Agreement will be effective unless memorialized in a writing authorized by X.
**B. THIS SECTION APPLIES TO YOU ONLY IF YOU LIVE IN THE EUROPEAN UNION, EFTA STATES, OR THE UNITED KINGDOM. PLEASE READ THIS SECTION CAREFULLY – IT MAY SIGNIFICANTLY AFFECT YOUR LEGAL RIGHTS, INCLUDING YOUR RIGHT TO FILE A LAWSUIT IN COURT.**
1. **Choice of Law and Forum Selection.** To the extent permitted by law, all disputes related to this Agreement, including any disputes, claims, or controversies arising out of or relating to this Agreement, the marketing of the Licensed Material, and/or your participation in the Licensed Material, will be brought exclusively before a competent court in Ireland without regard to conflict of law provisions and will be governed by Irish law, notwithstanding any agreement between the parties to the contrary. Without prejudice to the foregoing, you agree that, in its sole discretion, X may bring any claim, cause of action, or dispute it has against you in any competent court in the country in which you reside that has jurisdiction and venue over the claim.
2. **YOU HAVE ONE YEAR TO BRING A CLAIM AGAINST X.** You must bring any claim against X arising out of or related to this Agreement within one (1) year after the date of the occurrence of the event or facts giving rise to the dispute unless applicable law provides that the normal statute of limitations for that claim may not be shortened by agreement. If you do not bring a claim within this period, you forever waive the right to pursue any claim or cause of action, of any kind or character, based on such events or facts, and such claims or causes of action are permanently banned, and X will have no liability with respect to such claim.
3. **Class Action Waiver.** To the extent permitted by law, you also waive the right to participate as a plaintiff or class member in any purported class action, collective action, or representative action proceeding.
4. **Changes to this Section.** This Dispute Resolution section survives the end of the relationship between you and X, including cancellation of or unsubscribing from any services or communications provided by X.
5. **Injunctive Relief.** Notwithstanding the foregoing, you agree that money damages would be an inadequate remedy for X in the event of a breach or threatened breach of this Agreement protecting X's intellectual property or Confidential Information, and that in the event of such a breach or threat, X, in addition to any other remedies to which it is entitled (including money damages), is entitled to such preliminary or injunctive relief (including an order prohibiting you from taking actions in breach of such provisions), without the need for posting bond, and specific performance as may be appropriate. The parties agree that neither the United Nations Convention on Contracts for the International Sale of Goods nor the Uniform Computer Information Transaction Act shall apply to this Agreement regardless of the states in which the parties do business or are incorporated. No waiver by X of any covenant or right under this Agreement will be effective unless memorialized in a writing authorized by X.
**XIV. Miscellaneous.**
**A. Assignment.** You shall not assign any of the rights or obligations granted hereunder, in whole or in part, whether voluntarily or by operation of law, contract, merger (whether you are the surviving or disappearing entity), stock or asset sale, consolidation, dissolution, through government action, or otherwise, except with the prior written consent of X. X is authorized to sign modifications and consents for X Internet Unlimited Company, an Irish company responsible for the information of X users who live outside the United States. Any attempted assignment in violation of this Section will be null and void and X may terminate this Agreement.
**B. User Protection.** Unless explicitly approved by X in writing, you shall not use, or knowingly display, distribute, or otherwise make X Content, or information derived from X Content, available for purpose of: (a) conducting or providing surveillance or gathering intelligence, including but not limited to investigating or tracking X users or X Content; (b) conducting or providing analysis or research for any unlawful or discriminatory purpose or in a manner that would be inconsistent with X users' reasonable expectations of privacy; (c) monitoring sensitive events (including but not limited to protests, rallies, or community organizing meetings); or (d) targeting, segmenting, or profiling individuals based on sensitive personal information, including their health (e.g., pregnancy), negative financial status or condition, political affiliation or beliefs, racial or ethnic origin, religious or philosophical affiliation or beliefs, sex life or sexual orientation, trade union membership, X Content relating to any alleged or actual commission of a crime, or any other sensitive categories of personal information prohibited by law.
**C. Government Use.** If you display, distribute, or otherwise make available any X Content to Users that are, or that act on behalf of, any government-related entity (each a “**Government End User**”); (a) you must apply for (or already subscribe to) an Enterprise plan (as described at [developer.x.com](https://developer.x.com)); (b) you shall identify all such Government End Users when submitting your use case for review to X; and (c) you shall thereafter notify X in writing of any new Government End Users or any new use cases with existing Government End Users before the Services display, distribute, or otherwise make available any X Content to a Government End User or for any new use case. X may prohibit you from making X Content available to any Government End User. You shall not use, or knowingly display, distribute, or otherwise make X Content, or information derived from X Content, available to any Government End User whose primary function or mission includes conducting surveillance or gathering intelligence. If law enforcement requests information about X or its users for purposes of an ongoing investigation, you may refer them to X’s Guidelines for Law Enforcement located at [**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support). The X API and X Content are "commercial items" as that term is defined at 48 C.F.R. 2.101, consisting of "commercial computer software" and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212. Any use, modification, derivative, reproduction, release, performance, display, disclosure, or distribution of the X API or X Content by any government entity is prohibited except as expressly permitted by the terms of this Agreement. Additionally, any use by U.S. government entities must be in accordance with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4. If you use the X API or X Content in your official capacity as an employee or representative of a U.S. state or local government entity and you are legally unable to accept the indemnity, jurisdiction, venue, or other clauses herein, then those clauses do not apply to such entity to the extent required by law. Contractor/manufacturer is X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
**D. Compliance with Laws; Export and Import.** Each party will comply with all applicable foreign, federal, state, and local laws, rules and regulations, including without limitation all laws relating to bribery and/or corruption. The Licensed Material is subject to U.S. export laws and may be subject to import and use laws of the country where it is delivered or used. You shall abide by these laws. Under these laws, the Licensed Material may not be sold, leased, downloaded, moved, exported, re-exported, or transferred across borders without a license, or approval from the relevant government authority, to any country or to any foreign national restricted by these laws, including countries embargoed by the U.S. Government (currently Cuba, Iran, North Korea, Northern Sudan and Syria), to any restricted or denied end-user, including but not limited to any person or entity prohibited by the U.S. Office of Foreign Assets Control, or for any restricted end-use. You shall maintain all rights and licenses that are required for your Services.
**E. Data Protection Addendum.** Each party shall comply with the X Controller-to-Controller Data Protection Addendum located at [**https://gdpr.x.com/en/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html), which may be updated by X from time to time.
**F. Survival.** Sections III (Restrictions on Use), V (Ownership and Feedback), VI (Confidentiality), VII(I) (Termination), VIII (Compliance Audit), IX (Warranty Disclaimer), X (Indemnification), XI (Limitation of Liability), XIII (Dispute Resolution and Class Action Waiver); and XIV (Miscellaneous) of this Agreement will survive the termination of this Agreement.
**G. Entire Agreement.** This Agreement constitutes the entire understanding of the parties regarding the subject matter of this Agreement and supersedes all other agreements between the parties related to the subject matter, whether written or oral. If any provision of this Agreement is held by a court of law to be unenforceable, the remaining provisions of the Agreement will remain in effect. No waiver under this Agreement will be effective unless it is in writing and signed by the party granting the waiver. A waiver granted on one occasion will not operate as a waiver on other occasions. This Agreement does not create or imply any partnership, agency or joint venture.
# Display requirements: Posts
Source: https://docs.x.com/developer-terms/display-requirements
Display requirements for showing X Posts in your app, including branding, attribution, anatomy of a Post, interactivity, and metadata to render.
## General principles and Post anatomy
Posts are one of our most visible brand elements, so it’s important that they are presented correctly. You should comply with the display requirements below when you display posts, timelines, and other X content.
If you follow these guidelines merely to display a post, you may not need to contact X for any additional display or trademark permissions. However, you may still want to submit your proposed use and context for X review. (Note that, in some cases, permission from the original content creator may still be necessary, as X does not provide permission to use third party/user content.)
The following general principles apply to all display mediums. Please note, medium-specific requirements do apply, and are outlined in the sections below.
The image below shows all the main components of a post.
### Do
* Display real, unmodified posts from real accounts.
* Follow X’s [Terms of Service](https://x.com/tos?lang=en), the [X Brand Assets and Guidelines](https://about.x.com/en_us/company/brand-resources.html), and (if applicable) the [Developer Agreement and Developer Policy](/developer-terms/agreement).
* Display the X logo.
### Don't
* Use X content to promote any product or service (e.g., by displaying X content in advertising or otherwise displaying X content to imply endorsement of any product or service) without explicit permission from the user.
* Use X content to imply sponsorship by, endorsement from, or a false association with X.
* Include buttons or icons from other social platforms.
* Modify post text.
* Use mock ups of posts that don’t exist on the platform.
***
## Online display / Mobile, web, and beyond
We’re committed to bringing the ease and power of X to everyone. To ensure every post is displayed optimally, we strongly encourage using [embedded posts and/or embedded timelines](https://publish.x.com). When you use these products to publish X content, posts and timelines are automatically rendered correctly, including advanced features like photos, video playback, edited posts, and fetching of up-to-date X data without OAuth. If it is not possible for you to use our embedding features, you must follow the requirements below when displaying posts and timelines online.
### Post author
* The post author’s profile picture, @username, and display name must always be displayed and link to the user’s X profile.
* The post author’s @username must always be displayed with the “@” symbol.
* The post author’s avatar must be positioned to the left of the author’s name and @username—except for posts in languages that read right to left, in which case the author’s avatar must be positioned to the right of the author’s display name and @username.
### Post text
* The post text must be displayed on a line below the author’s display name and @username, and may not be altered or modified.
* On touch devices, the white space around the post text and post author must link to the post’s permalink.
* Post entities within the post text must be properly linked to their appropriate home on X. For example:
* User @mentions must link to the mentioned user’s profile.
* Hashtags must link to a X search with the hashtag as the query.
* Links in post text must be displayed using the display\_url field in the URL entities API response, and link to the original t.co url field.
### Timestamp
* The post timestamp must be displayed and link to the post’s permalink.
### Post Actions
* All post Action icons (including reply, repost, and like) must always be visible for the user to interact with the post. These actions must be implemented using [Web Intents](/x-for-websites/web-intents/overview) or with the authenticated X API. In lieu of post Actions, “View on X” may be shown next to the timestamp, linking the user to the post permalink.
* No other social or third party actions may be attached to a post. (e.g., subscribe, comment, like).
* If the post being displayed is a repost, the display name of the user who reposted it and the repost icon must be displayed above or under the post text. e.g., “reposted by Jane Doe”. The display name must link to the profile of the user who reposted it.
* Follow [guidelines for displaying replies](/developer-terms/reply-requirements).
### Post edits
* X allows people to edit their posts up to 5 times during the first 30 minutes after posting the original post. When using [embedded posts](/x-for-websites/embedded-posts/overview), the display will appear slightly different depending on whether the post was edited before or after it was embedded.
* When a post is embedded first, and then edited, you must display those edits as they occur on the X platform:
* If you are displaying a previous version of an edited post, you must note below the timestamp that there is a new version of the post, and to the right of that note, provide a link which expands the post’s edit history.
* You must then display the full edit history of the post.
When a post has been edited first, and then embedded, you must note in the timestamp that the post was edited, and the timestamp must also link to the live post on X.
### Branding
* The official X logo must always be reasonably visible and displayed on the upper-right corner of an individual post or directly attached to the timeline (e.g., top of the timeline). The logo should be the same height “x” as in the image. See X’s [brand resources page](https://about.x.com/en_us/company/brand-resources.html) for brand guidelines and assets.
### Mobile deep linking
* Deep links from native mobile apps must direct to the native X application. If the native X application is not installed on the device, the link must direct to X.com via a web browser.
### Timelines
* All timelines must allow users to view the details of an individual post (e.g., by linking the post timestamp or by linking the entire post area).
If you plan any advertising near posts, please ensure it complies with the [Developer Policy](/developer-terms/policy).
If for any reason you cannot comply with one or more of these rules, please contact us directly via our [Policy Support form](https://help.x.com/forms/platform) before displaying X content. For questions or further information about use of the X name and trademarks, please contact [trademarks@x.com](mailto:trademarks@x.com).
***
## Broadcast display / 15 minutes of fame
We welcome and encourage the use of X in broadcast media. Our requirements ensure that X users receive proper attribution for their content, and help provide the best experience for your audience.
### Do
* Show the user’s full name, @username, post text, and profile picture.
* Include the X logo in close proximity to the posts for as long as they appear in your broadcast. Make sure that the X logo is sized similarly to the size in the above image, relative to the content.
* Use the full text of the post.
* When displaying images, the post text must also be included along with the user’s display name, @username, and the X logo.
### Don't
* Display X content in advertising or to imply endorsement of any product or service without explicit permission from the user.
* Delete, obscure, or alter the post content or identification of the user (with the exception of removing hyperlinks).
* Exclude the timestamp.
* Do not use X marks, in whole or in part, in the title of your production without first reviewing their use with X by contacting us at [trademarks@X.com](mailto:trademarks@X.com).
***
## Verbal or voice over
### Posts
When reading posts on air with no graphic display of the post, you do not need to display the X logo but you do need to verbally attribute it to X. Read the post as originally written, without edits.
### Usernames
Make sure to include a reference to X when mentioning X usernames. For example, “Follow us on X, at-username” or “You can follow Lady Gaga on X, at-ladygaga”
### Hashtags
Make sure to include a reference to X when mentioning X hashtags. For example, “Use the hashtag ‘election2016’ on X” or “The hashtag for this broadcast on X is bbcaq”.
# Geo guidelines
Source: https://docs.x.com/developer-terms/geo-guidelines
Guidelines for handling geotagged Posts and location data from the X API, including geo features, place objects, and user privacy considerations.
Last Update: October 22, 2014.
## Introduction
Posting With Location is the geotagging feature in the X API. This feature helps to provide a more meaningful experience for users by making posts more contextual. For instance, “Fireworks!” is much more relevant when associated with a location: “Fireworks!” from the SoMa Neighborhood in San Francisco, California. We look forward to working with the developer ecosystem to create great experiences around this functionality!
## User privacy and user control of their location information
To ensure a good and safe experience, developers should be sensitive to user privacy when dealing with their location as well as provide baseline consistency in the “Posting with Location” experience. Here are some key things to keep in mind that help protect user privacy and ensure users understand the impact of their actions:
## General guidelines
* Users must opt-in to use the Posting With Location feature (turn location “on”).
* Users must give explicit permission for their exact location to be displayed with their posts. If the location feature on your client is “sticky” — i.e. once location is turned on it always accompanies a post — you may wish to display only place names (place\_ids) and allow users to further opt in to exact latitude and longitude on a per-post basis or as a specific alternative setting.
* When you access your users’ location data to post a post, that information should not be stored by you apart from the post without the user’s explicit permission.
* It must be clear to users what level of location information, if any, will be displayed in association with their post. One way you can do this is by showing a map of how this information will be displayed before the post is published. If exact latitude and longitude is part of the information (or the only information) published by the user on the client, it should be clear to the user that their exact coordinates will be published.
* Users should be able to turn on and off their location each time they compose a post.
* You must follow the terms of X’s [Developer Policy](/developer-terms/policy.html) – including the requirement that you may not aggregate, cache, or store location data and other geographic information from the X API, except as part of a post, and may not use such location data or geographic information on a standalone basis.
## Specific examples
Example 1: *No addition of explicit latitude and longitude (this is the current X Web Client UI)*
1. Show a link to “Add your location” when a user composes a post;
2. In the background, use the X [reverse\_geocode](https://developer.x.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode.html) API call and pass the latitude, longitude, accuracy of your fix, and the user’s preferred granularity (which, by default, is “neighborhood”);
3. Display the name for the default place (X will attempt to order these in a way that makes sense - the ordering is such that a X client can just display the list without a need for modification);
4. Allow the user to select a different location from the list (e.g. change from “SoMa, San Francisco” to “South Beach, San Francisco”).
5. Important: Be transparent with the user if you will be displaying exact location information. Make sure the user knows if exact location information will be displayed.
6. Allow the user the choice to turn on or off location with every post compose.
Example 2: *Existing geotagging implementations*
A number of X client apps have the original geotagging feature (which only broadcast lat/lons without providing place\_IDs) implemented. The default behavior of the API mimics this behavior – i.e. as a developer you do not need to make any changes to your existing app in order to maintain the behavior that exists today. Indeed, if you simply pass a lat/lon coordinate in to X, X will automatically reverse geocode that latitude and longitude and display the place\_ID in addition to lat/lon for areas where we have data available.
Ensure that it is transparent to your users that their exact coordinates are being used and displayed on X. A best practice for existing apps would be to allow users to turn on or off their location on a per-post basis. You can also enable your users to share only place\_IDs instead of exact coordinates as a default, “sticky” setting.
## X storage of user location data
X will store data passed by the client as follows:
* X will save all the data that a user chooses to publicly display to his/her followers. This is similar to how X stores the time stamp that says when the post was made, meaning if a user posts with their exact coordinates, X will store this exact location along with the post for as long as the post exists. Users can clear location data from their posts by clicking the “clear my location history” button on the Settings page as described [here](https://support.twitter.com/articles/122236-how-to-tweet-with-your-location).
## Summary
The addition of location to a post adds an enormous amount of context and value from a user perspective. However, implementations of location in your client should be careful to take privacy and user transparency as a key consideration in designing a location-focused product.
If you have any questions or comments about privacy, location, and other geo features, please [contact us.](https://support.twitter.com/forms/platform)
# X Developer Policy
Source: https://docs.x.com/developer-terms/policy
The X Developer Policy outlines acceptable use of the X API, including rules around content, automation, privacy, security, and prohibited behaviors.
## X + Developers
X loves developers. We’re delighted and amazed by the tools and services this community creates by harnessing the power of X data. As part of our commitment to this community, we aim to provide data access that is open and fair for developers, safe for people on X, and beneficial for the X platform as a whole. To further these goals we’ve crafted the Developer Policy as a guide to help people understand our rules and expectations about appropriate API and X Content usage.
This Developer Policy (“**Policy**”) provides rules and guidelines for developers who interact with X’s ecosystem of applications, services, website, web pages and content. It is part of your contract with X governing access to and use of the X API and X Content (either as part of the Developer Agreement or other written agreement with X). Policy violations are considered violations of your agreement. This Policy may be changed from time to time without notice. Capitalized terms used in this Policy, which are not defined in this Policy, will have the respective meanings ascribed to them in the [Developer Agreement](/developer-terms/agreement) or the Master License Agreement.
## Using this policy
We’ve structured this policy to make it as easy to follow as possible. Please keep information from the following policy sections top of mind as you use the X API and X Content:
1. **Follow the Platform Usage Guidelines** - Getting approved to access the X API and X Content is just the first step. Our Platform Usage Guidelines should be your first stop anytime you have questions about how to ensure policy compliance for your planned use of the X platform.
2. **Set Yourself Up for Success** - You are responsible for complying with all X policies. It’s important that you review and understand this Policy, as well as the policies we link to in this document, before you access the X API and X Content. The time spent reviewing our policies may save you hours of rework down the road.
3. **Privacy and Control are Essential** - Protecting and defending the privacy of people on X is built into the core DNA of our company. As such, we prohibit the use of X data in any way that would be inconsistent with people’s reasonable expectations of privacy. By building on the X API or accessing X Content, you have a special role to play in safeguarding this commitment, most importantly by respecting people’s privacy and providing them with transparency and control over how their data is used.
We’ve provided a lot more detail on what each of these three key sections mean below. Please review them carefully to ensure that your usage of the X API and X Content is consistent with our policies.
If we believe you are in violation of this Policy (or any other X policy), we may suspend or permanently revoke your access to the X API and X Content.
Finally, please note that X may monitor your use of the X API to improve the X Applications, to examine any commercial use, and to ensure your compliance with your approved use case and this Policy.
Thanks for reading, and thank you for building with us! We look forward to seeing what you create!
## Platform usage guidelines
Have you taken care to review X’s policies and set up your API access the right way? Does your service follow X’s privacy and control guidelines? If you can answer yes to these two questions, then you are ready to start using the X API and X Content. X’s Platform Usage Guidelines provide the assistance needed to ensure that your use of X Content is compliant from day 1 throughout the lifecycle of your service. We suggest reviewing these rules on a regular basis to make sure that your integration is operating in a way that is safe and beneficial to people on X and the X platform as a whole.
## Spam, bots, and automation
**The use of the X API and developer products to create spam, or engage in any form of platform manipulation, is prohibited.** You should review the X Rules on [platform manipulation and spam](https://help.x.com/rules-and-policies/platform-manipulation), and ensure that your service does not, and does not enable people to, violate our policies.
[**Services that perform write actions, including posting Posts, following accounts, or sending Direct Messages, must follow the Automation Rules.**](https://help.x.com/rules-and-policies/x-automation) In particular, you should:
* Always get explicit consent before sending people [automated replies or Direct Messages](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444)
* Immediately respect requests to opt-out of being contacted by you
* Never perform bulk, aggressive, or spammy actions, including [bulk following](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769)
* Never post identical or substantially similar content across [multiple accounts](https://blog.twitter.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html)
**If you’re operating an API-based bot account you must clearly indicate what the account is and who is responsible for it.** You should never mislead or confuse people about whether your account is or is not a bot. A good way to do this is by including a statement that the account is a bot in the profile bio.
## X performance benchmarking
**You may not use the X API to measure the availability, performance, functionality, or usage of X for benchmarking, competitive, or commercial purposes.** For example, you should never use the X API to:
* Calculate aggregate X metrics, such as the total number of Monthly Actives (MAs) or Daily Actives (DAs)
* Calculate aggregate X Post metrics, such as the total number of Posts posted per day, or the number of account engagements
* Measure or analyze the responsiveness of X
* Measure or analyze spam or security on X, except as permitted below
**We support research that helps improve conversational health on X.** You may not publicly disclose any research or findings concerning, or develop, create, or offer services using, the X API or X Content that measure, analyze, or attempt to identify behaviors or content which violate X policies without express written permission from X.
**DSA Researchers:** If you need to contact X relating to access under Art. 40 of the Digital Services Act, please contact [**EU-Questions@X.com**](mailto:EU-Questions@X.com). If you wish to apply for researcher access, please submit an [application](https://forms.gle/btDwenPF7M3hgSvw7).
## Public display of Posts
**You must maintain the integrity of all X Content that you display publicly or to people who use your service.** If you don’t use [X for Websites](https://developer.x.com/docs/twitter-for-websites/overview) to display content, then you must use the X API to retrieve the most current version available for display. If displayed content ceases to be available through the X API, then you must remove it from your service as soon as reasonably possible, or within 24 hours after the receipt of a removal request from X, or the applicable X account owner, or as otherwise required by applicable law.
**There are specific rules you must follow if you display X Content offline.** Follow the [guidelines](https://developer.x.com/developer-terms/display-requirements) for using Posts in broadcast if you display Posts offline.
**If you embed or display Posts, you must contact us about your X API access if your site exceeds 10 million daily impressions.** X reserves the right to require additional terms as a condition to your use of the X API. Additional restrictions on X for Websites developer use include:
* **Embedded Posts and/or embedded timelines**
* You must provide people with legally sufficient notice that fully discloses X’s collection and use of data about browsing activities on your website, including for interest-based advertising and personalization. You must also obtain legally sufficient consent from people for such collection and use
* You must provide legally sufficient instructions on how people can opt out of X’s interest-based advertising and personalization as described [here](https://help.x.com/x-for-websites-ads-info-and-privacy)
* **X for Websites widgets**
* You must ensure that people are provided with clear and comprehensive information about, and consent to, the storing and accessing of cookies or other information on their devices as described in X’s [cookie use](https://help.x.com/rules-and-policies/x-cookies), where providing such information and obtaining such consent is required by law
* **Services targeted to children under 13**
* Services targeted to children under 13 must opt out of tailoring X in any embedded Post and/or embedded timelines by setting the opt-out parameter to be ‘true’ as described [here](https://developer.x.com/docs/twitter-for-websites/privacy)
## Content redistribution
**The best place to get X Content is directly from X. Consequently, we restrict the redistribution of X Content to third parties.** If you provide X Content to third parties, including downloadable datasets or via an API, you may only distribute Post IDs, Direct Message IDs, and/or User IDs (except as described below).
In total, you may not distribute more than 1,500,000 Post IDs to any entity (inclusive of multiple individuals associated with a single entity) within any 30 day period unless you have received written permission from X. In addition, developers may provide up to 500 public Posts Objects and/or User Objects to each person who uses your service on a daily basis if this is done via non-automated means (e.g., download of spreadsheets or PDFs).
Academic researchers are permitted to distribute Post IDs and/or User IDs solely for the purposes of non-commercial research on behalf of an academic institution, and that has been approved by X in writing, or peer review or validation of such research. Only as many Post IDs or User IDs that is necessary for such research, and has been approved by X may be used.
Any X Content provided to third parties remains subject to this Policy, and those third parties must agree to the X [Terms of Service](https://x.com/tos), [Privacy Policy](https://x.com/privacy), [Developer Agreement](/developer-terms/agreement), and [Developer Policy](/developer-terms/policy) before receiving such downloads. You may not enable any entity to circumvent any other limitations or restrictions on the distribution of X Content as contained in this [Policy](/developer-terms/policy), the [Developer Agreement](/developer-terms/agreement), or any other agreement with X.
**Note:** This Section does not apply to researchers with X API access via Art. 40 of the EU Digital Services Act (2022) (“**DSA**”), who are instead subject to the procedures and restrictions set forth in the DSA and the Developer Agreement.
## Pay to engage
**Your service shouldn’t compensate people to take actions on X, as that results in inauthentic engagement that degrades the health of the platform.** As you use the X API you may not sell or receive monetary or virtual compensation for any X actions. This includes, but is not limited to, Posts, follows, unfollows, reposts, likes, comments, and replies.
## Service authenticity
**You must clearly identify your service so that people can understand its source and purpose.** Don’t use names, logos, or URLs that mask your service’s identity and features, or that falsely imply an affiliation with X or third parties. Note that creating applications for the purpose of selling names, or to prevent others from using names, is prohibited.
**You may not use any URL (including shortened URLs) for your service that directs people to:**
* A site that is unrelated to your service
* A spam or malware site
* A site that encourages people to violate X policy
## X name, logo, and likeness
**You may only use and display the X name and logo to identify X as the source of X Content.** You should never use the X name and logo, the X Official Partner Program badge, or any other similar marks or names in a manner that creates a false sense of endorsement, sponsorship, or association with X. The X [Brand Resources](https://about.x.com/who-we-are/brand-toolkit) contain detailed information to help you use the X brand in the right way.
**You may only use the X Verified Account badge and any other enhanced account categorization as it is reported to you by X through the API.** This helps people know that the content your service displays is equivalent to that shown on X.
## Advertising on X
**There are restrictions regarding how and where you are allowed to advertise around X Content.** To start, your advertisements can’t resemble or reasonably be confused by people as a Post. Other rules on advertising include:
* **There must be a clear separation between X Content and your advertisements.** You may not place any advertisements within the X timeline other than X Ads.
* **X reserves the right to serve advertising via the X API.** If you decide to serve X Ads once we start delivering them via the API, we will share a portion of advertising revenue with you in accordance with the relevant terms and conditions.
* **You may not use X Content, or information obtained from the X API to target people with advertising outside of the X platform.**
The following additional rules apply for any use of the X services or features listed below:
## X Login
**You must present people with easy to find options to log into and out of X, for example via the OAuth protocol.** The *Sign in with X* option must be displayed at least as prominently as any other sign-up or sign-in feature on your service. You must also provide people without a X account the opportunity to create one via X.
***Once someone on your service authenticates via Sign in with X you must clearly display their X identity.*** X identity includes the person’s current X @handle, avatar, and X logo. Any display of someone’s X followers on your service must clearly show that the relationship is associated with X.
X reserves the right to monitor the total number of unique users who have authenticated or logged in via Sign In with X (or other X authentication methods) to your products, services, or those made available by or for you or your affiliates and, in the event that total number greatly exceeds the normal levels of other developers subscribed to a similar tier of service, you must apply (or already subscribe) to an Enterprise plan upon written notice from X.
You agree that X may, from time to time, review your *Sign in with X* option and, in its sole discretion, remove this X feature from your service.
## X Cards
**To ensure a quality experience you must develop your Card to render across all platforms where Cards are displayed.** Additional rules that you must follow when using Cards include:
* You must mark your Post as ‘true’ for sensitive media if you plan to display such media within a Card
* You must use HTTPS for hosting all assets within your Card. Your Card should never generate active mixed content browser warnings
* Audio and video content should include stop or pause controls, and default to ‘sound off’ for videos that automatically play content
**You may not exceed or circumvent X’s limitations placed on any Cards, including the Card’s intended use.** Additional restrictions on Cards use include:
* You may not place third-party sponsored content within Cards without X’s approval
* You may not attach monetary incentives (including virtual currency) within your Card or on X from your Card
* You may not include content or actions within your Card that are misleading or not contextually relevant, such as URLs and media.
* You may only attach an App Card to a Post when someone is explicitly promoting or referring to the app in the Post.
## Set yourself up for success
You can avoid many potential pitfalls while using the X API by ensuring that your service has been built the right way from day 1. This section of the Developer Policy contains rules that all developers must follow before using the X API or X Content.
The Free, Basic, and Pro plans (as described at [developer.x.com](http://developer.x.com)) are designed for hobbyists, commercial prototyping, early-stage X product integrations, and supporting applications with limited end-users. If you use the X API and X Content beyond this scope, then you must apply (or already subscribe to) an Enterprise plan (as described at [developer.x.com](http://developer.x.com)).
**We review all proposed uses of the X developer platform to verify policy compliance — so you’re required to disclose (and update, as applicable) your planned use of the X API and X Content in order to be granted and to maintain access.** All new developers must [apply for a developer account](https://developer.x.com/portal/petition/essential/basic-info) to access the X API. Current developers without an approved developer account must apply for one as directed to do so by X. As part of this process, you’ll need to provide us with a written description of your intended uses of the X API and X Content.
Your use case description is binding on you, and any substantive deviation from it may constitute a violation of our rules and result in enforcement action. You must notify us of any substantive modification to your use case and receive approval before you may begin using X Content for that new purpose. Failure to do so may result in suspension and termination of your API and data access.
**By building on the X API or accessing X Content, you must comply with ALL X policies.** These include this [Developer Policy](/developer-terms/policy), the [Automation Rules](https://help.x.com/rules-and-policies/x-automation), the [Display Requirements](https://developer.x.com/developer-terms/display-requirements.html), the [API Restricted Uses Rules](/developer-terms/restricted-use-cases), the [X Rules](https://help.x.com/rules-and-policies/x-rules), and the [X Brand Resources](https://about.x.com/who-we-are/brand-toolkit), as well as any other agreements you enter into with X relating to your use of the X API or X Content, including but not limited to the [Developer Agreement](/developer-terms/agreement) or a Master Licensing Agreement or Order (as applicable). You must also comply with any modifications to these policies and any new policies launched by X. It is your responsibility to monitor the use of your service and to design your service to prevent violations of X policy by people who use it. Failure to do so may result in suspension or termination of your API and X Content access.
**You may not register multiple applications for a single use case or substantially similar or overlapping use cases.** In this context, a “use case” is a consistent set of analyses, displays, or actions performed via an application. "White label" versions of a tool or service are not permissible. If you plan to “white label” versions of your application, you must notify and receive separate approval from us.
*As a single exception to these rules,* you may create and use a maximum of 3 applications for development, staging, and production instances of the same service. These apps must be registered to a single account, and should be clearly identified (in the name and description) as dev, staging, and prod instances of a single service. **You may not use development or staging applications for production purposes.**
**You must keep all API keys or other access credentials private.** You may not use, and may not encourage or facilitate others to use, API keys or other access credentials owned by others.
**Your license agreement with X limits your use of the X API and X Content. Among other things, the X API has rate limits which help to ensure fair data usage and to combat spam on the platform.** You may not exceed or circumvent rate limits, or any other limitations or restrictions described in this Policy or your agreement with X, listed on the [Developer Site](https://developer.x.com/), or communicated to you by X.
**You may not remove or alter any proprietary notices or marks on X Content received via the X API.** This helps to make sure that people know where X Content is coming from, and who it belongs to.
**For data integrity and platform health reasons, you may not interfere with, intercept, disrupt, or disable any features of the X API or the X service.** In other words, use the APIs as intended and documented on [developer.x.com](https://developer.x.com/). Refer to our [HackerOne guidelines](https://hackerone.com/x) for more details about acceptable use.
## Privacy and control are essential
X takes privacy seriously, and we expect everyone using X Content and the X API to do the same. Any use of the X developer platform, X API, or X Content in a manner that is inconsistent with people’s reasonable expectations of privacy may be subject to enforcement action, which can include suspension and termination of API and X Content access.
Your commitment to privacy and control must extend to all uses of X Content and all aspects of the service that you build using our API. To that end, the people using your service must understand and consent to how you use their data, and how you access X on their behalf. This can be accomplished through providing people with a clear, comprehensive, and transparent privacy policy, as well as ensuring that you get express and informed consent from each person using your service before taking any action on their behalf. **Please note that a person authenticating into your service does not by itself constitute consent.**
## Consent & permissions
**In particular, you must get express and informed consent from people before doing any of the following:**
* Taking *any* actions on their behalf. This includes (but is not limited to):
* Posting content to X
* Following/unfollowing accounts
* Modifying profile or account information
* Adding hashtags or any other content to Posts
* Republishing content accessed by means other than via the X API or other X tools
* Using someone’s X Content to promote a product or service
* Storing non-public content such as Direct Messages (DMs), or any other private or confidential information
* Sharing or publishing protected content, or any other private or confidential information
**If your service allows people to post content to X you must do the following before publishing:**
* Show exactly what will be published
* Make it clear to people using your service what geo information (if any) will be added to the content
**If your service allows people to post content to both your service and X, you must do the following before publishing:**
* Obtain permission to post the content
* Explain where you will post the content
**You must respect the protected and blocked status of all X Content. You may not serve content obtained using one person’s authentication token to a different person who is not authorized to view that content.**
* **Protected accounts:** A [protected account](https://help.x.com/safety-and-security/public-and-protected-posts)’s content is only available to people who have been approved by the owner to follow that account. So, if you run a service that accesses protected accounts, you may only do so to serve such content to the specific people with permission to view that content.
* **Blocked accounts:** People on X are able to [block](https://help.x.com/using-x/blocking-and-unblocking-accounts) access to their accounts for any reason they choose. Commingling information obtained from tokens (or any other API-based action) to bypass this choice is not permitted.
**As Direct Messages (DMs) are non-public in nature, services that provide DM features must take extra steps to safeguard personal privacy. You may not serve DM content to people who are not authorized to view that content. If your service provides DM functionality you must also:**
* Notify people if you send read receipt events for DMs. You can do this by providing a notice directly in your service, or by displaying read receipts from other participants in a conversation.
* Get consent before configuring media to be sent in a DM as "shared" (i.e. reusable across multiple DMs). If you do allow media in a DM to be “shared,” you must provide a clear notice that this content will be accessible to anyone with the media’s URL.
## Content compliance
**If you store X Content offline, you must keep it up to date with the current state of that content on X.** Specifically, you must delete or modify any content you have if it is deleted or modified on X. This must be done as soon as reasonably possible, or within 24 hours after receiving a request to do so by X or the applicable X account owner, or as otherwise required by your agreement with X or applicable law. This must be done unless otherwise prohibited by law, and only then with the express written permission of X.
Modified content can take various forms. This includes (but is not limited to):
* Content that has been made private or gained protected status
* Content that has been suspended from the platform
* Content that has had geotags removed from it
* Content that has been withheld or removed from X
## Off-X matching
**We limit the circumstances under which you may match a person on X to information obtained or stored off-X.** Off-X matching involves associating X Content, including a X @handle or user ID, with a person, household, device, browser, or other off-X identifier. You may only do this if you have express opt-in consent from the person before making the association, or as described below.
In situations in which you don’t have a person’s express, opt-in consent to link their X identity to an off-X identifier, we require that any connection you draw be based only on information that someone would reasonably expect to be used for that purpose. In addition, absent a person’s express opt-in consent you may only attempt to match your records about someone to a X identity based on:
* **Information provided directly to you by the person.** Note that records about individuals with whom you have no prior relationship, including data about individuals obtained from third parties, do not meet this standard; and/or
* **Public data.** “Public data” in this context refers to:
* Information about a person that you obtained from a public, generally-available resource (such as a directory of members of a professional association)
* Information on X about a person that is publicly available, including:
* Posts
* Profile information, including an account bio and publicly-stated location
* Display name and @handle
## Your privacy policy
**You must display your service’s privacy policy to people before they are permitted to download, install, or sign up to your service.** It must disclose at least the following information:
* The information that you collect from people who use your service
* How you use and share that information (including with X)
* How people can contact you with inquiries and requests regarding their information
Your privacy policy must be consistent with all applicable laws, and be no less protective of people than [X’s Privacy Policy](https://x.com/privacy) and the [privacy policy of our other services and corporate affiliates](https://help.x.com/rules-and-policies/x-services-and-corporate-affiliates). You must cease your access to the X API and the use of all X Content if you are unable to comply with your and/or X’s Privacy Policy.
## Using geo-data
**Use of geo data comes with additional restrictions due to the sensitive nature of this information.** If your service adds location information to Posts, you must disclose to people:
* When you add location information
* Whether you add location information as a geotag or annotations data
* Whether your location information is listed as a place, or as geographic coordinates
If your application allows people to post with their location you must comply with X’s [geo guidelines](/developer-terms/geo-guidelines) in full.
**Any use of location data or geographic information on a standalone basis is prohibited.** You may not (and may not permit others to) store, aggregate, or cache location data and other geographic information contained in X Content, except as part of a Post. For example, you may not separate location data or geographic information out from Posts to show where individuals have been over time. Heat maps and related tools that show aggregated geo activity (e.g., the number of people in a city using a hashtag) are permitted.
## X passwords
**You may not store X passwords, or request that people provide their X password, account credentials, or developer application information (including consumer key) to you directly.** We suggest the use of [Sign-in with X](/fundamentals/authentication/guides/log-in-with-x) as the authentication tool to link your service and people on X.
# X Developer PPU Agreement
Source: https://docs.x.com/developer-terms/ppu-agreement
The X Developer Pay-Per-Use Agreement covers terms for purchasing and using credits on paid X API services, including billing and usage rules.
By clicking “Pay,” and purchasing credits for use on Paid Services, or by otherwise accessing or using any Licensed Material, you agree to the terms of our Agreement. Credits do not expire unless otherwise specified, and are not transferable or refundable except as required by law. A verified phone number is required to purchase Credits.
This X Developer PPU Agreement (“**Agreement**”) is a binding legal agreement between you (referred to in this Agreement as “**you**”) and X and governs your access to and use of the Licensed Material (defined below), including any Paid Services (defined below).
By accessing or using any Licensed Material (defined below), or clicking on a button to accept the terms of this Agreement or purchase credits for Paid Services, you agree to be bound by the terms of this Agreement. If you do not understand the terms herein or do not accept any part of them, then you may not use or access any Licensed Material. You may not use the Licensed Material or accept this Agreement if you are not of legal age to form a binding contract with X or if you are barred from using or receiving the Licensed Material under applicable law. To purchase and use a Paid Service you must: (i) be at least 18 years old or the age of majority as determined by the laws of the jurisdiction in which you live or (ii) have the express consent of your parent or guardian to purchase and use that Paid Service. If you are a parent or legal guardian and you allow your child (or a child that you are a guardian of) to purchase or use a Paid Service, you agree that the terms of this Agreement apply to you, you will abide by this Agreement, and you are responsible for the child’s activity on the Paid Services and for ensuring that the child also abides by the terms of this Agreement. In any case, as stated in the Who May Use the Services section of the [**X Terms of Service**](https://x.com/tos), you must be at least 13 years old to use the "Services" as defined in the X Terms of Service. If you are accepting this Agreement or using the Licensed Material on behalf of a company, organization, government, or other legal entity, you represent and warrant that you have the authority to bind such company, organization, government, or other legal entity to this Agreement, in which case the words “you” and “your” as used in this Agreement shall refer to such entity. If you do not agree to the terms of this Agreement, you may not (and you may not allow any of your personnel to) access or use the Licensed Material.
I. **Definitions**.
In this Agreement, the following definitions apply:
1. **“Credits”** means virtual units purchased by you to enable usage of Paid Services, with each API call or action deducting a specific number of Credits based on the Pricing Schedule. Credits are not refundable except as required by law, non-transferable, and do not expire unless otherwise specified.
2\. **“Developer Site”** means X’s developer site located at [**https://developer.x.com**](https://developer.x.com/)
3\. **“Direct Message”** means a private message that is sent on X Applications by one user to one or more other specific user(s) using X’s direct messaging function.
4\. **“Intellectual Property Rights”** means all copyrights, moral rights, patent rights, trademarks, and any other intellectual property or similar rights (registered or unregistered) throughout the world.
5\. **“Licensed Material”** means, individually or collectively, the X API and X Content.
6\. **"Paid Service(s)”** means features or functionality of the Licensed Material that you access in exchange for deduction of credits purchased from X and deducted from your account based on your usage of calls and features as detailed on our pricing page. Unless otherwise set forth in this Agreement, all references to “Licensed Material” are intended to include the Paid Service(s).
7\. **“Payment Portal”** means the online portal made available to you to opt-in to your use of the Licensed Material, manage credit purchases for Paid Services, manage payment methods for Paid Services, enable “Auto-Recharge” (see Section VII.F) and update account information.
8\. “**Services”** means your services, websites, applications, and other offerings (including research) that display X Content or otherwise use the Licensed Material.
9\. **“Post”** means a short-form text and multimedia-based message distributed via the X Applications.
10\. **“Pricing Schedule”** means the current list of prices per API call or action, available at [https://developer.x.com/#pricing](https://developer.x.com/#pricing).
11\. **“X”** means (a) X Corp. (865 FM 1209, Building 2, Bastrop, TX 78602, USA) if your principal place of business is outside the European Union, EFTA States, and the United Kingdom; or (b) X Internet Unlimited Company (One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland) if your principal place of business is in the European Union, EFTA States, or the United Kingdom.
12\. **“X API”** means X Application Programming Interfaces (each, an “API”), Software Development Kits (each, an “SDK”), and the related tools, documentation, data, technology, code, and other materials provided by X through the Developer Site.
13\. **“X Applications”** means X’s real-time information service, commonly referred to as “X,” which includes those services currently provided by X at its websites and X-owned, operated, or controlled mobile applications, social plug-ins, and application programming interfaces.
14\. **“X Content”** means Posts, the unique identification number generated for each Post, X end user profile information, and any other data and information made available to you through the X API or by any other means authorized by X, and any copies and derivative works thereof.
15\. **“X Marks”** means the X name, trademarks, and logos that X makes available to you, including via the Developer Site, solely for use in accordance with this Agreement.
16\. **“Users”** means visitors, users, or customers of your Services.
**II. X API and X Content.**
**A. License from X.** Subject to your compliance with the terms of this Agreement and the applicable Incorporated Developer Terms (as defined below), X hereby grants you a non-exclusive, royalty free, non-transferable, non-sublicensable, and revocable license to solely:
1\. Use the X API to integrate X Content into your Services or conduct analysis of the X Content, as explicitly approved by X;
2\. Copy a reasonable amount of and display the X Content on and through your Services to Users, as permitted by this Agreement;
3\. Modify X Content only to format it for display on your Services; and
4\. Use and display X Marks to attribute X Applications as the source of the X Content, as set forth in this Agreement.
**B. License to X.** You hereby grant X a non-exclusive, royalty free, non-transferable, and non-sublicensable revocable license to access, index, and cache by any means, including web spiders and/or crawlers, any webpage or applications on which you display X Content using [**embedded Posts** or **embedded timelines**](https://publish.x.com).
**C. Incorporated Terms.** Your access to and use of the Licensed Material is also subject to, and you shall comply with, the following additional terms and policies (collectively, “**Incorporated Developer Terms**”):
1\. the [**X Developer Policy**](https://docs.x.com/developer-terms/policy);
2\. the [**API Restricted Use Rules**](https://docs.x.com/developer-terms/restricted-use-cases);
3\. the [**X Rules**](https://help.x.com/rules-and-policies/x-rules);
4\. as it relates to your display of any of the X Content, the [**Display Requirements**](https://docs.x.com/developer-terms/display-requirements);
5\. as it relates to your use and display of the X Marks, the [**X Brand Guidelines**](https://about.x.com/who-we-are/brand-toolkit); and
6\. as it relates to taking automated actions on your account, the [**Automation Rules**](https://help.x.com/rules-and-policies/x-automation).
**III. Restrictions on Use.**
**A. Reverse Engineering and other Restrictions.** You shall not and you shall not attempt to (or allow others to): (a) reverse engineer, decompile, disassemble, or translate the X API or otherwise attempt to derive source code, trade secrets, or know-how in or underlying any X API or any portion thereof; (b) interfere with, modify, disrupt, or disable features or functionality of the X API or monitoring mechanisms of the X API; (c) use or access the Licensed Material to create or attempt to create a substitute or similar service or product to the X Applications; (d) sell, rent, lease, sublicense, distribute, redistribute, syndicate, create derivative works of, assign, or otherwise transfer or provide access to, in whole or in part, the Licensed Material to any third party except as expressly permitted in this Agreement; (e) provide use of the X API on a service bureau, rental or managed services basis, or permit other individuals or entities to create links to the X API or "frame" or "mirror" the X API on any other server, or wireless or Internet-based device, or otherwise make available to a third party any token, key, password, or other login credentials to the X API; (f) use the Licensed Material for any illegal, unauthorized, or other improper purpose; (g) use the Licensed Material to derive or obtain non-public information of individual X users; (h) interfere with or disrupt the integrity or performance of the X Applications, X API, or X Content contained therein; (i) remove or alter any proprietary notices or marks on the X Content; (j) attempt to gain unauthorized access to the X Applications, X API, X Content, or related systems or networks; (k) use the X API or X Content to fine-tune or train a foundation or frontier model; or (l) use X Content, by itself or bundled with third party data, or derivative analysis therefrom, to target or serve users with advertising outside of the X Applications.
**B. Commercial Use Restrictions.** If your Services are designated as ‘non-commercial,’ you shall not make Commercial Use (as defined below) of the Licensed Material. Commercial Use restrictions may not apply to officially registered non-profits or NGOs. “Commercial Use” means any use of the Licensed Material or access to the X API: (a) by or for a business (i.e. an entity whose primary purpose is to earn revenue through a product or service), or (b) as part of a product or service that is monetized (e.g., website advertising, licensing fees, in-app promotions, and sponsorships).
**C. No Monitoring or Measuring.** Notwithstanding anything to the contrary, you may use the following information only for non-commercial, internal purposes (e.g., to improve the functionality of the Services): (a) aggregate X Applications user metrics, such as number of active users or accounts on X Applications; (b) the responsiveness of X Applications; and (c) results, usage statistics, data, or other information (in the aggregate or otherwise) derived from analyzing, using, or regarding the performance of the X API. All such information is Confidential Information (as defined below).
**D. Rate Limits.** You will not attempt to exceed or circumvent limitations on access, calls or use of the X API ("Rate Limits"), or otherwise use the X API in a manner that exceeds reasonable request volume, constitutes excessive or abusive usage or does not otherwise comply with this Agreement. API calls and requests will deduct credits from your balance as specified in the Pricing Schedule available at [https://developer.x.com/#pricing](https://developer.x.com/#pricing). If your credit balance is insufficient for a call, requests will be denied until your credit balance is sufficient to allow deduction for that request. If you exceed or X reasonably believes that you have attempted to circumvent Rate Limits, controls to limit use of the X APIs, or are otherwise using Licensed Material in breach of this Agreement, then your ability to use the Licensed Material may be temporarily suspended or permanently blocked. X may monitor your use of the X API to improve the Licensed Material and X Applications and to ensure your compliance with this Agreement and the Incorporated Developer Terms. You agree to comply with X’s requests for additional information in connection with your usage. X may review your use of Licensed Material at any time. X’s granting of access to the X API or allowing use of Licensed Material shall be deemed to be approval of your use or a waiver or limitation on its right to required use that is compliant with this Agreement and X’s policies. No payments made are refundable, however, X may, in its discretion, permit unused Credits to be used for use that is compliant with this Agreement.
**E. Location Data.** You shall not, and you shall not allow others to, aggregate, cache, or store location data and other geographic information contained in the X Content except in conjunction with the X Content to which it is attached. You may only use location data and geographic information to identify the location tagged by the X Content.
**F. Use of X Marks.** You shall not include any of the X Marks in your registered corporate name(s), your logos, or your service or product names. You shall not create any derivative works of the X Marks or use the X Marks in a manner that creates or reasonably implies an endorsement, sponsorship, or association with X. All use of the X Marks and all goodwill arising out of the use will inure to X's benefit. You will not remove or alter any proprietary notices or X Marks on the Licensed Material.
**G. Security.** You will maintain the security of the X API and will not make available to any third party any token, key, password, or other login credentials to the X API. You will use industry standard security measures to prevent unauthorized access or use of any of the features and functionality of the X API, including access by viruses, worms, or any other harmful code or material. You shall keep X Content confidential and secure from unauthorized access by using industry-standard organizational and technical safeguards for such data, and with no less care than you use in connection with securing similar data you store. You will immediately notify X, consult and cooperate with investigations, assist with any required notices, and provide any information reasonably requested by X if you know of or suspect any breach of security or potential vulnerability related to the Licensed Material. You will promptly remedy such breach or potential vulnerability resulting from your access to the Licensed Material.
**H. Digital Services Act.** Notwithstanding anything to the contrary in this Agreement, to the extent you are provided access to the Licensed Material pursuant to the procedures described in Article 40 of the Digital Services Act (Regulation (EU) 2022/2065) (“DSA”), your access and use of the Licensed Material is limited solely to performing research that contributes to the detection, identification, and understanding of systemic risks in the European Union and only to the extent necessary for X to comply with its obligations under the DSA. Any such use of the Licensed Material is non-commercial as described in Section III(B) of this Agreement. You may not disclose, reproduce, license, or otherwise distribute the Licensed Material (including any derivatives thereof) that you retrieve through the X API to any person or entity outside the persons specified within your approved application unless (i) the information is disclosed to the Digital Services Coordinator or other party specifically permitted by the DSA pursuant to the “vetted researcher” status and procedures described in Article 40, or (ii) disclosure is required by law.
**I. Tokens.** X may limit the number of tokens that it provides to you, including but not limited to tokens that enable access and use of functionality or features on X Applications.
**J. Usage Levels Under Agreement.** X may, at any time, review your use of its Licensed Materials under this Agreement, and suspend or terminate your use and require you to file an application for Enterprise access (as described at [**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction)) in order for X to consider your proposed continued use of Licensed Materials.
**K. Prohibition on I-Framing:** You shall not, under any circumstances, embed, display, or otherwise incorporate any Licensed Material, X Content, X API, or elements of the X Applications within an iframe, inline frame, or any similar embedding mechanism on your Services or any other platform. This prohibition is absolute and includes, but is not limited to, attempts to frame X Content for display, integration, or redistribution purposes. Violation of this clause may result in immediate termination of your Developer Agreement and your access to the Licensed Material (e.g., X API, X Data License, Developer Console) as outlined in Section VII.I.
**L. Self-Serve Use.** The Pay-Per-Use, Basic, and Pro plans (as described at [developer.x.com](https://developer.x.com)) are designed for hobbyists, commercial prototyping, initial development, early-stage X product integrations, and supporting applications with a limited number of end-users. If you use the X API beyond this scope, then you must apply (or already subscribe to) an Enterprise plan (as described at [developer.x.com](https://developer.x.com)).
**M. Commercial Use:** If you use the X API beyond the scope of hobbyist projects, commercial prototyping, initial development, early-stage X product integrations, or for applications with a limited number of end-users, then you must apply (or already subscribe to) an Enterprise plan (as described at developer.x.com).
**IV. Updates and Removals.**
**A. Updates.** X may update, modify or discontinue any features or function of the Licensed Material, in whole or in part, from time to time (in each instance, an “Update”). You shall implement and use the most current version of the Licensed Material and make any changes to your Services that are required as a result of the Update, at your sole expense. Updates may adversely affect the way your Services access or communicate with the X API or display X Content. X will not be liable for damages of any sort that result from any Update.
**B. Removals.** If X Content is deleted, gains protected status, or is otherwise suspended, withheld, modified, or removed from the X Applications (including removal of location information), you will make all reasonable efforts to delete or modify that X Content (as applicable) as soon as possible, and in any case within twenty four (24) hours after a written request to do so by X or by an X user with regard to its X Content unless prohibited by law or regulation and with the express written permission of X.
**V. Ownership, Betas, and Feedback.**
**A. Ownership.** Except to the extent expressly stated otherwise in this Agreement, neither party will acquire any right, title, or interest in any Intellectual Property Rights owned or licensed by the other party. The Licensed Material is licensed, not sold, and X (or its licensors or X Application users, as applicable) retains and reserves all rights, including all Intellectual Property Rights, not expressly granted in this Agreement. You shall not do anything inconsistent with X’s ownership, including without limitation, challenging X’s ownership of the X Marks, challenging the validity of the licenses granted in this Agreement, or otherwise copying or exploiting the X Marks except as specifically authorized in this Agreement. If you acquire any rights in the X Marks or any confusingly similar marks, by operation of law or otherwise, you will, at no expense to X, immediately assign those rights to X.
**B. Betas.** X may provide you with early access to non-generally available alphas, betas, research studies, pilots, marketing services, or other programs from time to time (each, a “Beta”). Betas will be considered Confidential Information. Your participation in any Beta is at your own risk, may be subject to additional requirements, and may assist X in research, analyzing, and validating existing or prospective programs, products and/or tools.
**C. Feedback.** X will be free to use any feedback, comments, or suggestions you provide X related to X, the Licensed Material, Betas, or any other of X’s products or services (“Feedback”) in any way without any compensation or obligation to you or any third party and Feedback will be deemed Confidential Information. You hereby irrevocably assign to X all right, title, and interest to Feedback.
**VI. Confidentiality.**
You may be given access to non-public information, software, and specifications relating to the Licensed Material (“Confidential Information”). You may use Confidential Information only as necessary in exercising your rights under this Agreement. You shall not disclose Confidential Information to any third party without X’s prior written consent. You shall protect Confidential Information from unauthorized use, access, or disclosure in the same manner that you would use to protect your own confidential information of a similar nature and in no event with less than a reasonable degree of care.
**VII. Term; Credit Purchase Terms; Credit Deduction; Suspension, and Termination.**
**A. Term.** The term of this Agreement will start on the date (i) you accept the terms herein or (ii) start accessing or using any of the Licensed Material, whichever is earlier, and will continue until you stop accessing and using the Licensed Material unless terminated earlier as described below.
**B. Credit Purchase Terms.** Paid Services provided as part of the Licensed Material are made available through the purchase of Credits that are deducted based on your use of features, benefits, or services, including X API usage, as described on the [https://developer.x.com/#pricing](https://developer.x.com/#pricing), Developer Site and the Payment Portal. If you purchase a Paid Service, you do so by first purchasing Credits in advance by paying the applicable fee upfront via the Payment Portal. Your credit balance will be updated after purchase and deducted as you use Paid Services. You must purchase additional credits as needed to enable access to Paid Services. Credit purchases are non-recurring unless you enable optional “Auto-Recharge” features detailed in Section VII.D. When you purchase credits via the Payment Portal, you expressly agree to the terms herein and authorize the charge. X may provide notifications for low balances. Prices for credits and deduction rates are subject to change from time to time as set forth in the Pricing Schedule. X will provide reasonable advance notice of any material change to prices, which notice may be provided via the Developer Site or Payment Portal. Price changes will apply to future purchases and deductions. If you do not agree with a price change, you may cease purchasing credits and using Paid Services. Credits do not expire unless otherwise specified, and are not transferable or refundable except as required by law.
**C. Credit Deduction:** Access to Paid Services requires sufficient credits in your account. Each API call or request or use of other feature or service specified in the Pricing Schedule will deduct credits from your balance based on the rates specified in the Pricing Schedule. Deduction rates may vary, and the Pricing Schedule is subject to change. X aims to deduct credits at the time of each call or request or use of other feature or service specified in the Pricing Schedule, and to deny Paid Services for which you have an insufficient balance. In that case, you will need to purchase additional credits to enable the Paid Service. You may not maintain a negative credit balance. It is your responsibility to monitor your credit balance to help maintain access to Paid Services.
**D. Usage Disputes**: If you believe there has been an error in credit deductions, you must notify X within thirty (30) days of the disputed deduction via [billing support](https://docs.x.com/forms/billing-support). X will investigate and, if an error is confirmed, adjust your credit balance accordingly. Adjustments are at X’s sole discretion and subject to this Agreement.
**E. Payment Terms.** X may offer payment options that vary by Paid Service, device, operating system, geographic location, or other factors, which may be updated from time to time. These payment options may include web payments using a third party payment processor (“Payment Processor”). When you access a Paid Service, you agree: (i) to pay the price listed for Credits, along with any additional amounts relating to applicable taxes, surcharges, credit card fees, bank fees, foreign transaction fees, foreign exchange fees, and currency fluctuations; and (ii) to abide by any applicable terms of service, privacy policies, or other legal agreements or restrictions (including additional age restrictions) imposed by the Payment Processor in connection with your use of a given payment method. The fee will be charged at the time of Credit purchase. It is your responsibility to monitor your Credit balance and make sure your banking, credit card, debit card, and/or other payment information is up to date, complete, and accurate at all times. If you make a payment for a Paid Service through a Payment Processor, X may receive information about your transaction such as when it was made, what platform you made the purchase on, and other information. X will not be liable for any errors made or delays by the Payment Processor, your bank, your credit card company, or any payment network. All payments to X are non-refundable except as otherwise expressly provided in this Agreement or as required by law.
**F. Optional Auto-Recharge Feature.** You may opt in to an “auto-recharge” feature via the Developer Console, authorizing X to automatically charge your saved payment method a user-selected amount when your credit balance falls below the threshold set in the auto-recharge tool, with charges including the applicable taxes and fees for that amount as per Section VII.E; you may modify or disable this feature at any time through the Payment Portal, and by enabling it, you consent to X, via its third-party Payment Processor, charging the selected amount each time the threshold is met, though failed charges (e.g., due to an invalid payment method) will prevent credit additions. Enabling auto-recharge does not guarantee uninterrupted access to Paid Services. You remain responsible for monitoring your credit balance, regardless of notifications X may provide for low balances or auto-recharge events, and auto-recharge charges are non-refundable except as required by law.
**D. Taxes and fees.** All fees exclude any and all taxes and similar fees now in force, enacted, or imposed in the future on the transaction, delivery of the Licensed Material, or the delivery of the X Content including any sales, use or value added taxes, goods and services tax, consumption tax, customs duties, tariffs, or similar charges. These taxes may include but are not limited to, VAT, GST, sales tax, withholding tax, and any other applicable taxes but exclude taxes solely based on X’s net income. You are responsible for the payment of all such taxes, duties, and charges and any related penalties and interest arising from the payment of such amounts. In addition, a surcharge may be charged to recover costs associated with Digital Services Tax ("DST") or similar jurisdiction-specific taxes or regulatory fees incurred by X in certain jurisdictions. This surcharge will appear as a separate line item on your invoice, where applicable, and will be calculated as a percentage of applicable charges as determined by X in its sole discretion. X may adjust this surcharge at any time, without prior notice, in response to increased tax or fee rates or related administrative costs. Depending on your location, X may be responsible for collecting and reporting information related to transaction taxes arising from your purchase of Paid Services. You grant X permission to provide your account and personal information to relevant tax authorities to fulfill our tax collection and reporting obligations.
**E. Refunds and Cessation of Paid Services.** You may cease using Paid Services at any time by not making further API calls. Unused credits are non-refundable and non-transferable, with no refunds for purchased or used credits, unless required by law. CREDIT PURCHASES ARE PREPAID, NON-REFUNDABLE (UNLESS REQUIRED BY LAW). You may request a refund for unused credits only in accordance with applicable law (e.g., withdrawal rights below). All transactions are final unless you have a right to withdraw pursuant to law, such as provided below.
**1. Withdrawal Right & Refunds for Users Living in EU or UK.** You have a legal right to withdraw from your credit purchase without giving any reason within 14 days from the date of purchase (“Withdrawal Period”). To exercise this right, you must inform X of your decision to withdraw before the Withdrawal Period expires by submitting a clear statement of withdrawal to [billing support](https://docs.x.com/forms/billing-support). If you withdraw within the Withdrawal Period and have not used any credits, X will refund the full amount paid for the credit purchase, including any applicable taxes or fees, within fourteen (14) days of receiving your withdrawal notice, using the same payment method used for the purchase, unless you expressly agree otherwise.
However, you expressly acknowledge and agree that if you use any credits during the Withdrawal Period (e.g., by making API calls or requests), you waive your right to withdraw, as the Paid Services will have begun with your prior express consent and acknowledgment that your withdrawal right is lost upon such use. If you use only a portion of your purchased credits during the Withdrawal Period and then exercise your withdrawal right, X will refund the amount corresponding to the unused credits, calculated based on the Pricing Schedule available at [https://developer.x.com/#pricing](https://developer.x.com/#pricing).
**2. No Withdrawal Right for Users Living in Taiwan.** If you are a consumer residing in Taiwan, you may be entitled to a seven (7) day withdrawal period for credit purchases under the Consumer Protection Act, unless you have used any credits, in which case the right to withdraw is lost. To exercise this right, you must notify X within seven (7) days from the date of purchase at [billing support](https://docs.x.com/forms/billing-support). Refunds for unused credits will be processed in accordance with applicable law.
**F. Credits Are Non-Transferable between X Accounts.** Each purchase of Credits applies to a single X account, meaning that your purchase will apply solely to the account you were using when you purchased the Credits and will not apply to other accounts that you may have access to or control over. If you have or control multiple accounts and you want access to Paid Services on each account, you must purchase the needed Credits on each account individually. You may not allow others to use your X account to access any Licensed Material that such person did not order. You may not purchase Credits or use any Licensed Material if you are a person with whom U.S. persons are not permitted to have dealings pursuant to economic sanctions, including, without limitation, sanctions administered by the United States Department of the Treasury's Office of Foreign Assets Control or any other applicable sanctions authority ("Prohibited Person"). This includes, without limitation, persons located in, a citizen of, or ordinarily resident in the following countries and regions: Cuba, Iran, the Crimea Region of Ukraine, North Korea and Syria. You represent and warrant that you are not a Prohibited Person.
**G. Restrictions and Obligations.** You may only purchase and use Credits and use the Licensed Material if you are legally allowed to use the Licensed Material in your country and you live in a country supported by X for the applicable Credit purchase, Paid Service or Licensed Material. X may, in its discretion, restrict the ability to access the Licensed Material or purchase Credits in certain countries. X reserves the right to modify the list of supported countries from time to time. X reserves the right to refuse sale of Credits or access to Paid Services or to cancel or discontinue the sale or use of a Paid Service or the use of any Licensed Material in its sole discretion.
**H. Suspension.** X may suspend your use of and access to the Licensed Material immediately without notice (a) if X reasonably believes that (i) your use of the Licensed Material would cause damage to, or an inordinate burden upon, the Licensed Material, (ii) you have violated this Agreement, (iii) you create risk or possible legal exposure for X, (iv) X’s provision of the Licensed Material to you is no longer commercially viable; (b) for prolonged inactivity; (c) if X is requested or directed to do so by any competent court of law, regulatory authority, or law enforcement agency; or (d) for failure to pay for the Paid Services. X will not be liable for damages of any sort that result from any such suspension.
**I. Termination.** X may terminate this Agreement for any reason at X’s sole discretion. Such early termination by X shall be effective immediately. If you violate the terms of this Agreement, X may terminate this Agreement for cause immediately upon notice to you and you will not receive a refund for any Credits. You may cancel your access to Paid Services or your use of the Licensed Material on the Developer Site. You will not be entitled to a refund of any Credits, and you will not be entitled to use of any unused Credits. Upon termination of this Agreement: (a) all licenses granted in this Agreement immediately expire and you must cease use of any Licensed Material; and (b) you shall permanently delete all Licensed Material in all forms and types of media, and copies thereof, in your possession. Upon the request of X for any reason, you will promptly (and in any event within ten (10) business days of such request) provide evidence (e.g., screenshots of deletion confirmation) of compliance with the provisions of the aforementioned subpart (b) of this Section. The parties to this Agreement will not be liable to each other for any damages resulting solely from termination of this Agreement as permitted under this Agreement.
**VIII. Compliance Audit.**
X or a mutually agreed upon third party agent subject to obligations of confidentiality will be entitled to inspect and audit any records related to the performance of this Agreement in your control or possession upon reasonable notice to you, and at a reasonable time during normal business hours, for the purpose of verifying compliance with this Agreement and the fees payable to X for the two (2) year period preceding the audit. X may exercise its audit right no more than once every twelve (12) months unless it has reasonable cause for noncompliance, and such audit shall not unreasonably interfere with your business activities. You will provide your full cooperation and assistance with such audit and provide access to all Licensed Material in your possession, applicable agreements, and records. Without limiting the generality of the foregoing, as part of the audit, X may request, and you agree to provide, a written report, signed by an authorized representative, listing your then-current deployment of the Licensed Material. You will pay X within thirty (30) business days after the completion of the audit the amount of any underpayment revealed by any such audit. In addition, if any such audit reveals an underpayment by you of five percent (5%) or more, then you will also reimburse X for the reasonable costs and expenses of such audit. The requirements of this Section will survive for one (1) year following the termination of this Agreement.
**IX. Disclaimer.**
TO THE MAXIMUM EXTENT PERMISSIBLE BY APPLICABLE LAW, THE LICENSED MATERIAL IS PROVIDED TO YOU “AS IS”, “WHERE IS”, WITH ALL FAULTS, AND X DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING WITHOUT LIMITATION WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR CONDITIONS ARISING OUT OF THIS AGREEMENT, COURSE OF DEALING OR USAGE OF TRADE. X DOES NOT WARRANT THAT THE LICENSED MATERIAL OR ANY OTHER X PRODUCT OR SERVICE PROVIDED HEREUNDER WILL MEET ANY OF YOUR REQUIREMENTS OR THAT USE OF SUCH LICENSED MATERIAL OR OTHER PRODUCTS OR SERVICES WILL BE ERROR-FREE, UNINTERRUPTED, VIRUS-FREE, OR SECURE. YOU ARE RESPONSIBLE FOR YOUR USE OF THE LICENSED MATERIAL AND ANY CONTENT YOU PROVIDE. THIS DISCLAIMER OF WARRANTY MAY NOT BE VALID IN SOME JURISDICTIONS AND YOU MAY HAVE WARRANTY RIGHTS UNDER LAW WHICH MAY NOT BE WAIVED OR DISCLAIMED.
**FURTHER YOU UNDERSTAND AND AGREE THAT THE PAID SERVICES ARE PROVIDED TO YOU ON AN “AS IS” AND “AS AVAILABLE” BASIS.**
**X. Indemnification.**
You shall defend X against any and all proceedings, demands, claims, and suits (including without limitation product liability claims), and indemnify X from any and all liabilities, damages, and costs (including without limitation reasonable attorneys' fees) to the extent arising out of (a) your use of the Licensed Material in any manner that is inconsistent with this Agreement or (b) the performance, promotion, sale, or distribution of your Services. If X seeks indemnification or defense from you under this Section, X will promptly notify you in writing of the claim(s) brought against X for which it seeks indemnification or defense. X may assume full control of the defense of claims with legal counsel of its choice. You shall not enter into any third-party agreement that would affect the rights of X, constitute an admission of fault by X, or bind X in any manner without the prior written consent of X. If X assumes control of the defense of such claim, X shall not settle any such claim requiring payment from you without your prior written approval.
**XI. Limitation of Liability.**
IN NO EVENT WILL X BE LIABLE TO YOU OR ANY USERS FOR ANY INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL DAMAGES OR ANY LOSS OF OR DAMAGE TO USE, DATA, BUSINESS, GOODWILL OR PROFITS ARISING OUT OF OR IN CONNECTION WITH THIS AGREEMENT. IN ANY CASE, X'S AGGREGATE LIABILITY FOR ANY AND ALL CLAIMS UNDER THIS AGREEMENT WILL NOT EXCEED FIFTY DOLLARS (\$50.00). THE FOREGOING LIMITATIONS, EXCLUSIONS AND DISCLAIMERS SHALL APPLY REGARDLESS OF WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON CONTRACT, WARRANTY, TORT, STRICT LIABILITY OR OTHERWISE, AND WHETHER OR NOT X HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. IF APPLICABLE LAW PROHIBITS ANY LIMITATION ON LIABILITY HEREIN, THE PARTIES AGREE THAT THE LIMITATION WILL BE DEEMED TO HAVE BEEN MODIFIED TO CONFORM TO APPLICABLE LAW. THE PARTIES AGREE THAT THE LIMITATIONS ON LIABILITIES SET FORTH HEREIN ARE AGREED ALLOCATIONS OF RISK AND SUCH LIMITATIONS WILL APPLY NOTWITHSTANDING THE FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY.
**XII. Agreement Updates.**
X may update or amend this Agreement or any of the Incorporated Developer Terms from time to time. You will check the Developer Site regularly for updates. X will alert you of material revisions to these terms by posting the updated terms on these sites, via a service notification, or by other suitable means (e.g., via email to an email address associated with your account). The changes will not be retroactive and the most current version of this Agreement, available at the Developer Site, will govern your access to and use of the Licensed Material and any corresponding transactions. Your continued access or use of the Licensed Material will constitute binding acceptance of such updates and modifications.
**XIII. Dispute Resolution and Class Action Waiver.**
**A. THIS SECTION APPLIES TO YOU ONLY IF YOU LIVE OUTSIDE THE EUROPEAN UNION, EFTA STATES, OR THE UNITED KINGDOM, INCLUDING IF YOU LIVE IN THE UNITED STATES. PLEASE READ THIS SECTION CAREFULLY – IT MAY SIGNIFICANTLY AFFECT YOUR LEGAL RIGHTS, INCLUDING YOUR RIGHT TO FILE A LAWSUIT IN COURT.**
**1. Choice of Law and Forum Selection.** The laws of the State of Texas, excluding its choice of law provisions, will govern this Agreement and any dispute that arises between you and X, notwithstanding any other agreement between the parties to the contrary. All disputes related to this Agreement, including any disputes, claims, or controversies arising out of or relating to this Agreement, the marketing of the Licensed Material, and/or your participation in the Licensed Material will be brought exclusively in the U.S. District Court for the Northern District of Texas or state courts located in Tarrant County, Texas, United States, and you consent to personal jurisdiction in those forums and waive any objection as to inconvenient forum. Without prejudice to the foregoing, you agree that, in its sole discretion, X may bring any claim, cause of action, or dispute it has against you in any competent court in the country in which you reside that has jurisdiction and venue over the claim.
If you are a federal, state, or local government entity in the United States using the Licensed Material in your official capacity and legally unable to accept the controlling law, jurisdiction, or venue clauses above, then those clauses do not apply to you. For such U.S. federal government entities, this Agreement and any action related thereto will be governed by the laws of the United States of America (without reference to conflict of laws) and, in the absence of federal law and to the extent permitted under federal law, the laws of the State of Texas (excluding choice of law).
**2. YOU HAVE ONE YEAR TO BRING A CLAIM AGAINST X.** You must bring any claim against X arising out of or related to this Agreement within one (1) year after the date of the occurrence of the event or facts giving rise to the dispute unless applicable law provides that the normal statute of limitations for that claim may not be shortened by agreement. If you do not bring a claim within this period, you forever waive the right to pursue any claim or cause of action, of any kind or character, based on such events or facts, and such claims or causes of action are permanently banned and X will have no liability with respect to such claim.
**3. Class Action Waiver.** To the extent permitted by law, you also waive the right to participate as a plaintiff or class member in any purported class action, collective action, or representative action proceeding.
**4. Changes to this Section.** This Dispute Resolution Section survives the end of the relationship between you and X, including cancellation of or unsubscribing from any services or communications provided by X.
**5. Injunctive Relief.** Notwithstanding the foregoing, you agree that money damages would be an inadequate remedy for X in the event of a breach or threatened breach of this Agreement protecting X's intellectual property or Confidential Information, and that in the event of such a breach or threat, X, in addition to any other remedies to which it is entitled, is entitled to preliminary or injunctive relief (including an order prohibiting you from taking actions in breach of such provisions), without the need for posting bond, and specific performance as may be appropriate. The parties agree that neither the United Nations Convention on Contracts for the International Sale of Goods nor the Uniform Computer Information Transaction Act shall apply to this Agreement, regardless of the states in which the parties do business or are incorporated. No waiver by X of any covenant or right under this Agreement will be effective unless memorialized in a writing authorized by X.
**B. THIS SECTION APPLIES TO YOU ONLY IF YOU LIVE IN THE EUROPEAN UNION, EFTA STATES, OR THE UNITED KINGDOM. PLEASE READ THIS SECTION CAREFULLY – IT MAY SIGNIFICANTLY AFFECT YOUR LEGAL RIGHTS, INCLUDING YOUR RIGHT TO FILE A LAWSUIT IN COURT.**
**1. Choice of Law and Forum Selection.** To the extent permitted by law, all disputes related to this Agreement, including any disputes, claims, or controversies arising out of or relating to this Agreement, the marketing of the Licensed Material, and/or your participation in the Licensed Material, will be brought exclusively before a competent court in Ireland without regard to conflict of law provisions and will be governed by Irish law, notwithstanding any agreement between the parties to the contrary. Without prejudice to the foregoing, you agree that, in its sole discretion, X may bring any claim, cause of action, or dispute it has against you in any competent court in the country in which you reside that has jurisdiction and venue over the claim.
**2. YOU HAVE ONE YEAR TO BRING A CLAIM AGAINST X.** You must bring any claim against X arising out of or related to this Agreement within one (1) year after the date of the occurrence of the event or facts giving rise to the dispute unless applicable law provides that the normal statute of limitations for that claim may not be shortened by agreement. If you do not bring a claim within this period, you forever waive the right to pursue any claim or cause of action, of any kind or character, based on such events or facts, and such claims or causes of action are permanently banned, and X will have no liability with respect to such claim.
**3. Class Action Waiver.** To the extent permitted by law, you also waive the right to participate as a plaintiff or class member in any purported class action, collective action, or representative action proceeding.
**4. Changes to this Section.** This Dispute Resolution section survives the end of the relationship between you and X, including cancellation of or unsubscribing from any services or communications provided by X.
**5. Injunctive Relief.** Notwithstanding the foregoing, you agree that money damages would be an inadequate remedy for X in the event of a breach or threatened breach of this Agreement protecting X's intellectual property or Confidential Information, and that in the event of such a breach or threat, X, in addition to any other remedies to which it is entitled (including money damages), is entitled to such preliminary or injunctive relief (including an order prohibiting you from taking actions in breach of such provisions), without the need for posting bond, and specific performance as may be appropriate. The parties agree that neither the United Nations Convention on Contracts for the International Sale of Goods nor the Uniform Computer Information Transaction Act shall apply to this Agreement regardless of the states in which the parties do business or are incorporated. No waiver by X of any covenant or right under this Agreement will be effective unless memorialized in a writing authorized by X.
**XIV. Miscellaneous.**
**A. Assignment.** You shall not assign any of the rights or obligations granted hereunder, in whole or in part, whether voluntarily or by operation of law, contract, merger (whether you are the surviving or disappearing entity), stock or asset sale, consolidation, dissolution, through government action, or otherwise, except with the prior written consent of X. X is authorized to sign modifications and consents for X Internet Unlimited Company, an Irish company responsible for the information of X users who live outside the United States. Any attempted assignment in violation of this Section will be null and void and X may terminate this Agreement.
**B. User Protection.** Unless explicitly approved by X in writing, you shall not use, or knowingly display, distribute, or otherwise make X Content, or information derived from X Content, available for purpose of: (a) conducting or providing surveillance or gathering intelligence, including but not limited to investigating or tracking X users or X Content; (b) conducting or providing analysis or research for any unlawful or discriminatory purpose or in a manner that would be inconsistent with X users' reasonable expectations of privacy; (c) monitoring sensitive events (including but not limited to protests, rallies, or community organizing meetings); or (d) targeting, segmenting, or profiling individuals based on sensitive personal information, including their health (e.g., pregnancy), negative financial status or condition, political affiliation or beliefs, racial or ethnic origin, religious or philosophical affiliation or beliefs, sex life or sexual orientation, trade union membership, X Content relating to any alleged or actual commission of a crime, or any other sensitive categories of personal information prohibited by law.
**C. Government Use**. If you display, distribute, or otherwise make available any X Content to Users that are, or that act on behalf of, any government-related entity (each a “**Government End User**”); (a) you must apply for (or already subscribe to) an Enterprise plan (as described at [**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction)); (b) you shall identify all such Government End Users when submitting your use case for review to X; and (c) you shall thereafter notify X in writing of any new Government End Users or any new use cases with existing Government End Users before the Services display, distribute, or otherwise make available any X Content to a Government End User or for any new use case. X may prohibit you from making X Content available to any Government End User. You shall not use, or knowingly display, distribute, or otherwise make X Content, or information derived from X Content, available to any Government End User whose primary function or mission includes conducting surveillance or gathering intelligence. If law enforcement requests information about X or its users for purposes of an ongoing investigation, you may refer them to X’s Guidelines for Law Enforcement located at [**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support). The X API and X Content are "commercial items" as that term is defined at 48 C.F.R. 2.101, consisting of "commercial computer software" and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212. Any use, modification, derivative, reproduction, release, performance, display, disclosure, or distribution of the X API or X Content by any government entity is prohibited except as expressly permitted by the terms of this Agreement. Additionally, any use by U.S. government entities must be in accordance with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4. If you use the X API or X Content in your official capacity as an employee or representative of a U.S. state or local government entity and you are legally unable to accept the indemnity, jurisdiction, venue, or other clauses herein, then those clauses do not apply to such entity to the extent required by law. Contractor/manufacturer is X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
**D. Compliance with Laws; Export and Import.** Each party will comply with all applicable foreign, federal, state, and local laws, rules and regulations, including without limitation all laws relating to bribery and/or corruption. The Licensed Material is subject to U.S. export laws and may be subject to import and use laws of the country where it is delivered or used. You shall abide by these laws. Under these laws, the Licensed Material may not be sold, leased, downloaded, moved, exported, re-exported, or transferred across borders without a license, or approval from the relevant government authority, to any country or to any foreign national restricted by these laws, including countries embargoed by the U.S. Government (currently Cuba, Iran, North Korea, Northern Sudan and Syria), to any restricted or denied end-user, including but not limited to any person or entity prohibited by the U.S. Office of Foreign Assets Control, or for any restricted end-use. You shall maintain all rights and licenses that are required for your Services.
**E. Data Protection Addendum.** Each party shall comply with the X Controller-to-Controller Data Protection Addendum located at [**https://gdpr.x.com/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html), which may be updated by X from time to time.
**F. Survival.** Sections III (Restrictions on Use), V (Ownership and Feedback), VI (Confidentiality), VII(I) (Termination), VIII (Compliance Audit), IX (Warranty Disclaimer), X (Indemnification), XI (Limitation of Liability), XIII (Dispute Resolution and Class Action Waiver); and XIV (Miscellaneous) of this Agreement will survive the termination of this Agreement.
**G. Entire Agreement.** This Agreement constitutes the entire understanding of the parties regarding the subject matter of this Agreement and supersedes all other agreements between the parties related to the subject matter, whether written or oral. If any provision of this Agreement is held by a court of law to be unenforceable, the remaining provisions of the Agreement will remain in effect. No waiver under this Agreement will be effective unless it is in writing and signed by the party granting the waiver. A waiver granted on one occasion will not operate as a waiver on other occasions. This Agreement does not create or imply any partnership, agency or joint venture.
[**DEVELOPER POLICY AND TERMS**](https://docs.x.com/developer-terms)
FOLLOW [**@XDEVELOPERS**](https://x.com/XDevelopers)
[**Subscribe to developer news**](https://developer.x.com/twitterdev-news-subscription)
# Display requirements: Replies
Source: https://docs.x.com/developer-terms/reply-requirements
Display requirements for showing replies to Posts in apps that use the X API, including thread structure, attribution, and reply context rules.
## Reply
Please follow the following guidelines for displaying replies.
### For a default reply:
### For a reply with social context:
### For a Quote:
# Restricted uses of the X API
Source: https://docs.x.com/developer-terms/restricted-use-cases
Details on restricted use cases for the X API, including off-platform tracking, government surveillance, sensitive data handling, and prohibited tools.
Use of our developer platform requires that you review and agree to our [Developer Agreement and Policy](/developer-terms/agreement), as well as our related policies, including the [Display Requirements](https://docs.x.com/developer-terms/display-requirements) and [Automation Rules](https://help.x.com/en/rules-and-policies/twitter-automation). Among other things, our agreements and policies provide guidance about several restricted use cases. We’ve provided additional information about some of these restrictions below.
## Automation, spam, and auto-responses
The use of X's APIs and developer products to create spam, or engage in spammy behavior, is prohibited. You should review the [X Rules](https://t.co/rules) on spam, and ensure that your application does not, and does not enable users to, violate our policies.
If your application will be used to perform write actions on the X service, including posting Posts, following accounts, or sending Direct Messages, you should carefully review the [Automation Rules](https://support.x.com/articles/76915) to ensure your service complies with our guidelines. In particular, you should:
* Always get a user’s explicit consent before sending them [automated replies or messages](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444)
* Immediately respect user requests to opt-out of being contacted by you
* Never perform bulk, aggressive, or spammy actions, including [bulk following](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769)
* Never post identical or substantially similar content across [multiple accounts](https://blog.x.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html)
## Sensitive information
You should be careful about using X data to derive or infer potentially sensitive characteristics about X users. Never derive or infer, or store derived or inferred, information about a X user’s:
* Health (including pregnancy)
* Negative financial status or condition
* Political affiliation or beliefs
* Racial or ethnic origin
* Religious or philosophical affiliation or beliefs
* Sex life or sexual orientation
* Trade union membership
* Alleged or actual commission of a crime
Aggregate analysis of X content that does not store any personal data (for example, user IDs, usernames, and other identifiers) is permitted, provided that the analysis also complies with applicable laws and all parts of the Developer Agreement and Policy.
## Off-X matching
Off-X matching involves associating X content, including a X username or user ID, with a person, household, device, browser, or other off-X identifier. One example would be associating a X username with a business’s customer records (i.e. “John Doe” in your customer record is matched to @johndoe on X).
We want people to feel comfortable to create a separate and, if they choose, pseudonymous identity on X. If you intend to associate any information about a X user with an off-X identifier, we require that you get express, opt-in consent from the user before making the association. For example, you could get this consent if the user shares their X handle directly with you as part of a signup process for your service.
In situations in which you do not have a user’s express, opt-in consent to link their X identity to an off-X identifier, we require that any connection you draw be based only on information that a user would reasonably expect to be used for that purpose. If a user would be surprised to learn that you are using information they provided to link their X account to an identity off of X, don’t do it. In addition, absent a person’s express opt-in consent you may only attempt to match your records about someone to a X identity based on:
* **Information provided directly to you by the user.** Records about individuals with whom you have no prior relationship, including data about individuals obtained from third parties, do not meet this standard; and/or
* **Public data.** “Public data” in this context refers to:
* Information about a user which you obtained from a public, generally-available resource (such as a directory of members of a professional association)
* Information on X about a user which is publicly available, including:
* Posts
* Profile information, including a user’s bio and publicly-stated location
* Display name and username
## Redistribution of X content
If you need to share X content you obtained via the X APIs with another party, the best way to do so is by sharing Post IDs, Direct Message IDs, and/or User IDs, which the end user of the content can then rehydrate (i.e. request the full Post, User, or Direct Message content) using the X APIs. This helps ensure that end users of X content always get the most current information directly from us.
We permit limited redistribution of hydrated X content via non-automated means. If you choose to share hydrated X content with another party in this way, you may only share up to 50,000 hydrated public Post Objects and/or User Objects per recipient, per day, and should not make this data publicly available (for example, as an attachment to a blog post or in a public Github repository).
There are a few other points to keep in mind about redistributing X content:
* You may only distribute up to a total of 1,500,000 Post IDs to a single entity within a 30 day period unless you’ve received prior express written permission from X.
* Individuals redistributing Post IDs and/or User IDs on behalf of an academic institution for the sole purpose of non-commercial research are permitted to redistribute an unlimited number of Post IDs and/or User IDs.
* To request permission to share X content as outlined above, please use the API Policy support form.
To the extent you are permitted to distribute X content to a third party, note that this content remains subject to the Developer Agreement and Policy, and those third parties must agree to the X [Terms of Service](https://x.com/en/tos), [Privacy Policy](https://x.com/en/privacy), [Developer Agreement](/developer-terms/agreement), and [Developer Policy](/developer-terms/policy) before receiving X content.
## Multiple applications
You are not permitted to register multiple applications for a single use case, or substantially similar or overlapping use cases. Learn more about these policies [here](https://twittercommunity.com/t/policy-clarification-multiple-applications-for-the-same-use-case/92080).
In this context, we define “use case” as a consistent set of analyses, displays, or actions performed via an application. Providing the same service or application to different end users counts as a single use case: however, "white label" versions of a tool or service are not included. If you plan to "white label" versions of your application, you must notify and receive separate approval from us. These rules apply both to applications you register, and to applications registered by the end users of your tool or service; requiring your end users to register applications for the purpose of using your tool or service could result in enforcement actions against you, your applications, your customers, and/or the end users of your tool or service.
The only exception to this rule is to create development (“dev”), staging, and production (“prod”) instances of the same service. Ensure that these applications are clearly labeled (for instance, in the application name or description), and that you do not use development or staging applications for production purposes.
## Measuring the X service
Do not use the X APIs to measure the availability, performance, functionality, or usage of X for benchmarking or competitive purposes. For example, you should never use the X APIs to:
* Calculate aggregate X user metrics, such as the total number of active users or accounts
* Calculate aggregate X Post metrics, such as the total number of Posts per day, or the number of user engagements or account engagements
* Measure or analyze spam or security on X, except as permitted in the [X Rules](https://help.x.com/en/rules-and-policies/twitter-rules)
## Surveillance, privacy, and user protection
At X, protecting and defending the privacy of our users is built into the core DNA of our company — and our developer and data products reflect that commitment. We believe that X data can be a powerful force for good in the world — from saving lives during flooding in Jakarta to helping the USGS track earthquakes to working with the UN to achieve the Sustainable Development Goals. However, we prohibit the use of X data and the X APIs by any entity for surveillance purposes, or in any other way that would be inconsistent with our users' reasonable expectations of privacy. Period.
We describe prohibited uses of our data and developer products in the [Developer Agreement](/developer-terms/agreement), including prohibitions on investigating or tracking X users or their content, as well as tracking, alerting, or monitoring sensitive events (such as protests, rallies, or community organizing meetings).
Other categories of activities prohibited under these terms include (but are not limited to):
* Investigating or tracking sensitive groups and organizations, such as unions or activist groups
* Background checks or any form of extreme vetting
* Credit or insurance risk analyses
* Individual profiling or psychographic segmentation
* Facial recognition
These policies apply to all users of our APIs. Any misuse of the X APIs for these purposes will be subject to enforcement action, which can include suspension and termination of access.
For additional information for law enforcement authorities seeking information about X accounts, visit [https://t.co/le](https://t.co/le).
In addition, at this time, X prohibits any use of the X APIs and/or X Content to fine-tune or train a foundation or frontier model with the exception of [Grok](https://help.x.com/en/using-x/about-grok).
# Create Account Activity replay job
Source: https://docs.x.com/enterprise-api/account-activity/create-replay-job
post /2/account_activity/replay/webhooks/{webhook_id}/subscriptions/all
Create a replay job to redeliver Account Activity API events for an Enterprise webhook subscription over a specified time window of up to five days.
# Create subscription
Source: https://docs.x.com/enterprise-api/account-activity/create-subscription
post /2/account_activity/webhooks/{webhook_id}/subscriptions/all
Creates an Account Activity subscription for the user and the given webhook.
# Delete subscription
Source: https://docs.x.com/enterprise-api/account-activity/delete-subscription
delete /2/account_activity/webhooks/{webhook_id}/subscriptions/{user_id}/all
Deletes an Account Activity subscription for the given webhook and user ID.
# Get subscription count
Source: https://docs.x.com/enterprise-api/account-activity/get-subscription-count
get /2/account_activity/subscriptions/count
Retrieves a count of currently active Account Activity subscriptions.
# Get subscriptions
Source: https://docs.x.com/enterprise-api/account-activity/get-subscriptions
get /2/account_activity/webhooks/{webhook_id}/subscriptions/all/list
Retrieves a list of all active subscriptions for a given webhook.
# V2 Account Activity API
Source: https://docs.x.com/enterprise-api/account-activity/introduction
The Account Activity API (AAA) provides a way to receive real-time events related to X. Reference for the Enterprise X API tier covering account activity.
The Account Activity API (AAA) provides a way to receive real-time events related to X user accounts via webhooks. By subscribing specific user accounts to a pre-configured webhook, your application can be notified of various activities such as Posts, Direct Messages, Likes, Follows, Blocks, and more, from one or more of your owned or subscribed accounts through a single connection.
This API is commonly used to build applications that need to react instantly to user actions or maintain an up-to-date state based on user activity.
## Overview
Events delivered to your server in real-time
Delivers data at the speed of X — no polling required
Posts, DMs, follows, likes, blocks, mutes, and more
Subscribe user accounts to receive all their activity
***
## How it works
1. **Register webhook** — Register your webhook URL via the [V2 Webhooks API](/x-api/webhooks/introduction)
2. **Subscribe users** — Add user subscriptions to your webhook
3. **Receive events** — Get activity events delivered as POST requests with JSON payloads
4. **Process events** — Handle events in your application and respond with `200 OK`
***
## Activity types
You will receive all related activities below for each user subscription on your webhook registration:
* **Posts** (by user)
* **Post deletes** (by user)
* **@mentions** (of user)
* **Replies** (to or from user)
* **Reposts** (by user or of user)
* **Quote Posts** (by user or of user)
* **Reposts of Quoted Posts** (by user or of user)
* **Likes** (by user or of user)
* **Follows** (by user or of user)
* **Unfollows** (by user or of user)
* **Blocks** (by user or of user)
* **Unblocks** (by user or of user)
* **Mutes** (by user or of user)
* **Unmutes** (by user or of user)
* **Direct Messages sent** (by user)
* **Direct Messages received** (by user)
* **Typing indicators** (to user)
* **Read receipts** (to user)
* **Subscription revokes** (by user)
We do not deliver home timeline data via the Account Activity API. Use the [User Posts timeline by User ID](/x-api/users/get-posts) endpoint to pull this data.
The returned Posts from the Account Activity API count towards the monthly [Post cap](/x-api/fundamentals/post-cap).
***
## Feature summary
| Tier | Number of Unique Subscriptions | Number of Webhooks |
| :---------- | :----------------------------- | :----------------- |
| Pay Per Use | 3 | 1 |
| Enterprise | 5000+ | 5+ |
***
## Account Activity data object structure
| Object | Details |
| :-------------- | :--------------------------------------------------------------------------------------------------------- |
| `for_user_id` | Identifies the user subscription that the event is related to. |
| `is_blocked_by` | (Conditional) Shown only for Post mention events if the mentioning user is blocked by the subscribed user. |
| `source` | The user performing the activity (e.g., the user following, blocking, or muting). |
| `target` | The user the activity applies to (e.g., the user being followed, blocked, or muted). |
### Available activities
| Message Type | Details |
| :-------------------------------------- | :--------------------------------------------------------------------------------------------- |
| `tweet_create_events` | Post status for Posts, Retweets, Replies, @mentions, Quote Tweets, or Retweet of Quote Tweets. |
| `favorite_events` | Like event with user and target. |
| `follow_events` | Follow event with user and target. |
| `unfollow_events` | Unfollow event with user and target. |
| `block_events` | Block event with user and target. |
| `unblock_events` | Unblock event with user and target. |
| `mute_events` | Mute event with user and target. |
| `unmute_events` | Unmute event with user and target. |
| `user_event` | Revoke events when a user removes app authorization (subscription auto-deleted). |
| `direct_message_events` | DM status for sent or received messages. |
| `direct_message_indicate_typing_events` | DM typing event with user and target. |
| `direct_message_mark_read_events` | DM read event with user and target. |
| `tweet_delete_events` | Notice of deleted Posts for compliance. |
***
## Payload examples
Below are example payloads for each Account Activity event.
### tweet\_create\_events (Posts, Retweets, Replies, QuoteTweets)
```json theme={null}
{
"for_user_id": "2244994945",
"tweet_create_events": [
{
}
]
}
```
### tweet\_create\_events (@mentions)
```json theme={null}
{
"for_user_id": "2244994945",
"user_has_blocked": "false",
"tweet_create_events": [
{
}
]
}
```
### favorite\_events
```json theme={null}
{
"for_user_id": "2244994945",
"favorite_events": [{
"id": "a7ba59eab0bfcba386f7acedac279542",
"created_at": "Mon Mar 26 16:33:26 +0000 2018",
"timestamp_ms": 1522082006140,
"favorited_status": {
},
"user": {
}
}]
}
```
### follow\_events
```json theme={null}
{
"for_user_id": "2244994945",
"follow_events": [{
"type": "follow",
"created_timestamp": "1517588749178",
"target": {
},
"source": {
}
}]
}
```
### unfollow\_events
```json theme={null}
{
"for_user_id": "2244994945",
"follow_events": [{
"type": "unfollow",
"created_timestamp": "1517588749178",
"target": {
},
"source": {
}
}]
}
```
### block\_events
```json theme={null}
{
"for_user_id": "2244994945",
"block_events": [{
"type": "block",
"created_timestamp": "1518127020304",
"source": {
},
"target": {
}
}]
}
```
### unblock\_events
```json theme={null}
{
"for_user_id": "2244994945",
"block_events": [{
"type": "unblock",
"created_timestamp": "1518127020304",
"source": {
},
"target": {
}
}]
}
```
### mute\_events
```json theme={null}
{
"for_user_id": "2244994945",
"mute_events": [
{
"type": "mute",
"created_timestamp": "1518127020304",
"source": {
},
"target": {
}
}
]
}
```
### unmute\_events
```json theme={null}
{
"for_user_id": "2244994945",
"mute_events": [
{
"type": "unmute",
"created_timestamp": "1518127020304",
"source": {
},
"target": {
}
}
]
}
```
### user\_event
```json theme={null}
{
"user_event": {
"revoke": {
"date_time": "2018-05-24T09:48:12+00:00",
"target": {
"app_id": "13090192"
},
"source": {
"user_id": "63046977"
}
}
}
}
```
### direct\_message\_events
```json theme={null}
{
"for_user_id": "4337869213",
"direct_message_events": [{
"type": "message_create",
"id": "954491830116155396",
"created_timestamp": "1516403560557",
"message_create": {
"target": {
"recipient_id": "4337869213"
},
"sender_id": "3001969357",
"source_app_id": "13090192",
"message_data": {
"text": "Hello World!",
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
}
}
}
}],
"apps": {
"13090192": {
"id": "13090192",
"name": "FuriousCamperTestApp1",
"url": "https://x.com/furiouscamper"
}
},
"users": {
"3001969357": {
"id": "3001969357",
"created_timestamp": "1422556069340",
"name": "Jordan Brinks",
"screen_name": "furiouscamper",
"location": "Boulder, CO",
"description": "Alter Ego - X PE opinions-are-my-own",
"url": "https://t.co/SnxaA15ZuY",
"protected": false,
"verified": false,
"followers_count": 22,
"friends_count": 45,
"statuses_count": 494,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/851526626785480705/cW4WTi7C_normal.jpg"
},
"4337869213": {
"id": "4337869213",
"created_timestamp": "1448312972328",
"name": "Harrison Test",
"screen_name": "Harris_0ff",
"location": "Burlington, MA",
"protected": false,
"verified": false,
"followers_count": 8,
"friends_count": 8,
"statuses_count": 240,
"profile_image_url_https": "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"
}
}
}
```
### direct\_message\_indicate\_typing\_events
```json theme={null}
{
"for_user_id": "4337869213",
"direct_message_indicate_typing_events": [{
"created_timestamp": "1518127183443",
"sender_id": "3284025577",
"target": {
"recipient_id": "3001969357"
}
}],
"users": {
"3001969357": {
"id": "3001969357",
"created_timestamp": "1422556069340",
"name": "Jordan Brinks",
"screen_name": "furiouscamper",
"location": "Boulder, CO",
"description": "Alter Ego - X PE opinions-are-my-own",
"url": "https://t.co/SnxaA15ZuY",
"protected": false,
"verified": false,
"followers_count": 23,
"friends_count": 47,
"statuses_count": 509,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/851526626785480705/cW4WTi7C_normal.jpg"
},
"3284025577": {
"id": "3284025577",
"created_timestamp": "1437281176085",
"name": "Bogus Bogart",
"screen_name": "bogusbogart",
"protected": true,
"verified": false,
"followers_count": 1,
"friends_count": 4,
"statuses_count": 35,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/763383202857779200/ndvZ96mE_normal.jpg"
}
}
}
```
### direct\_message\_mark\_read\_events
```json theme={null}
{
"for_user_id": "4337869213",
"direct_message_mark_read_events": [{
"created_timestamp": "1518452444662",
"sender_id": "199566737",
"target": {
"recipient_id": "3001969357"
},
"last_read_event_id": "963085315333238788"
}],
"users": {
"199566737": {
"id": "199566737",
"created_timestamp": "1286429788000",
"name": "Le Braat",
"screen_name": "LeBraat",
"location": "Denver, CO",
"description": "data by day @X, design by dusk",
"protected": false,
"verified": false,
"followers_count": 299,
"friends_count": 336,
"statuses_count": 752,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/936652894371119105/YHEozVAg_normal.jpg"
},
"3001969357": {
"id": "3001969357",
"created_timestamp": "1422556069340",
"name": "Jordan Brinks",
"screen_name": "furiouscamper",
"location": "Boulder, CO",
"description": "Alter Ego - X PE opinions-are-my-own",
"url": "https://t.co/SnxaA15ZuY",
"protected": false,
"verified": false,
"followers_count": 23,
"friends_count": 48,
"statuses_count": 510,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/851526626785480705/cW4WTi7C_normal.jpg"
}
}
}
```
### tweet\_delete\_events
```json theme={null}
{
"for_user_id": "930524282358325248",
"tweet_delete_events": [
{
"status": {
"id": "1045405559317569537",
"user_id": "930524282358325248"
},
"timestamp_ms": "1432228155593"
}
]
}
```
***
## Support for longform Posts
The V2 Account Activity API supports **longform** posts, which are posts exceeding 280 characters. When a longform post is included in a `tweet_create_events` payload, the `text` field contains the first 140 characters (or fewer), and the `truncated` field is set to `true`. The full post content is delivered in the `extended_tweet` object, which includes:
* `full_text` — The complete text of the post, including all characters beyond the 280-character limit.
* `entities` — Any entities (e.g., hashtags, URLs, user mentions, symbols) appearing in the full text, including those after the 280th character.
* `display_text_range` — The range of characters to display, accounting for the full text.
This ensures that applications can process the entire content of longform posts, including mentions or other entities that appear later in the text. Below is an example of a `tweet_create_events` payload for a longform post:
```json theme={null}
{
"for_user_id": "1603419180975409153",
"tweet_create_events": [
{
"created_at": "Mon May 19 14:01:46 +0000 2025",
"id": 1924465506158879000,
"id_str": "1924465506158878979",
"text": "The Antikythera Mechanism: A Window into Ancient Ingenuity Discovered in 1901 among the wreckage of a Roman ship of… https://t.co/bzbEKj8cd8",
"display_text_range": [0, 140],
"truncated": true,
"user": { ... },
"extended_tweet": {
"full_text": "The Antikythera Mechanism: A Window into Ancient Ingenuity Discovered in 1901 among the wreckage of a Roman ship off the Greek island of Antikythera...",
"display_text_range": [0, 2051],
"entities": {
"hashtags": [],
"urls": [],
"user_mentions": [
{
"screen_name": "xai",
"name": "xAI",
"id": 1661523610111193000,
"id_str": "1661523610111193088",
"indices": [2032, 2036]
},
{
"screen_name": "HistoryInPics",
"name": "History Photographed",
"id": 1582853809,
"id_str": "1582853809",
"indices": [2037, 2051]
}
],
"symbols": []
}
},
"entities": {
"hashtags": [],
"urls": [
{
"url": "https://t.co/bzbEKj8cd8",
"expanded_url": "https://twitter.com/i/web/status/1924465506158878979",
"display_url": "twitter.com/i/web/status/1…",
"indices": [117, 140]
}
],
"user_mentions": [],
"symbols": []
}
}
]
}
```
***
## Frequently asked questions
The Account Activity API uses webhooks, delivering data in real-time without requiring an open connection (unlike streaming APIs) or frequent polling (unlike REST APIs). Benefits include:
* **Speed** — Delivers data at the speed of X.
* **Simplicity** — Provides all account events through a single webhook connection, including Posts, @mentions, Replies, Reposts, Quote Tweets, Likes, DMs, Follows, Blocks, and Mutes.
* **Scale** — Supports all activities for managed accounts without rate limits or event caps (Enterprise tier).
Yes! You can register multiple webhook URLs and manage subscriptions separately via the [V2 Webhooks API](/x-api/webhooks/introduction).
Yes! See the [Account Activity API Quickstart](/x-api/account-activity/quickstart), the [Getting Started with Webhooks guide](/x-api/webhooks/quickstart), and the [Account Activity API Sample Application](https://github.com/xdevplatform/account-activity-dashboard-enterprise/tree/master).
Authentication requirements vary by endpoint:
* **User-specific actions** (e.g., subscribing a user) require **OAuth 1.0a** (3-legged OAuth flow).
* **App-level actions** (e.g., listing/deleting subscriptions, subscription count) require **OAuth2 App Only Bearer Token**.
Review the [Authentication section](/fundamentals/authentication/overview) for details.
Yes. If your app has subscriptions for User A and User B, and User A mentions User B in a Post, your webhook receives two events (one per user). Use the `for_user_id` field to identify the subscription.
No. The `/all/` product is the only option, delivering all supported event types.
The webhook limit is set at the account level, not per app. For example, with three webhooks and two apps, you could use two webhooks for one app and one for the other, but not three per app.
***
## API reference index
| Purpose | V2 Endpoint |
| :------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------- |
| Subscribes an application to an account's events | [`POST /2/account_activity/webhooks/:webhook_id/subscriptions/all`](/x-api/account-activity/create-subscription) |
| Returns a count of currently active subscriptions | [`GET /2/account_activity/subscriptions/count`](/x-api/account-activity/get-subscription-count) |
| Checks if a webhook is subscribed to an account | [`GET /2/account_activity/webhooks/:webhook_id/subscriptions/all`](/x-api/account-activity/validate-subscription) |
| Returns a list of currently active subscriptions | [`GET /2/account_activity/webhooks/:webhook_id/subscriptions/all/list`](/x-api/account-activity/get-subscriptions) |
| Deactivates a subscription using app-only OAuth | [`DELETE /2/account_activity/webhooks/:webhook_id/subscriptions/:user_id/all`](/x-api/account-activity/delete-subscription) |
| Creates a replay job | [`POST /2/account_activity/replay/webhooks/:webhook_id/subscriptions/all`](/x-api/account-activity/create-replay-job) |
For webhook management endpoints (register, view, validate, delete), see the [V2 Webhooks API documentation](/x-api/webhooks/introduction).
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* A publicly accessible HTTPS webhook endpoint
* Enterprise or Pay Per Use access for the Account Activity API
Set up subscriptions and start receiving events
Register and manage your webhooks
Migrate from legacy Enterprise to v2
Streaming alternative to webhooks
# Account Activity v2 migration overview
Source: https://docs.x.com/enterprise-api/account-activity/migrate/overview
Migrate from the legacy Enterprise Account Activity API to v2 with updated endpoint paths, OAuth 2.0 authentication, and webhook management.
This guide helps you migrate from the legacy Enterprise Account Activity API to the V2 Account Activity API. The core functionality remains the same, but endpoint structures and authentication methods have been updated for consistency with X API v2.
### Summary of Changes
* **API Format**: Endpoints use the /2/account\_activity/ base path instead of /1.1/account\_activity/.
* **Webhook Management**: Webhook creation, listing, validation (CRC), and deletion are handled by the [V2 Webhooks API](https://github.com/m-rosinsky/XWebhookTest/blob/main/app.py).
* **Authentication**: V2 endpoints require either:
* **OAuthUser** (3-legged OAuth) for user-specific actions (e.g., subscribing a user).
* **OAuth2 App Only** (Bearer Token) for app-level actions (e.g., listing/deleting subscriptions).
* V1.1 used varying requirements, often OAuth 1.0a.
* **Endpoint Mapping**:
| V1.1 Endpoint | V2 Equivalent / Action | Notes |
| ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| POST /1.1/account\_activity/webhooks.json?url=\ | POST /2/webhooks | [Docs](https://docs.x.com/x-api/webhooks/introduction). Requires OAuth2AppOnly. |
| GET /1.1/account\_activity/webhooks.json | GET /2/webhooks | [Docs](https://docs.x.com/x-api/webhooks/introduction). Requires OAuth2AppOnly. |
| PUT /1.1/account\_activity/webhooks/:webhook\_id.json | PUT /2/webhooks/:webhook\_id | Triggers CRC. [Docs](https://docs.x.com/x-api/webhooks/introduction). Requires OAuth2AppOnly. |
| DELETE /1.1/account\_activity/webhooks/:webhook\_id.json | DELETE /2/webhooks/:webhook\_id | [Docs](https://docs.x.com/x-api/webhooks/introduction). Requires OAuth2AppOnly. |
| POST /1.1/account\_activity/webhooks/:webhook\_id/subscriptions/all.json | POST /2/account\_activity/webhooks/:webhook\_id/subscriptions/all | Requires OAuthUser. |
| GET /1.1/account\_activity/subscriptions/count.json | GET /2/account\_activity/subscriptions/count | Requires OAuth2AppOnly. |
| GET /1.1/account\_activity/webhooks/:webhook\_id/subscriptions/all.json | GET /2/account\_activity/webhooks/:webhook\_id/subscriptions/all | Requires OAuthUser. |
| GET /1.1/account\_activity/webhooks/:webhook\_id/subscriptions/all/list.json | GET /2/account\_activity/webhooks/:webhook\_id/subscriptions/all/list | Requires OAuth2AppOnly. |
| DELETE /1.1/account\_activity/webhooks/:webhook\_id/subscriptions/:user\_id/all | DELETE /2/account\_activity/webhooks/:webhook\_id/subscriptions/:user\_id/all | Requires OAuth2AppOnly. |
| DELETE /1.1/account\_activity/webhooks/:webhook\_id/subscriptions/all | Deprecated / No Direct Equivalent | Use individual deletes or remove the webhook via DELETE /2/webhooks/:webhook\_id. |
* **Response Formats**: Review the success and error response structures in the AAAPI documentation.
When migrating, update your code to use the new base paths, adjust authentication flows, and manage webhooks using the [V2 Webhooks API](https://docs.x.com/x-api/webhooks/introduction).
### How to Migrate
* **Decide on a Package**:
* Choose the Enterprise or Self-serve package for Account Activity API access, considering:
* Number of webhooks needed.
* Current/projected subscriptions or authorized users.
* Number of X client applications.
* Desired support level (forum vs. managed enterprise 1:1 support).
* Pricing details (contact sales for Enterprise).
* **Update Your Authentication to OAuth 2.0**:
* Ensure your X App has “Read, Write, and Access Direct Messages” permissions.
* Update to OAuth 2.0 for V2 endpoints. Re-authorize users if scopes have changed.
* Use the Developer Console to manage:
* OAuth 2.0 Access Token.
* Client ID and Client Secret.
* **Verify or Reconfigure Your Webhook**:
* Use your existing webhook URL or set up a new one (e.g., [https://your\\\_domain.com/webhook/twitter](https://your\\_domain.com/webhook/twitter)).
* Follow the [V2 Webhooks API documentation](https://docs.x.com/x-api/webhooks/introduction) to register and manage your webhook.
* **Sample Apps:**
* [Simple webhook server](https://github.com/m-rosinsky/XWebhookTest/blob/main/app.py)
* A single python script that shows you how to respond to the CRC check and accept POST events.
* [Account Activity API sample dashboard](https://github.com/xdevplatform/account-activity-dashboard-enterprise/tree/master)
* A web app written with [bun.sh](http://bun.sh) that allows you to manage webhooks, subscriptions, and receive live events directly in the app.
# Quickstart
Source: https://docs.x.com/enterprise-api/account-activity/quickstart
This guide walks you through setting up the Account Activity API, managing user. Reference for the Enterprise X API tier covering account activity.
This guide walks you through setting up the Account Activity API, managing user subscriptions, validating your webhook, and using the replay feature to recover missed events.
## 1. Create an X App
Create an X app with an approved developer account from the [developer portal](https://developer.x.com/en/portal/products/enterprise). If creating the app on behalf of your company, use a corporate X account.
* Enable **"Read, Write, and Access direct messages"** on the permissions tab of your app page.
* On the "Keys and Access Tokens" tab, note your app's **Consumer Key (API Key)**, **Consumer Token (API Secret)**, and **Bearer Token**.
* Generate your app's **Access Token** and **Access Token Secret**. These are needed to subscribe to user accounts.
* Review [Obtaining Access Tokens](/fundamentals/authentication/overview) if unfamiliar with X Sign-in and user contexts.
* Note your app's numeric ID from the "Apps" page in the developer portal. This is required when applying for Account Activity API access.
***
## 2. Get Account Activity API access
The Account Activity API is available on the Enterprise and Pay Per Use tiers. Submit an application for access via the [developer portal](https://developer.x.com/en/portal/products/enterprise).
***
## 3. Register a webhook
To receive Account Activity events, you must register a webhook with a publicly accessible HTTPS URL. See the [V2 Webhooks API documentation](/x-api/webhooks/introduction) for details on developing a webhook consumer app, registering a webhook, securing it, and handling Challenge-Response Checks (CRC).
* Ensure your webhook is configured to handle POST requests with JSON-encoded event payloads.
* Obtain the **`webhook_id`** from the webhook registration response, as it is required for managing subscriptions.
```bash theme={null}
curl --request POST \
--url 'https://api.x.com/2/webhooks' \
--header 'Authorization: Bearer $BEARER_TOKEN' \
--header 'Content-Type: application/json' \
--data '{"url": "https://yourdomain.com/webhooks/twitter"}'
```
***
## 4. Validate setup
To validate that your app and webhook are configured correctly:
1. Subscribe a user account to your webhook (see [Adding a Subscription](#adding-a-subscription) below).
2. Favorite a Post posted by one of the X accounts your app is subscribed to.
3. You should receive a `favorite_events` payload via a POST request to your webhook URL.
It may take up to 10 seconds for events to start being delivered after adding a subscription.
***
## Managing subscriptions
Once you have a registered webhook with a valid `webhook_id`, you can manage user subscriptions to receive their account activities. Use the following endpoints to add, view, or remove subscriptions.
### Adding a subscription
**Endpoint:** `POST /2/account_activity/webhooks/:webhook_id/subscriptions/all` — [API Reference](/x-api/account-activity/create-subscription)
Subscribes the authenticating user to receive events via the specified webhook.
**Authentication:** OAuth 1.0a (3-legged OAuth flow required, representing the user being subscribed).
| Path Parameter | Description |
| :------------- | :-------------------------------------------------------- |
| `webhook_id` | The ID of the webhook to associate the subscription with. |
```bash theme={null}
curl --request POST \
--url 'https://api.x.com/2/account_activity/webhooks/:WEBHOOK_ID/subscriptions/all' \
--header 'authorization: OAuth oauth_consumer_key="", oauth_nonce="GENERATED", oauth_signature="GENERATED", oauth_signature_method="HMAC-SHA1", oauth_timestamp="GENERATED", oauth_token="", oauth_version="1.0"'
```
**Success (200 OK):**
```json theme={null}
{
"data": {
"subscribed": true
}
}
```
**Failure reasons:**
| Reason | Description |
| :---------------------------- | :-------------------------------------------------------------------------- |
| `WebhookIdInvalid` | The provided `webhook_id` was not found or is not associated with the app. |
| `DuplicateSubscriptionFailed` | A subscription for this user already exists for the specified `webhook_id`. |
| `SubscriptionLimitExceeded` | The application has reached its subscription limit across all webhooks. |
***
### Checking a subscription
**Endpoint:** `GET /2/account_activity/webhooks/:webhook_id/subscriptions/all` — [API Reference](/x-api/account-activity/validate-subscription)
Checks if the authenticating user is subscribed to the specified webhook.
**Authentication:** OAuth 1.0a (3-legged OAuth flow required).
| Path Parameter | Description |
| :------------- | :------------------------------ |
| `webhook_id` | The ID of the webhook to check. |
```bash theme={null}
curl --request GET \
--url 'https://api.x.com/2/account_activity/webhooks/:WEBHOOK_ID/subscriptions/all' \
--header 'authorization: OAuth oauth_consumer_key="", oauth_nonce="GENERATED", oauth_signature="GENERATED", oauth_signature_method="HMAC-SHA1", oauth_timestamp="GENERATED", oauth_token="", oauth_version="1.0"'
```
**Success (200 OK):**
```json theme={null}
{
"data": {
"subscribed": true
}
}
```
**Failure reasons:**
| Reason | Description |
| :----------------- | :------------------------------------------------------------------------- |
| `WebhookIdInvalid` | The provided `webhook_id` was not found or is not associated with the app. |
***
### Removing a subscription
**Endpoint:** `DELETE /2/account_activity/webhooks/:webhook_id/subscriptions/:user_id/all` — [API Reference](/x-api/account-activity/delete-subscription)
Deactivates the subscription for a specific user ID, stopping event delivery to the webhook.
**Authentication:** OAuth2 App Only Bearer Token.
| Path Parameter | Description |
| :------------- | :------------------------------------------------- |
| `webhook_id` | The ID of the webhook containing the subscription. |
| `user_id` | The numerical ID of the user to unsubscribe. |
```bash theme={null}
curl --request DELETE \
--url 'https://api.x.com/2/account_activity/webhooks/:WEBHOOK_ID/subscriptions/:USER_ID/all' \
--header 'authorization: Bearer '
```
**Success (200 OK):**
```json theme={null}
{
"data": {
"subscribed": false
}
}
```
**Failure reasons:**
| Reason | Description |
| :--------------------- | :---------------------------------------------------------------------------- |
| `SubscriptionNotFound` | No subscription exists for the specified `user_id` on the given `webhook_id`. |
| `WebhookIdInvalid` | The provided `webhook_id` was not found or is not associated with the app. |
***
### Viewing all subscriptions
**Endpoint:** `GET /2/account_activity/webhooks/:webhook_id/subscriptions/all/list` — [API Reference](/x-api/account-activity/get-subscriptions)
Retrieves a list of all user IDs currently subscribed to the specified webhook.
**Authentication:** OAuth2 App Only Bearer Token.
| Path Parameter | Description |
| :------------- | :----------------------------------------------- |
| `webhook_id` | The ID of the webhook to list subscriptions for. |
```bash theme={null}
curl --request GET \
--url 'https://api.x.com/2/account_activity/webhooks/:WEBHOOK_ID/subscriptions/all/list' \
--header 'authorization: Bearer '
```
**Success (200 OK):**
```json theme={null}
{
"data": {
"application_id": "",
"webhook_id": "",
"webhook_url": "",
"subscriptions": [
{ "user_id": "" },
{ "user_id": "" }
]
}
}
```
**Failure reasons:**
| Reason | Description |
| :----------------- | :------------------------------------------------------------------------- |
| `WebhookIdInvalid` | The provided `webhook_id` was not found or is not associated with the app. |
***
### Subscription count
**Endpoint:** `GET /2/account_activity/subscriptions/count` — [API Reference](/x-api/account-activity/get-subscription-count)
Returns the total count of active subscriptions and the provisioned limit for the authenticating application.
**Authentication:** OAuth2 App Only Bearer Token.
```bash theme={null}
curl --request GET \
--url 'https://api.x.com/2/account_activity/subscriptions/count' \
--header 'authorization: Bearer '
```
**Success (200 OK):**
```json theme={null}
{
"data": {
"account_name": "",
"provisioned_count": "",
"subscriptions_count_all": "",
"subscriptions_count_direct_messages": "0"
}
}
```
DM-only subscriptions are no longer supported. The `subscriptions_count_direct_messages` field will always be `"0"`.
***
## Replay
AAAv2 provides replay functionality that allows you to retrieve past events for a specified time range and re-deliver them to your webhook. This is useful for recovering missed events due to downtime.
**Endpoint:** `POST /2/account_activity/replay/webhooks/:webhook_id/subscriptions/all` — [API Reference](/x-api/account-activity/create-replay-job)
**Authentication:** OAuth2 App Only Bearer Token.
| Path Parameter | Description |
| :------------- | :------------------------------------- |
| `webhook_id` | The ID of the webhook to begin replay. |
| Query Parameter | Description |
| :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `from_date` | The oldest (starting) UTC timestamp from which the events will be provided. Must be in `yyyymmddhhmm` format. Timestamp is in minute granularity and is inclusive (i.e. 12:00 includes the 00 minute). Valid times must be within the last 24 hours, UTC time, and no more recent than 31 minutes before the current point in time. It's recommended that `from_date` and `to_date` should be within \~2 hours. |
| `to_date` | The latest (ending) UTC timestamp to which the event will be provided. Must be in `yyyymmddhhmm` format. Timestamp is in minute granularity and is exclusive (i.e. 12:30 does not include the 30th minute of the hour). Valid times must be within the last 24 hours, UTC time, and no more than 10 minutes before the current point in time. |
**Success (200 OK):**
```json theme={null}
{
"for_user_id": "",
"replay_event": {
"job_id": "",
"created_at": "yyyy-mm-ddThh:mm:ss.000Z"
}
}
```
**Failure reasons:**
| Reason | Description |
| :-------------------- | :---------------------------------------------------------------------- |
| `QueryParamInvalid` | `from_date` is older than 24 hours from the current time. |
| `QueryParamInvalid` | `from_date` is more recent than `to_date`. |
| `QueryParamInvalid` | `from_date` is in the future. |
| `QueryParamInvalid` | `to_date` is in the future. |
| `QueryParamInvalid` | `from_date` or `to_date` is not in the correct format. |
| `CrcValidationFailed` | Incorrect response received from the webhook URL during CRC validation. |
| `ReplayConflictError` | A replay job is already in progress for the specified webhook. |
| `WebhookIdInvalid` | The provided `webhook_id` is invalid or not associated with the app. |
### Job completed messages
Once your replay job successfully completes, X will deliver the following job completion event. Once you receive this event, the job has finished running and another can be submitted.
```json theme={null}
{
"replay_job_status": {
"webhook_id": "",
"job_state": "Complete",
"job_state_description": "Job completed successfully",
"job_id": ""
}
}
```
In the event your job does not complete successfully, X will return the following message encouraging you to retry your Replay Job. Once you receive this event, the job has finished running and another can be submitted.
```json theme={null}
{
"replay_job_status": {
"webhook_id": "",
"job_state": "Incomplete",
"job_state_description": "Job failed to deliver all events, please retry your replay job",
"job_id": ""
}
}
```
***
## Important notes
* **Authentication**: When subscribing users, use the consumer key, consumer secret, access token, and access token secret for the user's account.
* **Direct Messages**: All incoming and outgoing Direct Messages (sent via `POST /2/dm_conversations/with/:participant_id/messages`) are delivered via webhooks to keep your app aware of all DM activity.
* **Event Duplication**:
* If two subscribed users are in the same DM conversation, your webhook receives duplicate events (one per user). Use the `for_user_id` field to distinguish them.
* If multiple apps share the same webhook URL and user, events are sent multiple times (once per app).
* Your app should deduplicate events using the event ID to handle occasional duplicates.
***
## Sample apps
| App | Description |
| :------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------- |
| [Simple webhook server](https://github.com/m-rosinsky/XWebhookTest/blob/main/app.py) | A single Python script that shows how to respond to the CRC check and accept POST events |
| [Account Activity API dashboard](https://github.com/xdevplatform/account-activity-dashboard-enterprise/tree/master) | A web app written with [bun.sh](https://bun.sh) that lets you manage webhooks, subscriptions, and receive live events |
***
## Next steps
Activity types, data objects, and payload examples
Register and manage your webhooks
Migrate from legacy Enterprise to v2
CRC setup, security, and webhook registration
# Validate subscription
Source: https://docs.x.com/enterprise-api/account-activity/validate-subscription
get /2/account_activity/webhooks/{webhook_id}/subscriptions/all
Checks a user’s Account Activity subscription for a given webhook.
# Activity Stream
Source: https://docs.x.com/enterprise-api/activity/activity-stream
get /2/activity/stream
Stream of X Activities
# Create X activity subscription
Source: https://docs.x.com/enterprise-api/activity/create-x-activity-subscription
post /2/activity/subscriptions
Creates a subscription for an X activity event
# Deletes X activity subscription
Source: https://docs.x.com/enterprise-api/activity/deletes-x-activity-subscription
delete /2/activity/subscriptions/{subscription_id}
Deletes a subscription for an X activity event
# Get X activity subscriptions
Source: https://docs.x.com/enterprise-api/activity/get-x-activity-subscriptions
get /2/activity/subscriptions
Get a list of active subscriptions for XAA
# X Activity API for Enterprise real-time events
Source: https://docs.x.com/enterprise-api/activity/introduction
Subscribe to real-time X Activity events like post.create, follow, profile updates, and Spaces start or end, delivered via HTTP stream or webhook.
The X Activity API (XAA) endpoint group allows developers to tap into activity events happening on the X Platform.
A developer can subscribe to events they are interested in such as `profile.update.bio`, `post.create`, `post.delete` etc. and filter for the User ID whose events they want. The matching events for that User ID will be delivered to your app with sub-second latency.
## Delivery mechanisms
The X Activity API currently supports the following delivery mechanisms to send events to your app:
* Persistent HTTP stream
* [Webhook](/x-api/webhooks/introduction)
## Supported event types
Currently, X Activity API supports the following event types, organized by category:
### Profile Events
Profile events are triggered when a user makes changes to their profile information.
| Event Name | Description | Filters |
| -------------------------------- | --------------------------------------------------- | --------- |
| `profile.update.bio` | Fired when a user updates their profile bio | `user_id` |
| `profile.update.profile_picture` | Fired when a user updates their profile picture | `user_id` |
| `profile.update.banner_picture` | Fired when a user updates their profile banner | `user_id` |
| `profile.update.screenname` | Fired when a user updates their display name | `user_id` |
| `profile.update.handle` | Fired when a user updates their handle | `user_id` |
| `profile.update.geo` | Fired when a user updates their profile location | `user_id` |
| `profile.update.url` | Fired when a user updates their profile website URL | `user_id` |
| `profile.update.verified_badge` | Fired when a user updates their verified badge | `user_id` |
| `profile.update.affiliate_badge` | Fired when a user updates their affiliate badge | `user_id` |
### Follow Events
Follow events are triggered when the filtered user follows another user, or is followed by another user.
| Event Name | Description | Filters |
| ----------------- | ---------------------------------------- | --------- |
| `follow.follow` | Fired when a user follows another user | `user_id` |
| `follow.unfollow` | Fired when a user unfollows another user | `user_id` |
**Enterprise Only:** The `follow.follow` and `follow.unfollow` events are only available to Enterprise and Partner tier accounts at this time.
### Spaces Events
Spaces events are triggered when a user starts or ends a Space.
| Event Name | Description | Filters |
| -------------- | -------------------------------- | --------- |
| `spaces.start` | Fired when a user starts a Space | `user_id` |
| `spaces.end` | Fired when a user ends a Space | `user_id` |
### Post Events
Post events are triggered when a user creates or deletes a Post.
| Event Name | Description | Filters |
| ------------- | -------------------------------- | --------- |
| `post.create` | Fired when a user creates a Post | `user_id` |
| `post.delete` | Fired when a user deletes a Post | `user_id` |
**Post events via XAA vs Filtered Stream:** X Activity API supports `post.create` and `post.delete` events. Subscribe by `user_id` to get real-time notifications when users create or delete Posts.
If you want targeted keyword filtering, boolean logic, geo targeting, language filters, or any of the other operators that the Filtered Stream supports, use the [Filtered Stream](/x-api/posts/filtered-stream/introduction) endpoint instead.
### Legacy DM Events
Legacy DM events pertain to the legacy, unencrypted DM system.
| Event Name | Description | Filters |
| -------------------- | ------------------------------------------------------------------------------------ | --------- |
| `dm.received` | Fired when a user receives an unencrypted direct message | `user_id` |
| `dm.sent` | Fired when a user sends an unencrypted direct message | `user_id` |
| `dm.read` | Fired when a user reads the filtered users unencrypted DM message, or "read receipt" | `user_id` |
| `dm.indicate_typing` | Fired when a user is typing a message to the filtered user | `user_id` |
### Chat Events
Chat events pertain to the new, encrypted messaging stack, or XChat.
| Event Name | Description | Filters |
| ------------------------ | ------------------------------------------------------ | --------- |
| `chat.received` | Fired when a user receives an encrypted direct message | `user_id` |
| `chat.sent` | Fired when a user sends an encrypted direct message | `user_id` |
| `chat.conversation_join` | Fired when a user joins an encrypted chat conversation | `user_id` |
### News Events
News events provide updates on trending topics and headlines curated by Grok.
| Event Name | Description | Filters |
| ---------- | ------------------------------------- | --------- |
| `news.new` | New grok-curated trends and headlines | `keyword` |
**Enterprise Only:** The `news.new` event is only available to Enterprise and Partner tier accounts at this time.
In future releases, XAA will expand to support additional event types including social interactions, content engagement, monetization features, and more. We will continue to update our docs when new event types become available.
## Event privacy and authentication
The X Activity API distinguishes between **public events** and **private events** as at parity with the X app as explained below.
### Public Events
Public events are activities that a public user account performs publicly that are visible to all X users. These events are visible to all users on the X platform and don't require OAuth authentication from the user in order to view.
**Current public events:**
* Profile updates (bio, picture, banner, location, URL, username changes)
* Post creation (`post.create`) and deletion (`post.delete`)
For these public events, you can create subscriptions by specifying the user ID in your filter and receive them via XAA.
### Private Events
Private events are activities that require explicit user consent through OAuth authentication. A User has to authenticate via X and give explicit permission to a developer app to access these events.
**Authentication requirements for private events:**
* The user must authenticate your application via OAuth 2.0
* Your application must obtain appropriate OAuth scopes
* The user must explicitly grant permission for your app to access these events
* Subscriptions for private events can only be created for users who have authorized your application
## Subscription limits
The X Activity API has different subscription limits based on your account tier:
| Package Tier | Maximum Subscriptions |
| ------------ | --------------------- |
| Self-serve | 1000 |
| Enterprise | 50,000 |
| Partner | 100,000 |
## Endpoints
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------------------------------- | :------------------------- |
| GET | [`/2/activity/stream`](/x-api/activity/activity-stream) | Connect to activity stream |
| POST | [`/2/activity/subscriptions`](/x-api/activity/create-x-activity-subscription) | Create a subscription |
| GET | [`/2/activity/subscriptions`](/x-api/activity/get-x-activity-subscriptions) | List subscriptions |
| PUT | [`/2/activity/subscriptions/:id`](/x-api/activity/update-x-activity-subscription) | Update a subscription |
| DELETE | [`/2/activity/subscriptions/:id`](/x-api/activity/deletes-x-activity-subscription) | Delete a subscription |
**Account setup**
To access these endpoints, you will need:
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info).
* To authenticate using the keys and tokens from a [developer App](/fundamentals/developer-apps) that is located within a Project.
Learn more about getting access to the X API v2 endpoints in our [getting started guide](/x-api/getting-started/getting-access).
# Quickstart
Source: https://docs.x.com/enterprise-api/activity/quickstart
This guide explains how to subscribe for and receive events using the X Activity API endpoints. Reference for the Enterprise X API tier covering activity.
This guide explains how to subscribe for and receive events using the X Activity API endpoints. There are generally 3 steps involved:
1. Identify the User ID for the User whose events you want to filter on
2. Create a subscription for the type of event you want to filter for that User
3. Receive the events using webhook or persistent http stream connection
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's [Bearer Token](/resources/fundamentals/authentication)
***
## Getting user IDs
Before creating subscriptions, you'll need to know the user ID of the account you want to filter on. In this example, we will use the XDevelopers handle. You can look up user IDs in a few ways including:
**Look up a user's ID by username:**
```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" "https://api.x.com/2/users/by/username/xdevelopers"
```
**Get your own user ID:**
```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" https://api.x.com/2/users/me
```
Both endpoints return user information including the `id` field, which you can use in subscription filters. Example json response is shown below:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "Developers",
"username": "XDevelopers"
}
}
```
***
## Creating a subscription
Next step is to create a subscription. In this example, we will subscribe to XDevelopers's bio updates. In order to do so, we will pass the `user_id` and `event_type` in the JSON body. In this case, the `event_type` is `profile.update.bio`.
We'll pass X Developer's user ID: `2244994945`, and an optional tag:
```json theme={null}
{
"event_type": "profile.update.bio",
"filter": {
"user_id": "2244994945"
},
"tag": "Xdevelopers' bio updates"
}
```
We'll use our [bearer token](https://docs.x.com/fundamentals/authentication/oauth-2-0/overview#bearer-token-also-known-as-app-only) (from the developer portal) for authorization for all endpoints related to XAA:
```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"
}'
```
Upon successful request, your subscription will be created:
```json 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
}
}
```
***
## Getting the events
Once we have created the subscription, we can receive the events via [webhooks](https://docs.x.com/x-api/webhooks/introduction) or a persistent HTTP stream. In this example, we will open the persistent HTTP stream:
```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" https://api.x.com/2/activity/stream
```
When Xdevelopers account updates their profile bio, the event will be delivered through the stream:
```json theme={null}
{
"data": {
"filter": {
"user_id": "2244994945"
},
"event_type": "profile.update.bio",
"tag": "Xdevelopers' bio updates",
"payload": {
"before": "Mars & Cars",
"after": "Mars, Cars & AI"
}
}
}
```
***
## Subscription management
The X Activity API provides endpoints to manage your subscriptions through standard CRUD operations.
### Create Subscription
Create a new subscription to receive events:
```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"
}'
```
* The `tag` field is optional. This can be used to help identify events on delivery.
* The `webhook_id` field is also optional. See our [webhook docs](https://docs.x.com/x-api/webhooks/introduction) for help setting up a webhook. If a `webhook_id` is specified, the event will be delivered to the provided webhook, in addition to the stream if it is open.
**Response:**
```json 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"
}
}
```
### List Subscriptions
Retrieve all active subscriptions for your application:
```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" \
https://api.x.com/2/activity/subscriptions
```
**Response:**
```json 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
}
}
```
### Delete Subscription
Remove a subscription:
```bash theme={null}
curl -H "Authorization: Bearer YOUR_BEARER_TOKEN" \
-X DELETE \
https://api.x.com/2/activity/subscriptions/1976325569252868096
```
**Response:**
```json theme={null}
{
"data": {
"deleted": true
},
"meta": {
"total_subscriptions": 0
}
}
```
`total_subscriptions` shows the remaining number of subscriptions associated with your app after the delete operation.
### Update Subscription
The PUT endpoint allows you to update a subscription's delivery method or tag.
Updating the `filter` or `event_type` requires deleting the existing subscription and adding a new one.
```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"
}'
```
**Response:**
```json 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
}
}
```
***
## Next steps
Full endpoint documentation
Set up webhook delivery
# Update X activity subscription
Source: https://docs.x.com/enterprise-api/activity/update-x-activity-subscription
put /2/activity/subscriptions/{subscription_id}
Updates a subscription for an X activity event
# Create Bookmark
Source: https://docs.x.com/enterprise-api/bookmarks/create-bookmark
post /2/users/{id}/bookmarks
Adds a post to the authenticated user’s bookmarks.
# Delete Bookmark
Source: https://docs.x.com/enterprise-api/bookmarks/delete-bookmark
delete /2/users/{id}/bookmarks/{tweet_id}
Removes a Post from the authenticated user’s Bookmarks by its ID.
# Get Bookmark folders
Source: https://docs.x.com/enterprise-api/bookmarks/get-bookmark-folders
get /2/users/{id}/bookmarks/folders
Retrieves a list of Bookmark folders created by the authenticated user.
# Get Bookmarks
Source: https://docs.x.com/enterprise-api/bookmarks/get-bookmarks
get /2/users/{id}/bookmarks
Retrieves a list of Posts bookmarked by the authenticated user.
# Get Bookmarks by folder ID
Source: https://docs.x.com/enterprise-api/bookmarks/get-bookmarks-by-folder-id
get /2/users/{id}/bookmarks/folders/{folder_id}
Retrieves Posts in a specific Bookmark folder by its ID for the authenticated user.
# Add members to a Chat group conversation
Source: https://docs.x.com/enterprise-api/chat/add-members-to-a-chat-group-conversation
post /2/chat/conversations/{id}/members
Adds one or more members to an existing encrypted Chat group conversation, rotating the conversation key.
# Add public key
Source: https://docs.x.com/enterprise-api/chat/add-public-key
post /2/users/{id}/public_keys
Registers a user's public key for X Chat encryption.
# Append Chat Media Upload
Source: https://docs.x.com/enterprise-api/chat/append-chat-media-upload
post /2/chat/media/upload/{id}/append
Appends media data to an XChat upload session.
# Create Chat Group Conversation
Source: https://docs.x.com/enterprise-api/chat/create-chat-group-conversation
post /2/chat/conversations/group
Creates a new encrypted Chat group conversation on behalf of the authenticated user.
# Download Chat Media
Source: https://docs.x.com/enterprise-api/chat/download-chat-media
get /2/chat/media/{id}/{media_hash_key}
Downloads encrypted media bytes from an XChat conversation. The response body contains raw binary bytes. For 1:1 conversations, provide the recipient's user ID; the server constructs the canonical conversation ID from the authenticated user and recipient.
# Finalize Chat Media Upload
Source: https://docs.x.com/enterprise-api/chat/finalize-chat-media-upload
post /2/chat/media/upload/{id}/finalize
Finalizes an XChat media upload session.
# Get Chat Conversation
Source: https://docs.x.com/enterprise-api/chat/get-chat-conversation
get /2/chat/conversations/{id}
Returns metadata for a Chat conversation including type, muted status, and group details. Use chat_conversation.fields to select which fields are returned. Use expansions to hydrate member, admin, or participant user objects. Use user.fields to control which profile fields are returned for expanded users.
# Get Chat Conversations
Source: https://docs.x.com/enterprise-api/chat/get-chat-conversations
get /2/chat/conversations
Retrieves a list of Chat conversations for the authenticated user's inbox.
# Get user public keys
Source: https://docs.x.com/enterprise-api/chat/get-user-public-keys
get /2/users/{id}/public_keys
Returns the public keys and Juicebox configuration for the specified user.
# Initialize Chat Group
Source: https://docs.x.com/enterprise-api/chat/initialize-chat-group
post /2/chat/conversations/group/initialize
Initializes a new XChat group conversation and returns a unique conversation ID.
This endpoint is the first step in creating a group chat. The returned conversation_id
should be used in subsequent calls to POST /chat/conversations/group to fully create and
configure the group with members, admins, encryption keys, and other settings.
**Workflow:**
1. Call this endpoint to get a `conversation_id`
2. Use that `conversation_id` when calling `POST /chat/conversations/group` to create the group
**Authentication:**
- Requires OAuth 1.0a User Context or OAuth 2.0 User Context
- Required scope: `dm.write`
# Initialize Chat Media Upload
Source: https://docs.x.com/enterprise-api/chat/initialize-chat-media-upload
post /2/chat/media/upload/initialize
Initializes an XChat media upload session.
# Add Conversation Keys
Source: https://docs.x.com/enterprise-api/chat/initialize-conversation-keys
post /2/chat/conversations/{id}/keys
Adds (initializes or rotates) the encryption keys for a Chat conversation.
Call this before sending messages in a new 1:1 conversation, and again with a
newer key version to rotate the conversation key.
For 1:1 conversations, provide the recipient's user ID as the conversation_id.
The server constructs the canonical conversation ID from the authenticated user
and recipient.
The request body must contain the conversation key version and participant keys
(the conversation key encrypted for each participant using their public key).
**Workflow (new 1:1 conversation):**
1. Generate a conversation key using the SDK
2. Encrypt the key for both participants using their public keys
3. Call this endpoint to register the keys
4. Send messages using `POST /chat/conversations/{id}/messages`
To rotate the keys of an existing conversation, repeat the same call with a
newer conversation key version.
**Authentication:**
- Requires OAuth 1.0a User Context or OAuth 2.0 User Context
- Required scopes: `tweet.read`, `users.read`, `dm.write`
# Mark Conversation as Read
Source: https://docs.x.com/enterprise-api/chat/mark-conversation-as-read
post /2/chat/conversations/{id}/read
Marks a specific Chat conversation as read on behalf of the authenticated user. For 1:1 conversations, provide the recipient's user ID; the server constructs the canonical conversation ID from the authenticated user and recipient.
# Send Chat Message
Source: https://docs.x.com/enterprise-api/chat/send-chat-message
post /2/chat/conversations/{id}/messages
Sends an encrypted message to a specific Chat conversation. For 1:1 conversations, provide the recipient's user ID; the server constructs the canonical conversation ID from the authenticated user and recipient.
# Send Typing Indicator
Source: https://docs.x.com/enterprise-api/chat/send-typing-indicator
post /2/chat/conversations/{id}/typing
Sends a typing indicator to a specific Chat conversation on behalf of the authenticated user. For 1:1 conversations, provide the recipient's user ID; the server constructs the canonical conversation ID from the authenticated user and recipient.
# Get Community by ID
Source: https://docs.x.com/enterprise-api/communities/get-community-by-id
get /2/communities/{id}
Retrieves details of a specific Community by its ID.
# Communities Lookup
Source: https://docs.x.com/enterprise-api/communities/lookup/introduction
The Communities lookup endpoint lets you retrieve information about X Communities by their ID. Reference for the Enterprise X API tier covering lookup.
The Communities lookup endpoint lets you retrieve information about X Communities by their ID.
## Overview
Communities are public or private groups on X where members can share Posts, discuss topics, and connect around shared interests.
Get details for a specific Community
Find Communities by keyword
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------- | :------------------ |
| GET | [`/2/communities/:id`](/x-api/communities/get-community-by-id) | Get Community by ID |
***
## Response fields
| Field | Description |
| :------------- | :--------------------------- |
| `id` | Community ID |
| `name` | Community name |
| `description` | Community description |
| `created_at` | Creation date |
| `member_count` | Number of members |
| `is_private` | Whether Community is private |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/communities/1234567890?\
community.fields=name,description,member_count,created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Find Communities by keyword
Full endpoint documentation
# Search Communities
Source: https://docs.x.com/enterprise-api/communities/search-communities
get /2/communities/search
Retrieves a list of Communities matching the specified search query.
# Communities Search
Source: https://docs.x.com/enterprise-api/communities/search/introduction
The Communities Search endpoint lets you search for Communities by keyword. Reference for the Enterprise X API tier covering search.
The Communities Search endpoint lets you search for Communities by keyword. Discover Communities around topics of interest.
## Overview
Search Communities by name and description
Find Communities to join
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------------- | :--------------------- |
| GET | [`/2/communities/search`](/x-api/communities/search-communities) | Search for Communities |
***
## Parameters
| Parameter | Description |
| :----------------- | :-------------------------- |
| `query` | Search query (required) |
| `max_results` | Results per page (max 100) |
| `community.fields` | Additional Community fields |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/communities/search?\
query=Python&\
max_results=10&\
community.fields=name,description,member_count" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Look up Communities by ID
Full endpoint documentation
# Create a Community Note
Source: https://docs.x.com/enterprise-api/community-notes/create-a-community-note
post /2/notes
Creates a community note endpoint for LLM use case.
# Delete a Community Note
Source: https://docs.x.com/enterprise-api/community-notes/delete-a-community-note
delete /2/notes/{id}
Deletes a community note.
# Evaluate a Community Note
Source: https://docs.x.com/enterprise-api/community-notes/evaluate-a-community-note
post /2/evaluate_note
Endpoint to evaluate a community note.
# Community Notes API for Enterprise
Source: https://docs.x.com/enterprise-api/community-notes/introduction
Enterprise overview of the Community Notes endpoints for searching eligible Posts and programmatically submitting Community Note proposals via the X API.
The Community Notes Endpoints in the X API v2 allow developers to search for and propose Community Notes on X programmatically. Use of the API requires your account being signed up for X Developer AI access and enrolled in Community Notes as an AI Note Writer. You can [enroll and learn more about AI Note Writers](https://communitynotes.x.com/guide/en/api/overview) in the Community Notes Guide.
Currently, the API supports two endpoint categories:
## Search
### Search for X Posts that are eligible to receive a Community Note
Developers can retrieve a list of X Posts that are eligible to receive a Community Note using the `GET https://api.x.com/2/notes/search/posts_eligible_for_notes` endpoint.
### Search for Community Notes that have been written by the user on X Posts
Developers can retrieve a list of Community Notes that have been written by the authenticating user on X Posts using the `GET https://api.x.com/2/notes/search/notes_written` endpoint.
## Evaluate drafted Community Notes before submitting
Before submitting a note, developers can get the note evaluated using the `POST https://api.x.com/2/evaluate_note` endpoint.
## Manage Community Notes
Developers can submit Community Notes on X Posts using the `POST https://api.x.com/2/notes` endpoint.
## Rate limits
The current rate limits are 90 requests per 15 minutes for all Community Notes endpoints and an additional 250 requests per day limit for the Manage Community Notes endpoint.
**Note:** These endpoints are currently in a pilot test. Please check out our [Quick Start Guide](https://docs.x.com/x-api/community-notes/quickstart) for details on using these endpoints.
# Community Notes API quickstart for Enterprise
Source: https://docs.x.com/enterprise-api/community-notes/quickstart
Enterprise quickstart for the Community Notes API: authenticate, search eligible Posts, and submit proposed notes as an AI Note Writer step by step.
This guide walks you through using the Community Notes API to search for eligible Posts and submit notes.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Enrollment as a [Community Notes AI Note Writer](https://communitynotes.x.com/guide/en/api/overview)
* User Access Token (OAuth 1.0a)
Currently, `test_mode` must be set to `true` for all requests. Test notes are not publicly visible.
***
## Find Posts eligible for notes
```bash theme={null}
curl "https://api.x.com/2/notes/search/posts_eligible_for_notes?\
test_mode=true&\
max_results=100" \
-H "Authorization: OAuth ..."
```
```python theme={null}
from requests_oauthlib import OAuth1Session
import json
oauth = OAuth1Session(
client_key='YOUR_API_KEY',
client_secret='YOUR_API_SECRET',
resource_owner_key='YOUR_ACCESS_TOKEN',
resource_owner_secret='YOUR_ACCESS_TOKEN_SECRET',
)
url = "https://api.x.com/2/notes/search/posts_eligible_for_notes"
params = {"test_mode": True, "max_results": 100}
response = oauth.get(url, params=params)
print(json.dumps(response.json(), indent=2))
```
```json theme={null}
{
"data": [
{
"id": "1933207126262096118",
"text": "Join us to learn more about our new analytics endpoints...",
"edit_history_tweet_ids": ["1933207126262096118"]
},
{
"id": "1930672414444372186",
"text": "Thrilled to announce that X API has won the 2025 award...",
"edit_history_tweet_ids": ["1930672414444372186"]
}
],
"meta": {
"newest_id": "1933207126262096118",
"oldest_id": "1930672414444372186",
"result_count": 2
}
}
```
Use the Post `id` from the response to write a Community Note.
***
## Submit a Community Note
A Community Note requires:
* `post_id` — The Post you're adding context to
* `text` — Your note (1-280 characters, must include a source URL)
* `classification` — Either `misinformed_or_potentially_misleading` or `not_misleading`
* `misleading_tags` — Required if classification is misleading
* `trustworthy_sources` — Boolean indicating if source is trustworthy
```bash theme={null}
curl -X POST "https://api.x.com/2/notes" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{
"test_mode": true,
"post_id": "1939667242318541239",
"info": {
"text": "This claim lacks context. See the full report: https://example.com/report",
"classification": "misinformed_or_potentially_misleading",
"misleading_tags": ["missing_important_context"],
"trustworthy_sources": true
}
}'
```
```python theme={null}
from requests_oauthlib import OAuth1Session
import json
oauth = OAuth1Session(
client_key='YOUR_API_KEY',
client_secret='YOUR_API_SECRET',
resource_owner_key='YOUR_ACCESS_TOKEN',
resource_owner_secret='YOUR_ACCESS_TOKEN_SECRET',
)
payload = {
"test_mode": True,
"post_id": "1939667242318541239",
"info": {
"text": "This claim lacks context. See the full report: https://example.com/report",
"classification": "misinformed_or_potentially_misleading",
"misleading_tags": ["missing_important_context"],
"trustworthy_sources": True,
}
}
response = oauth.post("https://api.x.com/2/notes", json=payload)
print(json.dumps(response.json(), indent=2))
```
```json theme={null}
{
"data": {
"note_id": "1938678124100886981"
}
}
```
***
## Get your submitted notes
Retrieve notes you've written:
```python theme={null}
from requests_oauthlib import OAuth1Session
import json
oauth = OAuth1Session(
client_key='YOUR_API_KEY',
client_secret='YOUR_API_SECRET',
resource_owner_key='YOUR_ACCESS_TOKEN',
resource_owner_secret='YOUR_ACCESS_TOKEN_SECRET',
)
url = "https://api.x.com/2/notes/search/notes_written"
params = {"test_mode": True, "max_results": 100}
response = oauth.get(url, params=params)
print(json.dumps(response.json(), indent=2))
```
**Response:**
```json theme={null}
{
"data": [
{
"id": "1939827717186494817",
"info": {
"text": "This claim lacks context. https://example.com/report",
"classification": "misinformed_or_potentially_misleading",
"misleading_tags": ["missing_important_context"],
"post_id": "1939719604957577716",
"trustworthy_sources": true
}
}
],
"meta": {
"result_count": 1
}
}
```
***
## Classification options
When classification is `misinformed_or_potentially_misleading`, include one or more tags:
| Tag | Description |
| :-------------------------- | :------------------------------- |
| `disputed_claim_as_fact` | Presents disputed claim as fact |
| `factual_error` | Contains factual errors |
| `manipulated_media` | Media has been altered |
| `misinterpreted_satire` | Satire taken out of context |
| `missing_important_context` | Lacks key context |
| `outdated_information` | Information is no longer current |
| `other` | Other reasons |
When classification is `not_misleading`, no misleading tags are required.
***
## Common errors
```json theme={null}
{"title": "Unauthorized", "status": 401, "detail": "Unauthorized"}
```
**Resolution:** Check your OAuth credentials are correct.
```json theme={null}
{"detail": "User must be an API Note Writer to access this endpoint."}
```
**Resolution:** Enroll as a [Community Notes AI Note Writer](https://communitynotes.x.com/guide/en/api/overview).
```json theme={null}
{"message": "User already created a note for this post."}
```
**Resolution:** You can only submit one note per Post.
***
## Next steps
Official Community Notes documentation
Working code examples
# Search for Community Notes Written
Source: https://docs.x.com/enterprise-api/community-notes/search-for-community-notes-written
get /2/notes/search/notes_written
Returns all the community notes written by the user.
# Search for Posts Eligible for Community Notes
Source: https://docs.x.com/enterprise-api/community-notes/search-for-posts-eligible-for-community-notes
get /2/notes/search/posts_eligible_for_notes
Returns all the posts that are eligible for community notes.
# Integration guide
Source: https://docs.x.com/enterprise-api/compliance/batch-compliance/integrate
When using the Batch compliance endpoints, developers can batch upload large amounts of X. Reference for the Enterprise X API tier covering batch compliance.
## Working with resumable uploads
When using the Batch compliance endpoints, developers can batch upload large amounts of X data and understand what action is needed to ensure that their datasets reflect user intent and the current state of the content on X. Uploading large amounts of data to a remote server is a relatively straightforward operation when systems and connectivity are stable and reliable. However, this may not always be the case. Some environments may impose a connection timeout, effectively cutting the connection between your app and the upload server after a set amount of time; you may also encounter connection issues, for example when trying to upload a large file from your laptop over a wi-fi connection. In these circumstances, it’s desirable to upload smaller portions of that file at a time, rather than having one single continuous connection.
X's batch compliance endpoints rely on Google Cloud Storage to process large files. This type of storage is optimized for various applications; Cloud Storage supports a technique to manage large files called resumable uploads.
If the upload goes wrong at any point, Google Cloud Storage is able to resume the operation from where it was left off.
### Creating a resumable job
#### Step one:
First, you will have to create a compliance job and specify whether you will be uploading Post IDs or user IDs (using the type parameter). Additionally, add resumable to the body and set it to true. Make sure to replace the \$APP\_ACCESS\_TOKEN below with your App only Access Token below.
```
curl --request POST \
'https://api.x.com/2/compliance/jobs' --header 'Authorization: Bearer $APP_ACCESS_TOKEN --header 'Content-Type: application/json' --data-raw '{
"type": "tweets",
```
# Batch Compliance
Source: https://docs.x.com/enterprise-api/compliance/batch-compliance/introduction
Use Enterprise Batch Compliance endpoints to upload Post ID or user ID datasets and retrieve current compliance status for deletions, suspensions, and edits.
The Batch Compliance endpoints let you upload datasets of Post IDs or user IDs and receive their current compliance status. Use this to identify deleted Posts, suspended accounts, and other compliance events.
## Overview
Check status of Posts in bulk
Check status of users in bulk
Submit jobs and retrieve results later
Process millions of IDs
***
## How it works
1. **Create a job** — Specify the type (Posts or users) and upload URL
2. **Upload IDs** — Upload your dataset to the provided URL
3. **Wait for processing** — Job processes asynchronously
4. **Download results** — Get compliance status for each ID
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------------------- | :-------------------------- |
| POST | [`/2/compliance/jobs`](/x-api/compliance/create-compliance-job) | Create a new compliance job |
| GET | [`/2/compliance/jobs/:id`](/x-api/compliance/get-compliance-job-by-id) | Get job status |
| GET | [`/2/compliance/jobs`](/x-api/compliance/get-compliance-jobs) | List all jobs |
***
## Job types
| Type | Description |
| :------- | :--------------------------- |
| `tweets` | Check Post compliance status |
| `users` | Check user compliance status |
***
## Compliance events
### Post events
| Event | Description |
| :---------- | :--------------------------- |
| `deleted` | Post was deleted by user |
| `bounced` | Post failed compliance check |
| `protected` | Account became protected |
| `suspended` | Account was suspended |
| `scrub_geo` | Geo data was removed |
### User events
| Event | Description |
| :------------ | :----------------------- |
| `deleted` | Account was deleted |
| `suspended` | Account was suspended |
| `protected` | Account became protected |
| `deactivated` | Account was deactivated |
***
## Example: Create a job
```bash theme={null}
curl -X POST "https://api.x.com/2/compliance/jobs" \
-H "Authorization: Bearer $BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"type": "tweets",
"name": "my-compliance-job"
}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [Bearer Token](/resources/fundamentals/authentication)
Create your first compliance job
Key concepts and best practices
Full endpoint documentation
# Quickstart
Source: https://docs.x.com/enterprise-api/compliance/batch-compliance/quickstart
This guide walks you through creating a batch compliance job to check the compliance. Reference for the Enterprise X API tier covering batch compliance.
This guide walks you through creating a batch compliance job to check the compliance status of Posts or users.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
Create a new compliance job specifying the type (tweets or users):
```bash theme={null}
curl -X POST "https://api.x.com/2/compliance/jobs" \
-H "Authorization: Bearer $BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"type": "tweets",
"name": "my-compliance-job"
}'
```
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/compliance/jobs"
headers = {
"Authorization": f"Bearer {bearer_token}",
"Content-Type": "application/json"
}
payload = {
"type": "tweets",
"name": "my-compliance-job"
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
```
**Response:**
```json theme={null}
{
"data": {
"id": "1234567890",
"type": "tweets",
"name": "my-compliance-job",
"status": "created",
"upload_url": "https://storage.googleapis.com/...",
"download_url": "https://storage.googleapis.com/...",
"created_at": "2024-01-15T10:00:00.000Z"
}
}
```
Save the `upload_url` and `download_url` for the next steps.
Create a text file with one ID per line:
```
1234567890
1234567891
1234567892
1234567893
```
Save as `ids.txt`.
Upload the file to the provided `upload_url`:
```bash theme={null}
curl -X PUT "UPLOAD_URL_FROM_RESPONSE" \
-H "Content-Type: text/plain" \
--data-binary @ids.txt
```
Poll the job status until it's complete:
```bash theme={null}
curl "https://api.x.com/2/compliance/jobs/1234567890" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
**Job statuses:**
| Status | Description |
| :------------ | :---------------------------- |
| `created` | Job created, awaiting upload |
| `in_progress` | Processing data |
| `complete` | Results ready for download |
| `failed` | Job failed |
| `expired` | Job expired before completion |
Once status is `complete`, download from the `download_url`:
```bash theme={null}
curl "DOWNLOAD_URL_FROM_RESPONSE" -o results.json
```
**Result format** (one JSON object per line):
```json theme={null}
{"id": "1234567890", "action": "delete", "created_at": "2024-01-10T12:00:00.000Z", "redacted_at": "2024-01-12T08:30:00.000Z", "reason": "deleted"}
{"id": "1234567891", "action": "delete", "created_at": "2024-01-10T12:00:00.000Z", "redacted_at": "2024-01-13T14:20:00.000Z", "reason": "suspended"}
```
Only IDs with compliance events appear in the results. IDs not in the results are still valid.
***
## Compliance actions
| Action | Reason | Description |
| :------- | :---------- | :--------------------------- |
| `delete` | `deleted` | Post was deleted |
| `delete` | `bounced` | Post failed compliance check |
| `delete` | `protected` | Account became protected |
| `delete` | `suspended` | Account was suspended |
| `delete` | `scrub_geo` | Geo data was removed |
| Action | Reason | Description |
| :------- | :------------ | :----------------------- |
| `delete` | `deleted` | Account was deleted |
| `delete` | `suspended` | Account was suspended |
| `delete` | `protected` | Account became protected |
| `delete` | `deactivated` | Account was deactivated |
***
## List all jobs
Get all compliance jobs for your App:
```bash theme={null}
curl "https://api.x.com/2/compliance/jobs?type=tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Next steps
Key concepts and best practices
Real-time compliance events
Full endpoint documentation
# Create Compliance Job
Source: https://docs.x.com/enterprise-api/compliance/create-compliance-job
post /2/compliance/jobs
Creates a new Compliance Job for the specified job type.
# Get Compliance Job by ID
Source: https://docs.x.com/enterprise-api/compliance/get-compliance-job-by-id
get /2/compliance/jobs/{id}
Retrieves details of a specific Compliance Job by its ID.
# Get Compliance Jobs
Source: https://docs.x.com/enterprise-api/compliance/get-compliance-jobs
get /2/compliance/jobs
Retrieves a list of Compliance Jobs filtered by job type and optional status.
# Enterprise compliance event streams for X data
Source: https://docs.x.com/enterprise-api/compliance/streams/introduction
Keep stored X data in sync with deletes, edits, and account changes using Enterprise compliance event streams for Posts and users in near real time.
X is committed to our community of developers who build with the X API. As part of this commitment, we aim to make our API open and fair to developers, safe for people on X and beneficial for the X platform as a whole. It is crucial that any developer who stores X content offline, ensures the data reflects user intent and the current state of content on X. For example, when someone on X deletes a Post or their account, protects their Posts, or edits a Post, it is critical for both X and our developers to honor that person's expectations and intent.
Near real-time streams of compliance events provide developers the tools to maintain X data in compliance with the [X Developer Agreement and Policy](https://developer.x.com/en/developer-terms/policy).
There are two compliance event streams, one for *Post compliance* events, and one for *User compliance* events. These streams are available with Enterprise access and are designed to help partners that ingest high volumes of data 'listen' for compliance events such as Post edit events.
These streams provide the following events:
**Post compliance stream:**
* **delete** - indicates that the Post was deleted.
* **tweet\_edit** - indicates a Post has been edited and provides the ID of the updated Post.
* **withheld** - indicates that the Post has been withheld from one or more countries.
* **drop** - indicates that the Post should be removed from public view.
* **undrop** - indicates that the Post may be displayed again and treated as public.
**User compliance stream:**
* **user\_delete** - indicates that the User account was deleted
* **user\_undelete** - indicates that the User account was undeleted
* **user\_protect** - indicates that the User account became private
* **user\_unprotect** - indicates that the User account became public
* **user\_withheld** - indicates that the User account has been withheld from one or more countries.
* **user\_suspend** - indicates that the User account was suspended
* **user\_unsuspend** - indicates that the User account was unsuspended
* **user\_profile\_modification** - indicates that the User profile has been updated. This includes an updated description, name, location, and URL.
**Account setup**
To access these endpoints, you will need:
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info).
* To authenticate using the keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started guide](/x-api/getting-started/getting-access).
***
## Streaming fundamentals
Best practices for streaming clients
Reconnect gracefully
Handle high throughput
Build resilient applications
# Get Connection History
Source: https://docs.x.com/enterprise-api/connections/get-connection-history
get /2/connections
Returns active and historical streaming connections with disconnect reasons for the authenticated application.
# Stream Connections
Source: https://docs.x.com/enterprise-api/connections/introduction
The Stream Connections endpoints let you retrieve the history of your application's streaming. Reference for the Enterprise X API tier covering connections.
The Stream Connections endpoints let you retrieve the history of your application's streaming connections and terminate active or multiple connections. Use these to monitor connection status, resolve issues like duplicate connections, and manage streaming sessions for endpoints like Filtered Stream and Sampled Stream.
These endpoints require [Bearer Token authentication](/fundamentals/authentication/oauth-2-0/application-only) and are available for apps with access to streaming endpoints.
## Overview
View active and past connections
End all active streaming connections
Stop connections for specific streams
Kill specific connections by UUID
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------------------------------- | :---------------------------------------------- |
| GET | [`/2/connections`](/x-api/connections/get-connection-history) | Get active and historical streaming connections |
| DELETE | [`/2/connections/all`](/x-api/connections/terminate-all-connections) | Terminate all active connections |
| DELETE | [`/2/connections/{endpoint_id}`](/x-api/connections/terminate-connections-by-endpoint) | Terminate connections for a specific endpoint |
| DELETE | [`/2/connections`](/x-api/connections/terminate-multiple-connections) | Terminate multiple connections by UUIDs |
***
## Use cases
* **Troubleshoot disconnections** — Check history to diagnose issues ([see handling disconnections](/x-api/fundamentals/handling-disconnections))
* **Enforce connection limits** — Terminate duplicate or excess connections
* **Clean up sessions** — Stop all streams before maintenance or redeploy
* **Monitor usage** — Track connection patterns across endpoints like filtered\_stream, sample\_stream
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/fundamentals/developer-apps) in the Developer Console with streaming access
* Your App's [Bearer Token](/fundamentals/authentication/oauth-2-0/application-only)
Full endpoint documentation
Learn about streaming
# Terminate all connections
Source: https://docs.x.com/enterprise-api/connections/terminate-all-connections
delete /2/connections/all
Terminates all active streaming connections for the authenticated application.
# Terminate connections by endpoint
Source: https://docs.x.com/enterprise-api/connections/terminate-connections-by-endpoint
delete /2/connections/{endpoint_id}
Terminates all streaming connections for a specific endpoint ID for the authenticated application.
# Terminate multiple connections
Source: https://docs.x.com/enterprise-api/connections/terminate-multiple-connections
delete /2/connections
Terminates multiple streaming connections by their UUIDs for the authenticated application.
# Manage Direct Message blocks on the Enterprise API
Source: https://docs.x.com/enterprise-api/direct-messages/blocks/introduction
Use the Enterprise Manage DM blocks endpoints to block or unblock accounts on behalf of an authenticated user and control who can send Direct Messages on X.
The manage DM blocks endpoints enable you to block or unblock a specified account on behalf of an authenticated user. For these endpoints, there are two POST methods available:
* **/2/users/:id/dm/block**: Allows you to block an account
* **/2/users/:id/dm/unblock**: Allows you to unblock an account
### Getting started
### Authentication
Since you are making requests on behalf of a user, you must authenticate these endpoints with either [OAuth 1.0a User Context](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow) or [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2), and utilize the user Access Tokens associated with the user you are making the request on behalf of. You can generate this user Access Token using the [3-legged OAuth flow](https://developer.x.com/resources/fundamentals/authentication/obtaining-user-access-tokens) (OAuth 1.0a) or using the [Authorization Code with PKCE grant flow](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) (OAuth 2.0).
### Making a request
Block
Once a user has authenticated with your app, you can call the Block endpoint on behalf of user as shown below:
```
curl --request POST 'https://api.x.com/2/users/:id/dm/block' --header 'Authorization: ••••••'
```
If the request is successful, you should see the JSON response as shown below:
```
{
"data": {
"blocked": true
}
}
```
**Unblock**
Once a user has authenticated with your app, you can call the Unblock endpoint on behalf of user as shown below:
```
curl --request POST 'https://api.x.com/2/users/:id/dm/unblock' --header 'Authorization: ••••••'
```
If the request is successful, you should see the JSON response as shown below:
```
{
"data": {
"blocked": false
}
}
```
# Create DM conversation
Source: https://docs.x.com/enterprise-api/direct-messages/create-dm-conversation
post /2/dm_conversations
Initiates a new direct message conversation with specified participants.
# Create DM message by conversation ID
Source: https://docs.x.com/enterprise-api/direct-messages/create-dm-message-by-conversation-id
post /2/dm_conversations/{dm_conversation_id}/messages
Sends a new direct message to a specific conversation by its ID.
# Create DM message by participant ID
Source: https://docs.x.com/enterprise-api/direct-messages/create-dm-message-by-participant-id
post /2/dm_conversations/with/{participant_id}/messages
Sends a new direct message to a specific participant by their ID.
# Delete DM event
Source: https://docs.x.com/enterprise-api/direct-messages/delete-dm-event
delete /2/dm_events/{event_id}
Deletes a specific direct message event by its ID, if owned by the authenticated user.
# Download DM Media
Source: https://docs.x.com/enterprise-api/direct-messages/download-dm-media
get /2/dm_conversations/media/{dm_id}/{media_id}/{resource_id}
Downloads media attached to a legacy Direct Message. The requesting user must be a participant in the conversation containing the specified DM event. The response body contains raw binary bytes.
# Get DM event by ID
Source: https://docs.x.com/enterprise-api/direct-messages/get-dm-event-by-id
get /2/dm_events/{event_id}
Retrieves details of a specific direct message event by its ID.
# Get DM events
Source: https://docs.x.com/enterprise-api/direct-messages/get-dm-events
get /2/dm_events
Retrieves a list of recent direct message events across all conversations.
# Get DM events for a DM conversation
Source: https://docs.x.com/enterprise-api/direct-messages/get-dm-events-for-a-dm-conversation
get /2/dm_conversations/with/{participant_id}/dm_events
Retrieves direct message events for a specific conversation.
# Get DM events for a DM conversation
Source: https://docs.x.com/enterprise-api/direct-messages/get-dm-events-for-a-dm-conversation-1
get /2/dm_conversations/{id}/dm_events
Retrieves direct message events for a specific conversation.
# Integration Guide
Source: https://docs.x.com/enterprise-api/direct-messages/lookup/integrate
This guide covers the key concepts you need to integrate the Direct Messages lookup endpoints into. Reference for the Enterprise X API tier covering lookup.
This guide covers the key concepts you need to integrate the Direct Messages lookup endpoints into your application.
***
## Authentication
DM endpoints require user authentication to access private conversations:
| Method | Description |
| :----------------------------------------------------------------------------------------------------------------------------- | :------------- |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | Recommended |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Legacy support |
App-Only authentication is not supported. All Direct Messages are private.
### Required scopes (OAuth 2.0)
| Scope | Required for |
| :----------- | :-------------------- |
| `dm.read` | Reading DM events |
| `tweet.read` | Required with dm.read |
| `users.read` | Required with dm.read |
***
## Conversation types
Always has exactly two participants. Conversation ID format: `{smaller_user_id}-{larger_user_id}`
Two or more participants. Membership can change over time.
***
## Event types
| Event | Description | Key fields |
| :------------------ | :----------------- | :----------------------------- |
| `MessageCreate` | A message was sent | `text`, `sender_id` |
| `ParticipantsJoin` | User joined group | `participant_ids`, `sender_id` |
| `ParticipantsLeave` | User left group | `participant_ids` |
### Example events
```json theme={null}
{
"id": "1582838499983564806",
"event_type": "MessageCreate",
"text": "Hi everyone.",
"sender_id": "944480690",
"dm_conversation_id": "1578398451921985538",
"created_at": "2022-10-19T20:58:00.000Z"
}
```
```json theme={null}
{
"id": "1582835469712138240",
"event_type": "ParticipantsJoin",
"participant_ids": ["944480690"],
"sender_id": "17200003",
"dm_conversation_id": "1578398451921985538",
"created_at": "2022-10-19T20:45:58.000Z"
}
```
```json theme={null}
{
"id": "1582838535115067392",
"event_type": "ParticipantsLeave",
"participant_ids": ["944480690"],
"dm_conversation_id": "1578398451921985538",
"created_at": "2022-10-19T20:58:09.000Z"
}
```
***
## Fields and expansions
### Default fields
| Event type | Default fields |
| :--------------------- | :------------------------------------ |
| MessageCreate | `id`, `event_type`, `text` |
| ParticipantsJoin/Leave | `id`, `event_type`, `participant_ids` |
### Available fields
| Field | Description | Events |
| :------------------- | :---------------- | :------------------ |
| `dm_conversation_id` | Conversation ID | All |
| `created_at` | Event timestamp | All |
| `sender_id` | Who sent/invited | MessageCreate, Join |
| `attachments` | Media attachments | MessageCreate |
| `referenced_tweets` | Shared Posts | MessageCreate |
### Available expansions
| Expansion | Returns |
| :----------------------- | :---------------------------- |
| `sender_id` | User object for sender |
| `participant_ids` | User objects for participants |
| `attachments.media_keys` | Media objects |
| `referenced_tweets.id` | Post objects |
### Example with expansions
```bash cURL theme={null}
curl "https://api.x.com/2/dm_events?\
dm_event.fields=created_at,sender_id,attachments&\
expansions=sender_id,attachments.media_keys&\
user.fields=username,profile_image_url&\
media.fields=url,type" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get DM events with expansions
for page in client.dm_events.list(
dm_event_fields=["created_at", "sender_id", "attachments"],
expansions=["sender_id", "attachments.media_keys"],
user_fields=["username", "profile_image_url"],
media_fields=["url", "type"],
max_results=100
):
for event in page.data:
print(f"Event: {event.event_type} - {event.text}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
const paginator = client.dmEvents.list({
dmEventFields: ["created_at", "sender_id", "attachments"],
expansions: ["sender_id", "attachments.media_keys"],
userFields: ["username", "profile_image_url"],
mediaFields: ["url", "type"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((event) => {
console.log(`Event: ${event.event_type} - ${event.text}`);
});
}
```
***
## Pagination
DM events are returned in reverse chronological order (newest first):
```bash cURL theme={null}
# First request
curl "https://api.x.com/2/dm_events?max_results=100" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
# Subsequent request with pagination token
curl "https://api.x.com/2/dm_events?max_results=100&pagination_token=NEXT_TOKEN" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# The SDK handles pagination automatically
all_events = []
for page in client.dm_events.list(max_results=100):
if page.data:
all_events.extend(page.data)
print(f"Found {len(all_events)} DM events")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
async function getAllDMEvents() {
const allEvents = [];
// The SDK handles pagination automatically
const paginator = client.dmEvents.list({ maxResults: 100 });
for await (const page of paginator) {
if (page.data) {
allEvents.push(...page.data);
}
}
return allEvents;
}
// Usage
const events = await getAllDMEvents();
console.log(`Found ${events.length} DM events`);
```
Events from up to **30 days ago** are available.
***
## ID compatibility with v1.1
Conversation and event IDs are shared between v1.1 and v2 endpoints. This means you can:
* Use v2 to retrieve events, then use v1.1 to delete specific messages
* Reference conversation IDs from x.com URLs in API requests
***
## Next steps
Make your first DM lookup request
Send Direct Messages
Full endpoint documentation
Working code examples
# Direct Messages Lookup
Source: https://docs.x.com/enterprise-api/direct-messages/lookup/introduction
The Direct Messages lookup endpoints let you retrieve DM events for the authenticated user. Reference for the Enterprise X API tier covering lookup.
The Direct Messages lookup endpoints let you retrieve DM events for the authenticated user, including messages from both one-to-one and group conversations.
## Overview
Get all DM events for the user
Get events from a specific conversation
Get events by conversation ID
Messages, joins, and leaves
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------------------------------------------------------------ | :-------------------------------------- |
| GET | [`/2/dm_events`](/x-api/direct-messages/get-dm-events) | Get all DM events for the user |
| GET | [`/2/dm_conversations/with/:participant_id/dm_events`](/x-api/direct-messages/get-dm-events-for-a-dm-conversation) | Get events from one-to-one conversation |
| GET | [`/2/dm_conversations/:dm_conversation_id/dm_events`](/x-api/direct-messages/get-dm-events-for-a-dm-conversation-1) | Get events by conversation ID |
***
## Event types
| Event | Description |
| :------------------ | :------------------------------------- |
| `MessageCreate` | A message was sent in the conversation |
| `ParticipantsJoin` | A user joined the conversation |
| `ParticipantsLeave` | A user left the conversation |
***
## Data retention
Events from up to **30 days ago** are available through these endpoints.
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [3-legged OAuth](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow)
Make your first DM lookup request
Key concepts and best practices
Full endpoint documentation
Working code examples
# Migration guide
Source: https://docs.x.com/enterprise-api/direct-messages/lookup/migrate
Migrate Direct Message lookup integrations from X API v1.1 to v2, with endpoint mappings, parameter changes, and updated response structures.
## Comparing v1.1 and v2 Direct Message event lookup endpoints
Both v1.1 and v2 versions of the Direct Messages endpoints provide methods for looking up Direct Message events. This guide is intended to help understand the differences and provide information for migrating to v2.
A major difference between the two versions is that v1.1 supports only one-to-one conversations, while v2 introduces support for group conversations. One artifact of this is that v1.1 supports only "message created" events, while v2 also supports events associated with participants joining and leaving conversations. In fact, a fundamental v2 update is establishing dm\_conversations as a core API object.
With v1.1. there are two endpoints for retrieving Direct Messages (again, new messages are the only event type supported with v1.1):
* GET direct\_messages/events/show - Retrieves a single event by ID.
* GET direct\_messages/events/list - Retrieves up to 30 days of one-to-one Direct Messages sent and received by the authenticated user. Note that this method is not able to retrieve messages from group conversations.
With this v2 release, there are three GET methods for retrieving Direct Message conversation events:
* **GET /2/dm\_conversations/with/:participant\_id/dm\_events** - Retrieves Direct Message events associated with a one-to-one conversation. The :participant\_id path parameter is the User ID of the account having the conversation with the authenticated user making this request.
* **GET /2/dm\_conversations/:dm\_conversation\_id/dm\_events** - Retrieves Direct Message events associated with a specific conversation ID, as indicated by the :dm\_conversation\_id path parameter. This method supports both one-to-one and group conversations.
* **GET /2/dm\_events** - Retrieves Direct Message events associated with a user, including both one-to-one and group conversations. Events from up to 30 days ago are available.
An important detail is that conversation and event IDs are shared across v1.1 and v2 versions of the X Platform. This means both versions can be used together. For example, the Direct Messages v1.1 endpoints provide methods for returning a single event and for deleting events, methods not yet available with v2. Since IDs are common across v1.1 and v2, you can make v1.1 requests based on IDs provided by v2, or by referencing conversation IDs displayed in conversation URLs on the X application.
The following table compares fundamental aspects of the v1.1 and v2 Direct Message event lookup endpoints. The X API v2 characteristics shared here are common to all of the Direct Message lookup endpoints.
| | | |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint root path | [/1.1/direct\_messages](https://api.x.com/1.1/direct_messages) | [/2/dm\_conversations](https://api.x.com/2/users/:id/dm_conversations)
Direct Messages conversations are introduced as a fundamental API object.
These endpoints retrieve MessageCreate, ParticipantsJoin, and ParticipantLeave events. |
| HTTP methods supported | GET | GET |
| Supports Group Direct Messages | | ✔ |
| Event types supported | message\_create | MessageCreate, ParticipantsJoin, ParticipantsLeave |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2 User Context (scopes: dm.read, tweet.read, user.read) |
| Requires the use of credentials from a [developer App](/resources/fundamentals/authentication) associated with a X API v2 [Project](/resources/fundamentals/developer-apps) | | ✔ |
| Default request [rate limits](/x-api/fundamentals/rate-limits)\* \*All requests require user tokens | | GET requests: 300 requests per 15 mins
Rate limit is applied across all three endpoints |
The following tables compare the v2 GET methods with version v1.1. Note that these v2 offerings expand the available capabilities by supporting group conversations.
\*\*Get all messages in a specific one-to-one conversation \*\*
***
Path: GET /2/dm\_conversations/with/:participant\_id/dm\_events
| | | |
| :------------------------------------------------------------- | :------------------------------------------------ | :-------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Endpoint path | GET
/1.1/direct\_messages/events/list | GET /2/dm\_conversations/with/:participant\_id/dm\_events |
| How much event history is available | 30 days | No limit |
| Default request [rate limits](/x-api/fundamentals/rate-limits) | 15 requests per 15 minutes | 300 requests per 15 minutes Rate limit is applied across all three GET endpoints |
\*\*Get all messages by conversation ID \*\*
Path: GET /2/dm\_conversations/:dm\_conversation\_id/dm\_events
| | | |
| :------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Endpoint path | Not supported. V1.1 can return messages from one-to-one conversations only and there is no support for retrieving events by conversation IDs. | GET /2/dm\_conversations/:dm\_conversation\_id/dm\_events |
| How much event history is available | 30 days | No limit |
| Supports group conversations | | ✔ |
| Default request [rate limits](/x-api/fundamentals/rate-limits) | 15 requests per 15 minutes | 300 requests per 15 minutes Rate limit is applied across all three GET endpoints |
**Get all events across an authenticated user's conversations, both one-to-one and group conversations**
Path: GET /2/dm\_events
| | | |
| :------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Endpoint path | GET /1.1/direct\_messages/events/list
V1.1 can return messages from one-to-one conversations only. | GET /2/dm\_events |
| How much event history is available | 30 days | 30 days |
| Supports group conversations | | ✔ |
| Default request [rate limits](/x-api/fundamentals/rate-limits) | 15 requests per 15 minutes | 300 requests per 15 minutes Rate limit is applied across all three GET endpoints |
# Quickstart
Source: https://docs.x.com/enterprise-api/direct-messages/lookup/quickstart
This guide walks you through retrieving Direct Message events for the authenticated user. Reference for the Enterprise X API tier covering lookup.
This guide walks you through retrieving Direct Message events for the authenticated user.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Get all DM events
Retrieve all DM events for the authenticated user:
```bash cURL theme={null}
curl "https://api.x.com/2/dm_events?\
dm_event.fields=created_at,sender_id,text&\
max_results=100" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get all DM events with pagination
for page in client.dm_events.list(
dm_event_fields=["created_at", "sender_id", "text"],
max_results=100
):
for event in page.data:
print(f"{event.event_type}: {event.text}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get all DM events with pagination
const paginator = client.dmEvents.list({
dmEventFields: ["created_at", "sender_id", "text"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((event) => {
console.log(`${event.event_type}: ${event.text}`);
});
}
```
### Response
```json theme={null}
{
"data": [
{
"id": "1234567890",
"event_type": "MessageCreate",
"text": "Hello! How are you?",
"sender_id": "9876543210",
"created_at": "2024-01-15T10:30:00.000Z"
}
],
"meta": {
"result_count": 1,
"next_token": "abc123"
}
}
```
***
## Get one-to-one conversation
Retrieve DM events from a specific one-to-one conversation:
```bash cURL theme={null}
curl "https://api.x.com/2/dm_conversations/with/9876543210/dm_events?\
dm_event.fields=created_at,sender_id,text" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get DM events from a one-to-one conversation
for page in client.dm_events.get_by_participant(
participant_id="9876543210",
dm_event_fields=["created_at", "sender_id", "text"]
):
for event in page.data:
print(f"{event.created_at}: {event.text}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get DM events from a one-to-one conversation
const paginator = client.dmEvents.getByParticipant("9876543210", {
dmEventFields: ["created_at", "sender_id", "text"],
});
for await (const page of paginator) {
page.data?.forEach((event) => {
console.log(`${event.created_at}: ${event.text}`);
});
}
```
Replace `9876543210` with the other participant's user ID.
***
## Get conversation by ID
Retrieve DM events from a specific conversation ID:
```bash cURL theme={null}
curl "https://api.x.com/2/dm_conversations/1234567890-9876543210/dm_events?\
dm_event.fields=created_at,sender_id,text" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get DM events from a conversation by ID
for page in client.dm_events.get_by_conversation(
dm_conversation_id="1234567890-9876543210",
dm_event_fields=["created_at", "sender_id", "text"]
):
for event in page.data:
print(f"{event.created_at}: {event.text}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get DM events from a conversation by ID
const paginator = client.dmEvents.getByConversation("1234567890-9876543210", {
dmEventFields: ["created_at", "sender_id", "text"],
});
for await (const page of paginator) {
page.data?.forEach((event) => {
console.log(`${event.created_at}: ${event.text}`);
});
}
```
***
## Filter by event type
Get only specific event types:
```bash cURL theme={null}
curl "https://api.x.com/2/dm_events?\
event_types=MessageCreate&\
dm_event.fields=created_at,sender_id,text" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get only MessageCreate events
for page in client.dm_events.list(
event_types=["MessageCreate"],
dm_event_fields=["created_at", "sender_id", "text"]
):
for event in page.data:
print(f"{event.text}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get only MessageCreate events
const paginator = client.dmEvents.list({
eventTypes: ["MessageCreate"],
dmEventFields: ["created_at", "sender_id", "text"],
});
for await (const page of paginator) {
page.data?.forEach((event) => {
console.log(event.text);
});
}
```
### Event types
| Type | Description |
| :------------------ | :----------------------- |
| `MessageCreate` | A message was sent |
| `ParticipantsJoin` | User joined conversation |
| `ParticipantsLeave` | User left conversation |
***
## Include user data
Expand sender information:
```bash cURL theme={null}
curl "https://api.x.com/2/dm_events?\
dm_event.fields=created_at,sender_id,text&\
expansions=sender_id&\
user.fields=username,profile_image_url" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get DM events with sender info
for page in client.dm_events.list(
dm_event_fields=["created_at", "sender_id", "text"],
expansions=["sender_id"],
user_fields=["username", "profile_image_url"]
):
for event in page.data:
# Match sender from includes
print(f"{event.sender_id}: {event.text}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get DM events with sender info
const paginator = client.dmEvents.list({
dmEventFields: ["created_at", "sender_id", "text"],
expansions: ["sender_id"],
userFields: ["username", "profile_image_url"],
});
for await (const page of paginator) {
page.data?.forEach((event) => {
console.log(`${event.sender_id}: ${event.text}`);
});
// Sender user objects are in page.includes.users
}
```
### Response with expansion
```json theme={null}
{
"data": [
{
"id": "1234567890",
"event_type": "MessageCreate",
"text": "Hello!",
"sender_id": "9876543210"
}
],
"includes": {
"users": [
{
"id": "9876543210",
"username": "example_user",
"profile_image_url": "https://..."
}
]
}
}
```
***
## Common parameters
| Parameter | Description |
| :----------------- | :----------------------------------- |
| `max_results` | Events per page (1-100, default 100) |
| `pagination_token` | Token for next page |
| `dm_event.fields` | Event fields to return |
| `event_types` | Filter by event type |
| `expansions` | Related objects to include |
***
## Next steps
Send Direct Messages
Key concepts and best practices
Full endpoint documentation
# Integration Guide
Source: https://docs.x.com/enterprise-api/direct-messages/manage/integrate
This guide covers the key concepts you need to integrate the manage Direct Messages endpoints into. Reference for the Enterprise X API tier covering manage.
This guide covers the key concepts you need to integrate the manage Direct Messages endpoints into your application.
***
## Authentication
DM endpoints require user authentication:
| Method | Description |
| :----------------------------------------------------------------------------------------------------------------------------- | :------------- |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | Recommended |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Legacy support |
App-Only authentication is not supported. All Direct Messages are private.
### Required scopes (OAuth 2.0)
| Scope | Required for |
| :----------- | :---------------------------- |
| `dm.write` | Sending and deleting messages |
| `dm.read` | Required with dm.write |
| `tweet.read` | Required with dm scopes |
| `users.read` | Required with dm scopes |
***
## Endpoints overview
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------- | :-------------------------- |
| POST | `/2/dm_conversations/with/:participant_id/messages` | Send one-to-one message |
| POST | `/2/dm_conversations` | Create group conversation |
| POST | `/2/dm_conversations/:dm_conversation_id/messages` | Add message to conversation |
| DELETE | `/2/dm_events/:event_id` | Delete a message |
***
## Sending messages
### One-to-one message
Send a message to a specific user. Creates a new conversation if one doesn't exist:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/dm_conversations/with/9876543210/messages" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text": "Hello!"}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Send a one-to-one DM
response = client.dm_conversations.create_message(
participant_id="9876543210",
text="Hello!"
)
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Send a one-to-one DM
const response = await client.dmConversations.createMessage({
participantId: "9876543210",
text: "Hello!",
});
console.log(response.data);
```
### Group conversation
Create a new group and send the first message:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/dm_conversations" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"conversation_type": "Group",
"participant_ids": ["944480690", "906948460078698496"],
"message": {"text": "Welcome to our group!"}
}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Create a group conversation
response = client.dm_conversations.create(
conversation_type="Group",
participant_ids=["944480690", "906948460078698496"],
message={"text": "Welcome to our group!"}
)
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Create a group conversation
const response = await client.dmConversations.create({
conversationType: "Group",
participantIds: ["944480690", "906948460078698496"],
message: { text: "Welcome to our group!" },
});
console.log(response.data);
```
The `conversation_type` field must be set to `"Group"` (case sensitive).
### Add to existing conversation
Send a message to any conversation you're part of:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/dm_conversations/1582103724607971328/messages" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text": "Another message"}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Add message to existing conversation
response = client.dm_conversations.add_message(
dm_conversation_id="1582103724607971328",
text="Another message"
)
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Add message to existing conversation
const response = await client.dmConversations.addMessage({
dmConversationId: "1582103724607971328",
text: "Another message",
});
console.log(response.data);
```
***
## Media attachments
Attach one piece of media (photo, video, or GIF) per message.
Use the [Media Upload endpoint](/x-api/media/quickstart/media-upload-chunked) to upload your file and get a `media_id`.
```json theme={null}
{
"text": "Check out this image!",
"attachments": [{"media_id": "1583157113245011970"}]
}
```
* The authenticated user must have uploaded the media
* Media is available for 24 hours after upload
* Only one attachment per message is supported
***
## Sharing Posts
Include a Post in your message by adding the Post URL to the text:
```json theme={null}
{
"text": "Have you seen this? https://x.com/XDevelopers/status/1580559079470145536"
}
```
The response will include a `referenced_tweets` field with the Post ID.
***
## Message requirements
| Field | Required | Notes |
| :------------ | :------- | :------------------------- |
| `text` | Yes\* | Required if no attachments |
| `attachments` | Yes\* | Required if no text |
\*At least one of `text` or `attachments` must be provided.
***
## ID compatibility with v1.1
Conversation and event IDs are shared between v1.1 and v2 endpoints. This enables hybrid workflows:
* Create messages with v2
* Delete messages with v1.1 (not yet available in v2)
* Reference conversation IDs from x.com URLs
***
## Error handling
| Status | Error | Solution |
| :----- | :---------------- | :-------------------------------- |
| 400 | Invalid request | Check request body format |
| 401 | Unauthorized | Verify access token |
| 403 | Forbidden | Check scopes and user permissions |
| 429 | Too Many Requests | Wait and retry |
### Common issues
The recipient may have DM settings that prevent messages from unknown users, or may have blocked you.
Ensure the media was uploaded by the same authenticated user and is less than 24 hours old.
Verify all participant IDs are valid and the users allow group DM invites.
***
## Next steps
Send your first Direct Message
Retrieve DM conversations
Upload media for attachments
Full endpoint documentation
# Manage Direct Messages
Source: https://docs.x.com/enterprise-api/direct-messages/manage/introduction
Use the Enterprise Manage Direct Messages endpoints to create conversations, send new DMs, and delete DM events on behalf of authenticated users on X.
The Manage Direct Messages endpoints let you send and delete Direct Messages on behalf of authenticated users.
## Overview
Send a DM to another user
Delete a DM for yourself
Start a new conversation
Send to group conversations
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------- | :------------------------------ |
| POST | `/2/dm_conversations` | Create a new conversation |
| POST | `/2/dm_conversations/with/:participant_id/messages` | Send to one-to-one conversation |
| POST | `/2/dm_conversations/:dm_conversation_id/messages` | Send to existing conversation |
| DELETE | `/2/dm_events/:id` | Delete a DM event |
***
## Example: Send a message
```bash theme={null}
curl -X POST "https://api.x.com/2/dm_conversations/with/1234567890/messages" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text": "Hello! How are you?"}'
```
## Example response
```json theme={null}
{
"data": {
"dm_conversation_id": "1234567890-0987654321",
"dm_event_id": "1122334455667788990"
}
}
```
***
## Message types
You can send text messages and attach media:
```json theme={null}
{
"text": "Check out this photo!",
"attachments": [{
"media_id": "1234567890123456789"
}]
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
Send your first DM
Key concepts and best practices
Retrieve DM events
Full endpoint documentation
# Migration guide
Source: https://docs.x.com/enterprise-api/direct-messages/manage/migrate
Both v1.1 and v2 versions of the Direct Messages endpoints provide methods for creating Direct. Reference for the Enterprise X API tier covering manage.
## Comparing v1.1 and v2 Manage Direct Message endpoints
Both v1.1 and v2 versions of the Direct Messages endpoints provide methods for creating Direct Message messages. This guide is intended to help understand the differences and provide information for migrating to v2.
A major difference between the two versions is that v1.1 supports only one-to-one conversations, while v2 introduces support for group conversations. One artifact of this is that v1.1 supports only "message created" events, while v2 also supports events associated with participants joining and leaving conversations. In fact, a fundamental v2 update is establishing dm\_conversations as a core API object.
With v1.1. there are two endpoints for managing Direct Messages:
* POST direct\_messages/events/new - Creates a one-to-one Direct Message. This v1.1 endpoint can only create one-to-one messages, and does not support group messages.
* DELETE direct\_messages/events/destroy - Deletes a one-to-one message from the view of the authenticating user.
With this v2 release, there are three POST methods for creating Direct Messages:
* **POST /2/dm\_conversations/with/:participant\_id/messages** - Creates a one-to-one Direct Message. This method either adds the message to an existing one-to-one conversation or creates a new one. The :participant\_id path parameter is the User ID of the account receiving the message.
* **POST /2/dm\_conversations** - Creates a new group conversation and adds a Direct Message to it. These requests require a list of conversation participants. Note that you can create multiple conversations with the same participant list. These requests will always return a new conversation ID.
* **POST /2/dm\_conversations/:dm\_conversation\_id/messages** - Creates a Direct Message and adds it to an existing conversation. The :dm\_conversation\_id path parameter is the ID of the conversation that the message will be added to.
An important detail is that conversation and event IDs are shared across v1.1 and v2 versions of the X Platform. This means both versions can be used together. For example, the Direct Messages v1.1 endpoints provide methods for returning a single event and for deleting events, methods not yet available with v2. Since IDs are common across v1.1 and v2, you can make v1.1 requests based on IDs provided by v2, or by referencing conversation IDs displayed in conversation URLs on the X application.
The following table compares fundamental aspects of the v1.1 and v2 manage Direct Messages endpoints. The X API v2 characteristics shared here are common to all of the Direct Message lookup endpoints.
| | | |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint root path | [/1.1/direct\_messages](https://api.x.com/1.1/direct_messages) | [/2/dm\_conversations](https://api.x.com/2/users/:id/dm_conversations)
Direct Messages conversations are introduced as a fundamental API object.
These endpoints retrieve MessageCreate, ParticipantsJoin, and ParticipantLeave events. |
| HTTP methods supported | POST | POST |
| Supports Group Direct Messages | | ✔ |
| Event types supported | message\_create | MessageCreate, ParticipantsJoin, ParticipantsLeave |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2 User Context (scopes: dm.read, dm.write) |
| Requires the use of credentials from a [developer App](/resources/fundamentals/authentication) associated with a X API v2 [Project](/resources/fundamentals/developer-apps) | | ✔ |
| Default request [rate limits](/x-api/fundamentals/rate-limits)\* \*All requests require user tokens | 1000 requests per user per 24 hours 15000 requests per app per 24 hours | 200 requests per 15 minutes per user
1000 requests per user per 24 hours
15000 requests per app per 24 hours
These rate limits are shared across all dm\_conversations POST endpoints. |
The following tables compare the v2 POST methods with version v1.1. Note that these v2 offerings expand the available capabilities by supporting group conversations.
**Create a new one-to-one Direct Message**
Path: POST /2/dm\_conversations/with/:participant\_id/messages
| | | |
| :------------------------------------------------------------- | :----------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Endpoint path | POST direct\_messages/events/new (message\_create) | POST /2/dm\_conversations/with/:participant\_id/messages |
| Default request [rate limits](/x-api/fundamentals/rate-limits) | 1000 requests per user per 24 hours 15000 requests per app per 24 hours | 200 requests per 15 minutes per user
1000 requests per user per 24 hours
15000 requests per app per 24 hours
These rate limits are shared across all dm\_conversations POST endpoints. |
| Supports group Direct Messages | | ✔ |
**Create a new Direct Message group conversation and add a message to it**
Path: POST /2/dm\_conversations
| | | |
| :------------------------------------------------------------- | :---------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Endpoint path | Not supported | POST /2/dm\_conversations |
| Default request [rate limits](/x-api/fundamentals/rate-limits) | | 200 requests per 15 minutes per user
1000 requests per user per 24 hours
15000 requests per app per 24 hours
These rate limits are shared across all dm\_conversations POST endpoints. |
| Supports group Direct Messages | | ✔ |
**Add a Direct Message to an existing conversation by ID**
Path: POST /2/dm\_conversations/:dm\_conversation\_id/messages
| | | |
| :------------------------------------------------------------- | :---------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Endpoint path | Not supported | POST /2/dm\_conversations/:dm\_conversation\_id/messages |
| Default request [rate limits](/x-api/fundamentals/rate-limits) | | 200 requests per 15 minutes per user
1000 requests per user per 24 hours
15000 requests per app per 24 hours
These rate limits are shared across all dm\_conversations POST endpoints. |
| Supports group Direct Messages | | ✔ |
# Quickstart
Source: https://docs.x.com/enterprise-api/direct-messages/manage/quickstart
This guide walks you through sending Direct Messages and creating group conversations. Reference for the Enterprise X API tier covering manage.
This guide walks you through sending Direct Messages and creating group conversations.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 2.0 PKCE with `dm.write` and `dm.read` scopes)
***
## Send a one-to-one message
You need the user ID of the person you want to message. You can get this from the [User lookup endpoint](/x-api/users/lookup/introduction).
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/dm_conversations/with/9876543210/messages" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text": "Hello! This is a message from the API."}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Send a one-to-one message
response = client.dm.send_message(
participant_id="9876543210",
text="Hello! This is a message from the API."
)
print(f"Message sent: {response.data.dm_event_id}")
print(f"Conversation: {response.data.dm_conversation_id}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Send a one-to-one message
const response = await client.dm.sendMessage({
participantId: "9876543210",
text: "Hello! This is a message from the API.",
});
console.log(`Message sent: ${response.data?.dm_event_id}`);
console.log(`Conversation: ${response.data?.dm_conversation_id}`);
```
```json theme={null}
{
"data": {
"dm_conversation_id": "1234567890-9876543210",
"dm_event_id": "1582103724607971332"
}
}
```
***
## Create a group conversation
Gather the user IDs of everyone you want in the group (excluding yourself).
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/dm_conversations" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"conversation_type": "Group",
"participant_ids": ["944480690", "906948460078698496"],
"message": {"text": "Welcome to our new group!"}
}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Create a group conversation
response = client.dm.create_conversation(
conversation_type="Group",
participant_ids=["944480690", "906948460078698496"],
message={"text": "Welcome to our new group!"}
)
print(f"Group created: {response.data.dm_conversation_id}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Create a group conversation
const response = await client.dm.createConversation({
conversationType: "Group",
participantIds: ["944480690", "906948460078698496"],
message: { text: "Welcome to our new group!" },
});
console.log(`Group created: ${response.data?.dm_conversation_id}`);
```
```json theme={null}
{
"data": {
"dm_conversation_id": "1582103724607971328",
"dm_event_id": "1582103724607971332"
}
}
```
Save the `dm_conversation_id` to add more messages later.
***
## Add a message to an existing conversation
Send a message to a conversation you're already part of:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/dm_conversations/1582103724607971328/messages" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text": "Adding another message to the conversation."}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Add message to existing conversation
response = client.dm.send_message_to_conversation(
dm_conversation_id="1582103724607971328",
text="Adding another message to the conversation."
)
print(f"Message sent: {response.data.dm_event_id}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Add message to existing conversation
const response = await client.dm.sendMessageToConversation(
"1582103724607971328",
{ text: "Adding another message to the conversation." }
);
console.log(`Message sent: ${response.data?.dm_event_id}`);
```
***
## Send a message with media
First, upload your media using the [Media Upload endpoint](/x-api/media/quickstart/media-upload-chunked).
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/dm_conversations/with/9876543210/messages" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Check out this image!",
"attachments": [{"media_id": "1234567890123456789"}]
}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Send message with media
response = client.dm.send_message(
participant_id="9876543210",
text="Check out this image!",
attachments=[{"media_id": "1234567890123456789"}]
)
print(f"Message with media sent: {response.data.dm_event_id}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Send message with media
const response = await client.dm.sendMessage({
participantId: "9876543210",
text: "Check out this image!",
attachments: [{ mediaId: "1234567890123456789" }],
});
console.log(`Message with media sent: ${response.data?.dm_event_id}`);
```
***
## Delete a message
Delete a message you sent:
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/dm_events/1582103724607971332" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Delete a message
response = client.dm.delete_message("1582103724607971332")
print(f"Deleted: {response.data.deleted}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Delete a message
const response = await client.dm.deleteMessage("1582103724607971332");
console.log(`Deleted: ${response.data?.deleted}`);
```
**Response:**
```json theme={null}
{
"data": {
"deleted": true
}
}
```
You can only delete messages you sent, not messages from other participants.
***
## Required scopes
When using OAuth 2.0 PKCE, your access token must have these scopes:
| Scope | Description |
| :----------- | :------------------------------------------ |
| `dm.write` | Send and delete messages |
| `dm.read` | Read conversations (required with dm.write) |
| `tweet.read` | Required for some expansions |
| `users.read` | Required for user expansions |
***
## Next steps
Retrieve DM conversations
Key concepts and best practices
Full endpoint documentation
Working code examples
# Get OpenAPI Spec.
Source: https://docs.x.com/enterprise-api/general/get-openapi-spec
get /2/openapi.json
Retrieves the full OpenAPI Specification in JSON format. (See https://github.com/OAI/OpenAPI-Specification/blob/master/README.md)
# About the Enterprise API — firehose, streams, and webhooks
Source: https://docs.x.com/enterprise-api/getting-started/about-x-api
Overview of the X Enterprise API, including full firehose access, volume and likes streams, account activity webhooks, custom rate limits, and support.
The Enterprise API provides the highest tier of access to X data. It includes everything available in the standard X API plus exclusive high-volume endpoints, semantic embedding operators for Filtered Stream, custom rate limits, and dedicated account management for organizations that need X data at scale.
***
## What you can do
Everything in the standard X API, plus:
| Capability | Description |
| :------------------------------- | :------------------------------------------------------------------------------------------------------------- |
| **Stream the full firehose** | Access 100% of public posts in real-time with volume streams |
| **Stream all likes** | Full and sampled likes streams in real-time |
| **Advanced filtered streaming** | Powerstream (low-latency keyword filtering) |
| **Semantic embedding operators** | Match posts by meaning (not just keywords) using `embedding:` on Filtered Stream (Enterprise + Embedding tier) |
| **Deep engagement analytics** | Post and media engagement metrics at scale |
| **Account activity events** | Real-time subscriptions for user events (posts, DMs, likes, follows) |
| **Webhook delivery** | Receive filtered stream data via webhooks |
| **Custom rate limits** | Elevated limits tailored to your throughput needs |
| **Dedicated support** | Named account manager and priority issue resolution |
***
## Enterprise-exclusive endpoints
These endpoints are only available with Enterprise access:
Full firehose and language-specific streams for complete real-time coverage.
Stream all likes or sampled likes across the platform.
High-performance filtered streaming with advanced operators.
Post and media analytics for deep engagement insights.
Real-time event subscriptions for user activity.
Filtered stream delivery via webhooks.
***
## All available resources
Enterprise access includes the full set of X API resources:
Search, retrieve, create, and delete posts. Access timelines, threads, and quote posts.
Look up profiles, manage relationships, and access follower data.
Discover live audio conversations and participants.
Send and receive private messages between users.
Create and manage curated lists of accounts.
Access trending topics by location.
***
## API highlights
Request only the data you need. Use `fields` parameters to select specific attributes and `expansions` to include related objects.
```bash theme={null}
curl "https://api.x.com/2/tweets/123?tweet.fields=created_at,public_metrics&expansions=author_id&user.fields=username" \
-H "Authorization: Bearer $TOKEN"
```
[Learn more about fields →](/x-api/fundamentals/fields)
Posts include semantic annotations identifying people, places, products, and topics. Filter streams and searches by topic.
[Learn more about annotations →](/x-api/fundamentals/post-annotations)
Enterprise customers get access to dedicated engagement metrics endpoints for both posts and media, providing deep analytics at scale beyond what standard public metrics offer.
[Learn more about metrics →](/x-api/fundamentals/metrics)
Reconstruct entire conversation threads using `conversation_id`. Track replies across the full thread.
[Learn more about conversation tracking →](/x-api/fundamentals/conversation-id)
Access the edit history of posts, including all previous versions and edit metadata.
[Learn more about edit posts →](/x-api/fundamentals/edit-posts)
***
## Pricing
Enterprise plans are custom-tailored to your organization's needs. Pricing is based on your data volume, endpoint usage, and support requirements.
| Feature | Details |
| :------------------------ | :-------------------------------------------------- |
| **Custom packages** | Tailored to your specific data and throughput needs |
| **Longer-term contracts** | Predictable pricing with committed usage agreements |
| **No post read cap** | Custom or unlimited post read volumes |
| **Dedicated support** | Included with all Enterprise plans |
[Contact sales for pricing](/forms/enterprise-api-interest)
***
## Next steps
Contact our sales team to discuss your needs.
Browse all available endpoints including Enterprise-exclusive ones.
# Getting enterprise access
Source: https://docs.x.com/enterprise-api/getting-started/getting-access
Apply for X Enterprise API access, work with your dedicated account team during onboarding, and get credentials configured for your data volume.
Enterprise access requires an application and onboarding process. Your dedicated account team will help you get set up with credentials and configure your access.
***
## Step 1: Apply for enterprise access
[Fill out the Enterprise interest form](/forms/enterprise-api-interest) with details about your organization and use case.
Our sales team will reach out to understand your data volume, endpoint requirements, and support needs.
Receive a tailored plan with pricing, rate limits, and access levels designed for your use case.
***
## Step 2: Get onboarded
Once your Enterprise plan is in place, your dedicated account manager will help you set up:
Set up your app in the [Developer Console](https://console.x.com) with Enterprise-level access.
Your account manager will help configure rate limits, endpoint access, and any custom settings.
Generate your API keys and tokens for authentication.
***
## Step 3: Save your credentials
You'll receive several credentials depending on your authentication needs:
| Credential | Purpose |
| :------------------------ | :----------------------------------------------------------------------- |
| **API Key & Secret** | Identify your app. Used to generate tokens and sign OAuth 1.0a requests. |
| **Bearer Token** | App-only authentication for reading public data. |
| **Access Token & Secret** | Make requests on behalf of your own account (OAuth 1.0a). |
| **Client ID & Secret** | OAuth 2.0 authentication for user-context requests. |
**Save immediately.** X only displays credentials once. Store them in a password manager or secure vault. If you lose them, regenerate them (which invalidates the old ones).
***
## Which credentials do you need?
Use the **Bearer Token** for simple, read-only access to public data.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Best for: Searching posts, looking up users, reading trends.
Use **OAuth 2.0** (recommended) or **OAuth 1.0a** to act on behalf of users.
OAuth 2.0 offers fine-grained scopes—request only the permissions you need.
Best for: Posting, liking, following, accessing DMs.
[OAuth 2.0 guide →](/resources/fundamentals/authentication/oauth-2-0/overview)
Use your **Access Token & Secret** to make requests as your own account.
These tokens represent the account that owns the app.
Best for: Testing, personal bots, your own automation.
***
## Credential security best practices
Never hardcode credentials in your source code.
Add credential files to `.gitignore`.
Regenerate credentials periodically as a security measure.
Only request the OAuth permissions your app needs.
***
## Next steps
Call the API with your new credentials.
Understand OAuth 1.0a and OAuth 2.0.
# Important Resources
Source: https://docs.x.com/enterprise-api/getting-started/important-resources
Essential resources for X Enterprise API customers, including onboarding guides, account managers, support contacts, status pages, and SDKs.
Bookmark these essential resources for X API development.
***
## Documentation
Complete endpoint documentation with parameters and examples.
Object schemas for posts, users, media, and more.
OAuth 1.0a and OAuth 2.0 implementation guides.
Per-endpoint limits and best practices.
***
## Tools
| Tool | Description |
| :------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ |
| [Developer Console](https://console.x.com) | Manage apps, credentials, and billing |
| [Postman Collection](https://www.postman.com/xapidevelopers/x-api-public-workspace/collection/34902927-2efc5689-99c6-4ab6-8091-996f35c2fd80) | Interactive API testing |
| [Python SDK](/xdks/python/overview) | Official Python library |
| [TypeScript SDK](/xdks/typescript/overview) | Official TypeScript library |
| [OpenAPI Spec](https://api.x.com/2/openapi.json) | Machine-readable API specification |
***
## Learning
Step-by-step guides for common use cases.
Example apps and code samples.
Ideas and inspiration for projects.
Upgrade from v1.1 to v2.
***
## Community and support
Ask questions and share solutions with the community.
FAQs, troubleshooting, and contact options.
Official updates and announcements.
API-specific news and tips.
***
## Stay updated
| Resource | What you'll get |
| :------------------------------------------------------------------- | :----------------------------------- |
| [Changelog](/changelog) | All platform changes and updates |
| [Newsletter](/newsletter) | Monthly roundup of news and features |
| [Forum Announcements](https://devcommunity.x.com/c/announcements/22) | Important platform notices |
| [API Status](/status) | Real-time service availability |
Follow [@XDevelopers](https://x.com/XDevelopers) and turn on notifications to catch breaking changes and new features.
***
## Quick reference
### Response structure
All v2 responses follow this structure:
```json theme={null}
{
"data": { ... }, // Primary object(s)
"includes": { ... }, // Expanded objects (if requested)
"meta": { ... }, // Pagination info
"errors": [ ... ] // Partial errors (if any)
}
```
### Common parameters
| Parameter | Use |
| :----------------- | :--------------------------- |
| `tweet.fields` | Request specific post fields |
| `user.fields` | Request specific user fields |
| `expansions` | Include related objects |
| `max_results` | Limit results per page |
| `pagination_token` | Get next/previous page |
### Authentication methods
| Method | Use case |
| :----------- | :-------------------------------------- |
| Bearer Token | Read-only public data |
| OAuth 2.0 | User actions with fine-grained scopes |
| OAuth 1.0a | User actions (legacy, full permissions) |
[Full authentication guide →](/resources/fundamentals/authentication/overview)
# Make Your First Request
Source: https://docs.x.com/enterprise-api/getting-started/make-your-first-request
Make your first X Enterprise API request, including authentication setup, endpoint selection, sample cURL commands, and response handling tips.
This guide walks you through making your first X API request. You'll need a [developer account with app credentials](/x-api/getting-started/getting-access) before starting.
***
## Quick start with cURL
The fastest way to test the API is with cURL. Let's look up a user:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Replace `$BEARER_TOKEN` with your actual Bearer Token. You'll get a response like:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Step-by-step guide
In the [Developer Console](https://console.x.com), navigate to your app and copy the Bearer Token.
Start with one of these beginner-friendly endpoints:
| Endpoint | What it does |
| :------------------------------------------------ | :--------------------------------- |
| [User lookup](/x-api/users/lookup/introduction) | Get user profile by username or ID |
| [Post lookup](/x-api/posts/lookup/introduction) | Get post by ID |
| [Recent search](/x-api/posts/search/introduction) | Search posts from the last 7 days |
Use cURL, Postman, or your preferred HTTP client:
```bash theme={null}
# Look up a user by username
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Responses are JSON. The primary data is in the `data` field:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Request more data with fields
By default, endpoints return minimal fields. Use the `fields` parameter to request additional data:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers?user.fields=created_at,description,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Response:
```json 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 Platform",
"public_metrics": {
"followers_count": 570842,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
[Learn more about fields →](/x-api/fundamentals/fields)
***
## More examples
```bash theme={null}
curl "https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=from:xdevelopers&tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/tweets?max_results=5" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Using code instead of cURL
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/users/by/username/xdevelopers"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers)
print(response.json())
```
```javascript theme={null}
const bearerToken = "YOUR_BEARER_TOKEN";
const url = "https://api.x.com/2/users/by/username/xdevelopers";
fetch(url, {
headers: { Authorization: `Bearer ${bearerToken}` }
})
.then(res => res.json())
.then(data => console.log(data));
```
For production use, we recommend the official SDKs:
* [Python SDK](/xdks/python/overview)
* [TypeScript SDK](/xdks/typescript/overview)
They handle authentication, pagination, and rate limiting automatically.
***
## Tools for testing
Visual API testing with our collection.
Examples in multiple languages.
Full endpoint documentation.
***
## Troubleshooting
* Check that your Bearer Token is correct
* Ensure the token hasn't been regenerated
* Verify the `Authorization` header format: `Bearer YOUR_TOKEN`
* Your app may not have access to this endpoint
* Some endpoints require user-context authentication (OAuth 1.0a or 2.0)
* Check your app's permissions in the Developer Console
* You've hit a rate limit
* Check the `x-rate-limit-reset` header for when to retry
* Implement exponential backoff in your code
[Full error reference →](/x-api/fundamentals/response-codes-and-errors)
***
## Next steps
Understand OAuth for user-context requests.
Discover what you can build.
Faster development with official libraries.
Ideas for what to create.
# Enterprise API pricing and custom plans
Source: https://docs.x.com/enterprise-api/getting-started/pricing
Enterprise API plans are custom-tailored to your organization's data volume, endpoint usage, and support needs. Contact sales for high-volume pricing.
Enterprise plans are custom-tailored to your organization's needs. Work with a dedicated account team to build a package that matches your data volume, endpoint usage, and support requirements.
***
## How Enterprise pricing works
Pricing is tailored to your specific data volume, endpoint needs, and throughput requirements.
Predictable costs with longer-term agreements and committed usage levels.
Custom or unlimited post read volumes, far beyond the 2 million monthly cap on pay-per-use plans.
A named account manager and priority technical support are included with every Enterprise plan.
***
## What's included
Every Enterprise plan includes access to the full X API plus exclusive Enterprise endpoints:
| Feature | Details |
| :------------------------------- | :-------------------------------------------------------------------------------------------- |
| **All standard endpoints** | Everything available in the pay-per-use X API |
| **Volume streams** | Full firehose and language-specific streams |
| **Likes streams** | Full and sampled likes in real-time |
| **Powerstream** | Advanced filtered streaming |
| **Semantic embedding operators** | `embedding:` operator for semantic matching in Filtered Stream only (requires Embedding tier) |
| **Engagement metrics** | Post and media analytics endpoints |
| **Account Activity** | Real-time user event subscriptions |
| **Stream webhooks** | Filtered stream delivery via webhooks |
| **Custom rate limits** | Elevated limits tailored to your needs |
| **Dedicated support** | Named account manager and priority resolution |
***
## Enterprise vs. pay-per-use
| | Pay-per-use | Enterprise |
| :------------------------------- | :-------------------------- | :----------------------------------------------------------------------- |
| **Pricing model** | Credit-based, pay as you go | Custom contract |
| **Monthly post cap** | 2 million reads | Custom / unlimited |
| **Volume streams** | Not available | Full firehose and language streams |
| **Likes streams** | Not available | Full and sampled likes |
| **Semantic embedding operators** | Not available | `embedding:` operator for Filtered Stream only (requires Embedding tier) |
| **Engagement metrics** | Not available | Post and media analytics |
| **Rate limits** | Standard | Custom / elevated |
| **Support** | Community forum | Dedicated account manager |
| **Commitment** | None | Contract-based |
***
## Monitoring usage
Track your API usage programmatically with the [Usage endpoint](/x-api/usage/introduction):
```bash theme={null}
curl "https://api.x.com/2/usage/tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
This returns daily Post consumption counts, helping you:
* Track consumption against your contract limits
* Generate usage reports for stakeholders
* Identify high-consumption endpoints
* Plan capacity with your account team
***
## Get started
[Apply for Enterprise access](/forms/enterprise-api-interest) and tell us about your use case and data needs.
Our sales team will work with you to build a package that fits your requirements and budget.
Your dedicated account manager will help you set up credentials, configure access, and start building.
***
## Next steps
Contact our sales team to get started.
Monitor usage programmatically.
# Enterprise API
Source: https://docs.x.com/enterprise-api/introduction
Enterprise-grade access to the X firehose, volume streams, full-archive search, and PowerTrack with dedicated technical support and custom pricing.
The X API Enterprise plan provides the highest level of access to X data. Get complete firehose coverage, volume streams, semantic embedding operators for Filtered Stream, dedicated account management, and custom rate limits designed for organizations that depend on X data at scale.
Apply for Enterprise access with a dedicated account team.
Explore all available endpoints, including Enterprise-exclusive ones.
Official Python and TypeScript libraries.
***
## Why Enterprise?
Enterprise access includes everything in the pay-per-use X API plus exclusive high-volume endpoints, dedicated support, and custom packages tailored to your needs.
Stream 100% of public posts in real-time. No sampling, no limits. Get every post as it happens.
Access full-volume and language-specific streams, including English, Japanese, Korean, and Portuguese firehoses.
Get a dedicated account manager, personalized technical support, and priority issue resolution.
Higher rate limits and custom-tailored packages to match your throughput requirements.
Access post and media analytics endpoints for deep engagement insights across large datasets.
Stay compliant with real-time compliance event streams for posts, users, and likes.
Match posts by conceptual meaning — not just keywords — using the `embedding:` operator in Filtered Stream (requires Embedding tier).
***
## Enterprise-exclusive endpoints
These endpoints are only available on Enterprise plans:
Full firehose, language-specific streams, and sampled streams.
Stream all likes or sampled likes in real-time.
High-performance filtered streaming with low latency (keyword operators).
Deep analytics for post and media engagement.
Subscribe to real-time user activity events including posts, DMs, likes, and follows.
Receive filtered stream data via webhooks instead of persistent connections.
***
## What you can build
Enterprise access powers the most demanding use cases on X.
Search, retrieve, and publish posts. Access timelines, threads, and quote posts.
Look up users, manage follows, blocks, and mutes.
Find live audio conversations and their participants.
Send and receive private messages.
Create and manage curated lists of accounts.
Access trending topics by location.
***
## Key features
### Complete real-time coverage
Stream 100% of public posts as they happen. No sampling, no gaps. Enterprise firehose access gives you the complete picture of public conversation on X.
Available streams:
* **All posts** - Every public post in real-time
* **English posts** - All English-language posts
* **Japanese posts** - All Japanese-language posts
* **Korean posts** - All Korean-language posts
* **Portuguese posts** - All Portuguese-language posts
* **Sampled streams** - 1% and 10% random samples
[Learn more about volume streams](/x-api/posts/volume-streams/introduction)
### Rich data objects
Access detailed, structured data for posts, users, media, and more:
* **Posts**: Full text, metrics, entities, annotations, conversation threads
* **Users**: Profiles, follower counts, verification status
* **Media**: Images, videos, GIFs with metadata
* **Polls**: Options and vote counts
Customize responses with [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) to get exactly the data you need.
### Filtered stream
Get posts delivered in real-time as they're published. Enterprise adds higher rule limits and the semantic `embedding:` operator (in Filtered Stream only) to match posts by meaning (not just keywords).
```bash theme={null}
# Add a rule
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $TOKEN" \
-d '{"add": [{"value": "from:xdevelopers"}]}'
# Connect to stream
curl "https://api.x.com/2/tweets/search/stream" \
-H "Authorization: Bearer $TOKEN"
```
[Learn more about filtered stream](/x-api/posts/filtered-stream/introduction)
### Full-archive search
Search the complete history of public posts back to 2006. Build queries with operators for users, keywords, dates, and more.
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?query=AI%20lang:en" \
-H "Authorization: Bearer $TOKEN"
```
### Engagement metrics
Access deep engagement analytics including impressions, likes, reposts, replies, video views, and media-level metrics.
[Learn more about search](/x-api/posts/search/introduction)
***
## Enterprise vs. pay-per-use
| Feature | Pay-per-use | Enterprise |
| :--------------------- | :---------------------- | :-------------------------------------------------------------------- |
| **Post search** | Recent and full-archive | Recent and full-archive |
| **Filtered stream** | Up to 1,000 rules | 5,000+ rules + semantic `embedding:` operators (Filtered Stream only) |
| **Volume streams** | - | Full firehose and language streams |
| **Likes streams** | - | Full and sampled likes |
| **Powerstream** | - | Advanced filtered streaming |
| **Engagement metrics** | - | Post and media analytics |
| **Account Activity** | - | Real-time user event subscriptions |
| **Monthly post cap** | 2 million reads | Custom / unlimited |
| **Rate limits** | Standard | Custom / elevated |
| **Support** | Community forum | Dedicated account manager |
***
## Get started
[Contact our sales team](/forms/enterprise-api-interest) to discuss your needs and get a custom package.
Your dedicated account manager will help you set up credentials and configure your access.
Use the same modern v2 API endpoints plus Enterprise-exclusive endpoints for your integration.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Tools & libraries
Official Python library with async support.
Official TypeScript/JavaScript library.
Interactive API explorer.
[Browse all libraries](/tools-and-libraries)
***
## Support
Enterprise customers get a dedicated point of contact for technical and account support.
Get help from the community and X team.
# Add List member
Source: https://docs.x.com/enterprise-api/lists/add-list-member
post /2/lists/{id}/members
Adds a User to a specific List by its ID.
# Create List
Source: https://docs.x.com/enterprise-api/lists/create-list
post /2/lists
Creates a new List for the authenticated user.
# Delete List
Source: https://docs.x.com/enterprise-api/lists/delete-list
delete /2/lists/{id}
Deletes a specific List owned by the authenticated user by its ID.
# Get List by ID
Source: https://docs.x.com/enterprise-api/lists/get-list-by-id
get /2/lists/{id}
Retrieves details of a specific List by its ID.
# Get List followers
Source: https://docs.x.com/enterprise-api/lists/get-list-followers
get /2/lists/{id}/followers
Retrieves a list of Users who follow a specific List by its ID.
# Get List members
Source: https://docs.x.com/enterprise-api/lists/get-list-members
get /2/lists/{id}/members
Retrieves a list of Users who are members of a specific List by its ID.
# Get List Posts
Source: https://docs.x.com/enterprise-api/lists/get-list-posts
get /2/lists/{id}/tweets
Retrieves a list of Posts associated with a specific List by its ID.
# Integration Guide
Source: https://docs.x.com/enterprise-api/lists/list-lookup/integrate
This guide covers the key concepts you need to integrate the List lookup endpoints into your. Reference for the Enterprise X API tier covering list lookup.
This guide covers the key concepts you need to integrate the List lookup endpoints into your application.
***
## Authentication
List lookup endpoints support multiple authentication methods:
| Method | Best for | Access to private Lists? |
| :----------------------------------------------------------------------------------------------------------------------------- | :------------------ | :----------------------- |
| [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) | Public List data | No |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | User-facing apps | Yes (owned/followed) |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Legacy integrations | Yes (owned/followed) |
### Example request
```bash cURL theme={null}
curl "https://api.x.com/2/lists/84839422?\
list.fields=description,member_count,follower_count,private" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a List by ID
response = client.lists.get(
list_id="84839422",
list_fields=["description", "member_count", "follower_count", "private"]
)
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.lists.get("84839422", {
listFields: ["description", "member_count", "follower_count", "private"],
});
console.log(response.data);
```
***
## Endpoints overview
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------- | :------------------------ |
| GET | [`/2/lists/:id`](/x-api/lists/get-list-by-id) | Get List by ID |
| GET | [`/2/users/:id/owned_lists`](/x-api/users/get-owned-lists) | Get Lists owned by a user |
***
## Fields and expansions
### Default response
```json theme={null}
{
"data": {
"id": "84839422",
"name": "Tech News"
}
}
```
### Available fields
| Field | Description |
| :--------------- | :---------------------- |
| `created_at` | List creation timestamp |
| `description` | List description |
| `follower_count` | Number of followers |
| `member_count` | Number of members |
| `owner_id` | Owner's user ID |
| `private` | Whether List is private |
| Field | Description |
| :------------------ | :-------------------------- |
| `username` | Owner's @handle |
| `name` | Owner's display name |
| `verified` | Owner's verification status |
| `profile_image_url` | Owner's avatar URL |
### Example with expansions
```bash cURL theme={null}
curl "https://api.x.com/2/lists/84839422?\
list.fields=description,member_count,follower_count,owner_id&\
expansions=owner_id&\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get List with owner expansion
response = client.lists.get(
list_id="84839422",
list_fields=["description", "member_count", "follower_count", "owner_id"],
expansions=["owner_id"],
user_fields=["username", "verified"]
)
print(response.data)
print(response.includes) # Contains owner user object
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.lists.get("84839422", {
listFields: ["description", "member_count", "follower_count", "owner_id"],
expansions: ["owner_id"],
userFields: ["username", "verified"],
});
console.log(response.data);
console.log(response.includes); // Contains owner user object
```
### Response with expansion
```json theme={null}
{
"data": {
"id": "84839422",
"name": "Tech News",
"description": "Top tech journalists",
"member_count": 50,
"follower_count": 1250,
"owner_id": "2244994945"
},
"includes": {
"users": [
{
"id": "2244994945",
"username": "XDevelopers",
"verified": true
}
]
}
}
```
Learn more about customizing responses
***
## Pagination
When retrieving owned Lists, results are paginated:
```bash cURL theme={null}
# First request
curl "https://api.x.com/2/users/123/owned_lists?max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
# Subsequent request with pagination token
curl "https://api.x.com/2/users/123/owned_lists?max_results=100&pagination_token=NEXT_TOKEN" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# The SDK handles pagination automatically
all_lists = []
for page in client.lists.get_user_owned_lists(user_id="123", max_results=100):
if page.data:
all_lists.extend(page.data)
print(f"Found {len(all_lists)} lists")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
async function getAllOwnedLists(userId) {
const allLists = [];
// The SDK handles pagination automatically
const paginator = client.lists.getUserOwnedLists(userId, { maxResults: 100 });
for await (const page of paginator) {
if (page.data) {
allLists.push(...page.data);
}
}
return allLists;
}
// Usage
const lists = await getAllOwnedLists("123");
console.log(`Found ${lists.length} lists`);
```
Learn more about pagination
***
## Private Lists
* Private Lists are only visible to the owner
* You must authenticate as the owner to retrieve private List details
* The `private` field indicates whether a List is private
***
## Error handling
| Status | Error | Solution |
| :----- | :---------------- | :-------------------- |
| 400 | Invalid request | Check List ID format |
| 401 | Unauthorized | Verify authentication |
| 403 | Forbidden | List may be private |
| 404 | Not Found | List doesn't exist |
| 429 | Too Many Requests | Wait and retry |
***
## Next steps
Make your first List lookup request
Get Posts from a List
Full endpoint documentation
Working code examples
# List Lookup
Source: https://docs.x.com/enterprise-api/lists/list-lookup/introduction
Retrieve X List details by ID or fetch all Lists owned by a user with the Enterprise List lookup endpoints, including metadata and ownership info.
The List lookup endpoints let you retrieve information about Lists. Look up a specific List by ID or get all Lists owned by a user.
## Overview
Get details for a specific List
Get all Lists owned by a user
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------- | :------------------------ |
| GET | [`/2/lists/:id`](/x-api/lists/get-list-by-id) | Get List by ID |
| GET | [`/2/users/:id/owned_lists`](/x-api/users/get-owned-lists) | Get Lists owned by a user |
***
## Response fields
By default, the response includes `id` and `name`. Request additional fields:
| Field | Description |
| :--------------- | :---------------------- |
| `description` | List description |
| `owner_id` | Owner's user ID |
| `private` | Whether List is private |
| `follower_count` | Number of followers |
| `member_count` | Number of members |
| `created_at` | List creation date |
### Example request
```bash theme={null}
curl "https://api.x.com/2/lists/1234567890?\
list.fields=description,owner_id,member_count,follower_count" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Make your first List lookup request
Key concepts and best practices
Full endpoint documentation
Working code examples
# Overview
Source: https://docs.x.com/enterprise-api/lists/list-lookup/migrate/overview
The v2 List lookup endpoint group will replace the standard v1.1 GET lists/show and GET lists/ownership endpoints. If you have code, apps, or tools that use.
## Comparing X API’s List lookup endpoints
The v2 List lookup endpoint group will replace the standard v1.1 [GET lists/show](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-show) and [GET lists/ownership](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships) endpoints. If you have code, apps, or tools that use one of these versions of the List lookup endpoints, and are considering migrating to the newer X API v2 endpoint, then this set of guides is for you.
The following tables compare the standard v1.1 and X API v2 List endpoints:
**List Lookup by ID**
| | | |
| :----------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- |
| Description | Standard v1.1 | X API v2 |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint path | `/1.1/lists/show.json` | `/2/lists/:id` |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context
App only | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE
App only |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 75 requests per 15 min with OAuth 1.0a
75 requests per 15min with OAuth 2.0
75 requests per 15 min with App only | 75 requests per 15 min with OAuth 1.0a
75 requests per 15 min with OAuth 2.0
75 requests per 15 min with App only |
**User owned List lookup**
| | | |
| :----------------------------------------------------------------- | :------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------- |
| Description | Standard v1.1 | X API v2 |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint path | `/1.1/lists/ownerships.json` | `/2/users/:id/owned_lists` |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context
App only | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE
App only |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 15 requests per 15 min with OAuth 1.0a
15 requests per 15 min with App only | 15 requests per 15 min with OAuth 1.0a
15 requests per 15min with OAuth 2.0
15 requests per 15 min with App only |
To access the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info). When authenticating, you must use keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started](/x-api/getting-started/getting-access) page.
# v1 to v2
Source: https://docs.x.com/enterprise-api/lists/list-lookup/migrate/standard-to-twitter-api-v2
Migrate from standard v1.1 GET lists/show and lists/ownerships endpoints to X API v2 List lookup, comparing authentication, rate limits, and response fields.
### List lookup: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [GET lists/show](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-show) and [GET lists/ownerships](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 List lookup endpoints.
* **Similarities**
* Authentication methods
* Rate limits
* **Differences**
* Endpoint URLs
* App and Project requirements
* Data objects per request limits
* Response data formats
* Request parameters
#### Similarities
**Authentication**
Both endpoint versions support both [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2) and [App only](/resources/fundamentals/authentication#app-only-authentication-and-oauth-2-0-bearer-token). Therefore, if you were previously using one of the standard v1.1 List lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
Depending on your authentication library/package of choice, App only authentication is probably the easiest way to get started and can be set with a simple request header. To learn how to generate an App only Access Token, see [this App only guide](/resources/fundamentals/authentication#using-and-generating-an-app-only-bearer-token).
**Rate limits**
| | |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Standard v1.1** | **X API v2** |
| /1.1/lists/show\.json
75 requests per 15-minute window with OAuth 1.0a User Context
75 requests per 15-minute window with App only | /2/lists/:id
75 requests per 15-minute window with OAuth 1.0a User Context
75 requests per 15-minute window with OAuth 2.0 Authorization Code with PKCE |
| /1.1/lists/ownerships.json
15 requests per 15-minute window with OAuth 1.0a User Context
15 requests per 15-minute window with App only | /2/users/:id/owned\_lists
15 requests per 15-minute window with OAuth 1.0a User Context
15 requests per 15-minute window with OAuth 2.0 Authorization Code with PKCE
15 requests per 15-minute window with App only |
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* GET [https://api.x.com/1.1/lists/show.json](https://api.x.com/1.1/lists/show.json)
(Lookup a specified List)
* GET [https://api.x.com/1.1/lists/ownerships.json](https://api.x.com/1.1/lists/ownerships.json)
(Lookup specified user owned Lists)
* X API v2 endpoint:
* GET [https://api.x.com/2/lists/:id](https://api.x.com/2/lists/:id)
(Lookup a specified List)
* GET [https://api.x.com/2/users/:id/owned\_lists](https://api.x.com/2/users/:id/owned_lists)
(Lookup specified user owned Lists)
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps associated with a project.
**Data objects per request limits**
The standard v1.1 /lists/ownerships endpoint allows you to return up to 1000 Lists per request. The new v2 endpoints allow you to return up to 100 Lists per request. By default, 100 user objects will be returned, to change the number of results you will need to pass a query parameter max\_results= with a number between 1-100; you can then pass the next\_token returned in the response payload to the pagination\_token query parameter in your next request.
**Response data format**
One of the biggest differences between standard v1.1 and X API v2 endpoint versions is how you select which fields return in your payload.
For the standard endpoints, you receive many of the response fields by default and then have the option to use parameters to identify which additional fields or sets of fields should return in the payload.
The X API v2 version only delivers the List id and name fields by default. To request any additional fields or objects, you will need to use the [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) parameters. Any List fields that you request from this endpoint will return in the primary List object. Any expanded Post or user object and fields will return an includes object within your response. You can then match any expanded objects back to the List object by matching the IDs located in both the user and the expanded Post object.
Here are examples of possible List fields and expansions:
* created\_at
* follower\_count
* member\_count
* owner\_id
* description
* private
| | |
| :------------------------ | :------------ |
| **Endpoint** | **Expansion** |
| /2/lists/:id | owner\_id |
| /2/users/:id/owned\_lists | owner\_id |
We encourage you to read more about these new parameters in their respective guides, or by reading our guide on [how to use fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions).
We have also put together a [data format migration guide](/x-api/migrate/data-format-migration) that can help you map standard v1.1 fields to the newer v2 fields. This guide will also provide you with the specific expansion and field parameter that you will need to pass with your v2 request to return specific fields.
In addition to the changes in how you request certain fields, X API v2 is also introducing new JSON designs for the objects returned by the APIs, including [Post](/x-api/fundamentals/data-dictionary/reference#tweet) and [user](/x-api/fundamentals/data-dictionary/reference#user) objects.
* At the JSON root level, the standard endpoints return Post objects in a statuses array, while X API v2 returns a data array.
* Instead of referring to Retweeted and Quoted "statuses", X API v2 JSON refers to Retweeted and Quoted Tweets. Many legacy and deprecated fields, such as contributors and user.translator\_type are being removed.
* Instead of using both favorites (in Post object) and favourites (in user object), X API v2 uses the term like.
* X is adopting the convention that JSON values with no value (for example, null) are not written to the payload. Post and user attributes are only included if they have non-null values.
**Request parameters**
The following standard v1.1 request parameters have equivalents in X API v2:
**List lookup by ID**
| | |
| :------------------ | :----------------------------------------- |
| **Standard v1.1** | **X API v2** |
| list\_id | id |
| slug | No equivalent |
| owner\_screen\_name | No equivalent |
| owner\_id | Requested with expansions/fields parameter |
**User owned List lookup**
| | |
| :---------------- | :---------------- |
| **Standard v1.1** | **X API v2** |
| user\_id | id |
| screen\_name | No equivalent |
| count | max\_results |
| cursor | pagination\_token |
# Quickstart
Source: https://docs.x.com/enterprise-api/lists/list-lookup/quickstart
This guide walks you through looking up List information using the List lookup endpoints. Reference for the Enterprise X API tier covering list lookup.
This guide walks you through looking up List information using the List lookup endpoints.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
## Get a List by ID
Retrieve details for a specific List:
```bash cURL theme={null}
curl "https://api.x.com/2/lists/1234567890?\
list.fields=description,owner_id,member_count,follower_count,private,created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a List by ID
response = client.lists.get(
"1234567890",
list_fields=["description", "owner_id", "member_count", "follower_count", "private", "created_at"]
)
print(f"List: {response.data.name}")
print(f"Members: {response.data.member_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get a List by ID
const response = await client.lists.get("1234567890", {
listFields: ["description", "owner_id", "member_count", "follower_count", "private", "created_at"],
});
console.log(`List: ${response.data?.name}`);
console.log(`Members: ${response.data?.member_count}`);
```
### Response
```json theme={null}
{
"data": {
"id": "1234567890",
"name": "Tech News",
"description": "Top tech journalists and publications",
"owner_id": "2244994945",
"private": false,
"member_count": 50,
"follower_count": 1250,
"created_at": "2023-01-15T10:00:00.000Z"
}
}
```
***
## Get Lists owned by a user
Retrieve all Lists owned by a specific user:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/owned_lists?\
list.fields=description,member_count,follower_count&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get Lists owned by a user with pagination
for page in client.lists.get_owned_lists(
"2244994945",
list_fields=["description", "member_count", "follower_count"],
max_results=100
):
for lst in page.data:
print(f"{lst.name} - {lst.member_count} members")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get Lists owned by a user with pagination
const paginator = client.lists.getOwnedLists("2244994945", {
listFields: ["description", "member_count", "follower_count"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((lst) => {
console.log(`${lst.name} - ${lst.member_count} members`);
});
}
```
### Response
```json theme={null}
{
"data": [
{
"id": "1234567890",
"name": "Tech News",
"description": "Top tech journalists",
"member_count": 50,
"follower_count": 1250
},
{
"id": "9876543210",
"name": "Developer Tools",
"description": "Useful tools for developers",
"member_count": 25,
"follower_count": 500
}
],
"meta": {
"result_count": 2
}
}
```
***
## Include owner information
Expand the owner's user data:
```bash cURL theme={null}
curl "https://api.x.com/2/lists/1234567890?\
list.fields=description,owner_id&\
expansions=owner_id&\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get List with owner info
response = client.lists.get(
"1234567890",
list_fields=["description", "owner_id"],
expansions=["owner_id"],
user_fields=["username", "verified"]
)
print(f"List: {response.data.name}")
# Owner info is in response.includes.users
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get List with owner info
const response = await client.lists.get("1234567890", {
listFields: ["description", "owner_id"],
expansions: ["owner_id"],
userFields: ["username", "verified"],
});
console.log(`List: ${response.data?.name}`);
// Owner info is in response.includes?.users
```
### Response with expansion
```json theme={null}
{
"data": {
"id": "1234567890",
"name": "Tech News",
"description": "Top tech journalists",
"owner_id": "2244994945"
},
"includes": {
"users": [
{
"id": "2244994945",
"username": "XDevelopers",
"verified": true
}
]
}
}
```
***
## Available fields
| Field | Description |
| :--------------- | :---------------------- |
| `description` | List description |
| `owner_id` | Owner's user ID |
| `private` | Whether List is private |
| `member_count` | Number of members |
| `follower_count` | Number of followers |
| `created_at` | List creation date |
***
## Next steps
Get Posts from a List
Get List members
Create and update Lists
Full endpoint documentation
# Integration guide
Source: https://docs.x.com/enterprise-api/lists/list-members/integrate
This page covers tools and key concepts for integrating the List members endpoints. Reference for the Enterprise X API tier covering list members.
This page covers tools and key concepts for integrating the List members endpoints.
## Helpful tools
Before we dive into some key concepts that will help you integrate this endpoint, we recommend that you become familiar with:
### Postman
Postman is a great tool that you can use to test out an endpoint. Each Postman request includes every path and body parameter to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our ["Using Postman"](/tutorials/postman-getting-started) page.
### Code samples
Are you interested in getting set up with this endpoint with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [Github page](https://github.com/xdevplatform/Twitter-API-v2-sample-code).
### Third-party libraries
Take advantage of one of our communities' [third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the proper version tag.
***
## Key concepts
### Authentication
All X API v2 endpoints require you to authenticate your requests with a set of credentials, also known as keys and tokens. You can use either OAuth 1.0a User Context, OAuth 2.0 Authorization Code with PKCE, or App only to authenticate your requests for the Lists **lookup** endpoints. However, you must authenticate with OAuth 1.0a User Context or OAuth 2.0 for the **manage** Lists endpoints.
[OAuth 1.0a User Context](/resources/fundamentals/authentication), which means that you must use a set of API Keys and user Access Tokens to make a successful request. The access tokens must be associated with the user that you are making the request on behalf of. If you would like to generate a set of Access Tokens for another user, they must authorize your App using the [3-legged OAuth flow](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow).
Please note that OAuth 1.0a can be difficult to use. If you are not familiar with this authentication method, we recommend that you use a [library](/tools-and-libraries), use a tool like Postman, or use either OAuth 2.0 or App only to authenticate your requests.
[OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) allows for greater control over an application's scope, and authorization flows across multiple devices. OAuth 2.0 allows you to pick specific fine-grained scopes which give you specific permissions on behalf of a user.
To enable OAuth 2.0 in your App, you must enable it in your App's authentication settings found in the App settings section of the Developer Console.
[App only](/resources/fundamentals/authentication#oauth-2-0) just requires that you pass an [App only Access Token](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only) with your request. You can either generate an App only Access Token directly within a developer App, or generate one using the [POST oauth2/token](/resources/fundamentals/authentication#post-oauth2-token) endpoint.
### Developer Console, Projects, and developer Apps
To retrieve a set of authentication credentials that will work with the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info), set up a [Project](/resources/fundamentals/developer-apps) within that account, and created a [developer App](/resources/fundamentals/developer-apps) within that Project. You can then find your keys and tokens within your developer App.
### Rate limits
Every day, many thousands of developers make requests to the X API. To help manage the sheer volume of these requests, [rate limits](/x-api/fundamentals/rate-limits) are placed on each endpoint that limits the number of requests you can make on behalf of your app or on behalf of an authenticated user.
Lookup (GET) endpoints are rate limited at both the App-level and the user-level; while manage (POST/DELETE) endpoints are limited at the user-level. The app rate limit means that you, the developer, can only make a certain number of requests to this endpoint over a given period of time from any given App (assumed by using either the API Key and API Secret Key, or the App only Access Token). The user rate limit means that the authenticated user that you are making the request on behalf of can only perform a List lookup a certain number of times across any developer App.
The chart below shows the rate limits for each endpoint.
| Endpoint | HTTP method | Rate limit |
| :----------------------------- | :---------- | :-------------------------- |
| /2/lists/:id/members | GET | 900 requests per 15 minutes |
| /2/users/:id/list\_memberships | GET | 75 requests per 15 minutes |
| /2/lists/:id/members | POST | 300 requests per 15 minutes |
| /2/lists/:id/members/:user\_id | DELETE | 300 requests per 15 minutes |
### Fields and expansions
The X API v2 GET endpoint allows users to select exactly which data they want to return from the API using a set of tools called `fields` and `expansions`. The `expansions` parameter allows you to expand objects referenced in the payload. For example, looking up List members allows you to pull the following [expansions](/x-api/fundamentals/expansions):
* `pinned_tweet_id`
The `fields` parameter allows you to select exactly which [fields](/x-api/fundamentals/fields) within the different data objects you would like to receive. List members lookup delivers user objects primarily. By default, the user object returns id, name, and username fields. To receive additional fields such as `user.created_at` or `user.description`, you will have to specifically request those using a user.fields parameter.
We've added a guide on using [fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions).
The chart below shows the field and expansions available for each lookup endpoint:
| Endpoint | Fields | Expansions |
| :----------------------------- | :---------------------------- | :---------------- |
| /2/lists/:id/members | `user.fields`, `tweet.fields` | `pinned_tweet_id` |
| /2/users/:id/list\_memberships | `list.fields`, `user.fields` | `owner_id` |
### Pagination
Looking up membership/members can return a lot of data. To ensure we are returning consistent, high-performing results at any given time, we use pagination. Pagination is a feature in X API v2 endpoints that return more results than can be returned in a single response. When that happens, the data is returned in a series of 'pages'. Learn more about how to [paginate through results.](/x-api/fundamentals/pagination)
# List Members
Source: https://docs.x.com/enterprise-api/lists/list-members/introduction
The List Members endpoints let you view List members, add members to your Lists, and remove. Reference for the Enterprise X API tier covering list members.
The List Members endpoints let you view List members, add members to your Lists, and remove them. You can also see which Lists a user is a member of.
## Overview
Get all members of a List
Add a user to your List
Remove a user from your List
See Lists a user is on
***
## Endpoints
### List members lookup
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------------- | :--------------------- |
| GET | [`/2/lists/:id/members`](/x-api/lists/get-list-members) | Get members of a List |
| GET | [`/2/users/:id/list_memberships`](/x-api/users/get-list-memberships) | Get Lists a user is on |
### Manage List members
| Method | Endpoint | Description |
| :----- | :----------------------------------------------------------------- | :-------------- |
| POST | [`/2/lists/:id/members`](/x-api/lists/add-list-member) | Add a member |
| DELETE | [`/2/lists/:id/members/:user_id`](/x-api/lists/remove-list-member) | Remove a member |
***
## Example: Get List members
```bash theme={null}
curl "https://api.x.com/2/lists/1234567890/members?\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example: Add a member
```bash theme={null}
curl -X POST "https://api.x.com/2/lists/1234567890/members" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"user_id": "9876543210"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Get members of a List
Add and remove members
Key concepts and best practices
Full endpoint documentation
# List members lookup
Source: https://docs.x.com/enterprise-api/lists/list-members/migrate/list-members-lookup-standard-to-twitter-api-v2
If you have been working with the standard v1.1 GET lists/members and GET lists/memberships. Reference for the Enterprise X API tier covering migrate.
### List members lookup: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [GET lists/members](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-members) and [GET lists/memberships](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 List member endpoints.
* **Similarities**
* Authentication methods
* **Differences**
* Endpoint URLs
* Rate limits
* App and Project requirements
* Data objects per request limits
* Response data formats
* Request parameters
#### Similarities
**Authentication**
Both endpoint versions support both [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2) and [App only](/resources/fundamentals/authentication#oauth-2-0). Therefore, if you were previously using one of the standard v1.1 List members endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
Depending on your authentication library/package of choice, App only authentication is probably the easiest way to get started and can be set with a simple request header. To learn how to generate an App only Access Token, see [this App only guide](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only).
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* GET [https://api.x.com/1.1/lists/members.json](https://api.x.com/1.1/lists/members.json)
(Lookup members of a specified List)
* GET [https://api.x.com/1.1/lists/memberships.json](https://api.x.com/1.1/lists/memberships.json)
(Lookup Lists a user is a member of)
* X API v2 endpoint:
* GET [https://api.x.com/2/lists/:id/members](https://api.x.com/2/lists/:id/members)
(Lookup members of a specified List)
* GET [https://api.x.com/2/users/:id/list\_memberships](https://api.x.com/2/users/:id/list_memberships)
(Lookup Lists a user is a member of)
**Rate limits**
| | |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Standard v1.1** | **X API v2** |
| /1.1/lists/members.json
900 requests per 15-minute window with OAuth 1.0a User Context
15 requests per 15-minute window with App only | /2/lists/:id/members
900 requests per 15-minute window with OAuth 1.0a User Context
900 requests per 15-minute window with OAuth 2.0 Authorization Code with PKCE
900 requests per 15-minute window with App only |
| /1.1/lists/memberships.json
15 requests per 15-minute window with OAuth 1.0a User Context
15 requests per 15-minute window with App only | /2/users/:id/list\_memberships
15 requests per 15-minute window with OAuth 1.0a User Context
15 requests per 15-minute window with OAuth 2.0 Authorization Code with PKCE
15 requests per 15-minute window with App only |
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps associated with a project.
**Data objects per request limits**
The standard v1.1 /1.1/lists/members endpoint allows you to return up to 5000 users per request. The new v2 endpoints allow you to return up to 100 users per request. By default, 100 user objects will be returned, to change the number of results you will need to pass a query parameter max\_results= with a number between 1-100; you can then pass the next\_token returned in the response payload to the pagination\_token query parameter in your next request.
Additionally, the endpoint /1.1/lists/memberships, allow you to return up to 1000 Lists per request. With the v2 replacement, the endpoint allows up to 100 Lists per request. By default 100 Lists objects are returned, use the query parameters max\_results= and pagination\_token in the same fashion as /1.1/lists/members to change the number of results.
**Response data format**
One of the biggest differences between standard v1.1 and X API v2 endpoint versions is how you select which fields return in your payload.
For the standard endpoints, you receive many of the response fields by default and then have the option to use parameters to identify which additional fields or sets of fields should return in the payload.
The X API v2 version /users/:id/list\_memberships will deliver the List id and name fields by default. To request any additional fields or objects, you will need to use the [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) parameters. Any List fields that you request from this endpoint will return in the primary List object. Any expanded object and fields will return an includes object within your response. You can then match any expanded objects back to the primary List object by matching the IDs located in both the primary and the expanded object.
Here are examples of possible List fields and expansions:
* created\_at
* follower\_count
* member\_count
* owner\_id
* description
* private
| | |
| :----------------------------- | :---------------- |
| **Endpoint** | **Expansion** |
| /2/lists/:id/members | pinned\_tweet\_id |
| /2/users/:id/list\_memberships | owner\_id |
We encourage you to read more about these new parameters in their respective guides, or by reading our guide on [how to use fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions).
We have also put together a [data format migration guide](/x-api/migrate/data-format-migration) that can help you map standard v1.1 fields to the newer v2 fields. This guide will also provide you with the specific expansion and field parameter that you will need to pass with your v2 request to return specific fields.
In addition to the changes in how you request certain fields, X API v2 is also introducing new JSON designs for the objects returned by the APIs, including [Post](/x-api/fundamentals/data-dictionary/reference#tweet) and [user](/x-api/fundamentals/data-dictionary/reference#user) objects.
* At the JSON root level, the standard endpoints return Post objects in a statuses array, while X API v2 returns a data array.
* Instead of referring to Retweeted and Quoted "statuses", X API v2 JSON refers to Retweeted and Quoted Tweets. Many legacy and deprecated fields, such as contributors and user.translator\_type are being removed.
* Instead of using both favorites (in Post object) and favourites (in user object), X API v2 uses the term like.
* X is adopting the convention that JSON values with no value (for example, null) are not written to the payload. Post and user attributes are only included if they have non-null values.
**Request parameters**
The following standard v1.1 request parameters have equivalents in X API v2:
**List members lookup**
| | |
| :------------------ | :---------------- |
| **Standard v1.1** | **X API v2** |
| list\_id | id |
| slug | No equivalent |
| owner\_screen\_name | No equivalent |
| owner\_id | No equivalent |
| count | max\_results |
| cursor | pagination\_token |
| include\_entities | No equivalent |
| skip\_status | No equivalent |
**List membership lookup**
| | |
| :---------------- | :---------------- |
| **Standard v1.1** | **X API v2** |
| user\_id | id |
| screen\_name | No equivalent |
| count | max\_results |
| cursor | pagination\_token |
# Manage list members
Source: https://docs.x.com/enterprise-api/lists/list-members/migrate/manage-list-members-standard-to-twitter-api-v2
Migrate the standard v1.1 POST lists/members create and destroy endpoints to X API v2 for adding and removing List members with OAuth 1.0a user context.
### Manage List members: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [POST lists/members/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-members-create) and [POST lists/members/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-members-destroy) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 manage List members endpoints.
* **Similarities**
* Authentication
* **Differences**
* Endpoint URLs
* App and Project requirements
* HTTP methods
* Rate limits
* Request parameters
#### Similarities
**Authentication**
Both endpoint versions support [OAuth 1.0a User Context](https://developer.x.com/content/developer-twitter/resources/fundamentals/authentication). Therefore, if you were previously using one of the standard v1.1 manage List member endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* POST [https://api.x.com/1.1/lists/members/create.json](https://api.x.com/1.1/lists/members/create.json)
(Adds a member to a specified List)
* POST [https://api.x.com/1.1/lists/members/destroy.json](https://api.x.com/1.1/lists/members/destroy.json)
(Removes a member from a specified List)
* X API v2 endpoint:
* POST [https://api.x.com/2/lists/:id/members](https://api.x.com/2/lists/:id/members)
(Adds a member to a specified List)
* DELETE [https://api.x.com/2/lists/:id/members/:user\_id](https://api.x.com/2/lists/:id/members/:user_id)
(Removes a member from a specified List)
**Rate limits**
| **Standard v1.1** | **X API v2** |
| :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| /1.1/lists/members/create.json
none | /2/lists/:id/members
300 requests per 15-minute window with OAuth 1.0a User Context
300 requests per 15-minute window with OAuth 2.0 Authorization Code with PKCE |
| /1.1/lists/members/destroy.json
none | /2/lists/:id/members/:user\_id
300 requests per 15-minute window with OAuth 1.0a User Context
300 requests per 15-minute window with OAuth 2.0 Authorization Code with PKCE |
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps related to a project.
**Request parameters**
The following standard v1.1 request parameters have equivalents in X API v2:
| **Standard v1.1** | **X API v2** |
| :------------------ | :------------ |
| list\_id | id |
| slug | No equivalent |
| screen\_name | No equivalent |
| owner\_screen\_name | No equivalent |
| owner\_id | No equivalent |
# Overview
Source: https://docs.x.com/enterprise-api/lists/list-members/migrate/overview
The v2 List members endpoint group will replace the standard v1.1 GET lists/members, GET lists/memberships, POST lists/members/create and POST.
## Comparing X API’s List members endpoints
The v2 List members endpoint group will replace the standard v1.1 [GET lists/members](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-members), [GET lists/memberships](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships), [POST lists/members/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-members-create) and [POST lists/members/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-members-destroy) endpoints. If you have code, apps, or tools that use one of these versions of the List member endpoints, and are considering migrating to the newer X API v2 endpoint, then this set of guides is for you.
### List members lookup
The v2 List members lookup endpoints will replace the standard [GET lists/members](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-members), [GET lists/memberships](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships), endpoints.
The following tables compare the standard v1.1 and X API v2 List endpoints:
**List member Lookup**
| | | |
| :----------------------------------------------------------------- | :------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
| Description | Standard v1.1 | X API v2 |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint path | `/1.1/lists/members.json` | `/2/lists/:id/members` |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context
App only | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE
App only |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 900 requests per 15 min with OAuth 1.0a
75 requests per 15min with App only | 900 requests per 15 min with OAuth 1.0a
900 requests per 15 min with OAuth 2.0
900 requests per 15 min with App only |
**List membership lookup**
| | | |
| :----------------------------------------------------------------- | :------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------- |
| Description | Standard v1.1 | X API v2 |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint path | `/1.1/lists/memberships.json` | `/2/users/:id/list_memberships` |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context
App only | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE
App only |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 75 requests per 15 min with OAuth 1.0a
75 requests per 15min with App only | 75 requests per 15 min with OAuth 1.0a
75 requests per 15 min with OAuth 2.0
75 requests per 15min with App only |
### Manage List members
The v2 manage List members endpoints will replace the standard [POST lists/members/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-members-create), [POST lists/members/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-members-destroy) endpoints.
The following tables compare the standard v1.1 and X API v2 List endpoints:
**Add member**
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------- | :------------------------------------------------------------------------ |
| HTTP methods supported | POST | POST |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/lists/members/create.json | /2/lists/:id/members |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | None | 300 requests per 15 min (per user) |
**Remove member**
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------- | :------------------------------------------------------------------------ |
| HTTP methods supported | POST | DELETE |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/lists/members/destroy.json | /2/lists/:id/:user\_id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | None | 300 requests per 15 min (per user) |
To access the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info). When authenticating, you must use keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started](/x-api/getting-started/getting-access) page.
# List Members Lookup
Source: https://docs.x.com/enterprise-api/lists/list-members/quickstart/list-members-lookup
Step-by-step quickstart for retrieving the members of an X List using the Enterprise tier List members lookup endpoint, with example requests.
This guide walks you through retrieving members of a List.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
## Get List members
You can find the List ID in the URL when viewing a List:
```
https://x.com/i/lists/84839422
└── This is the List ID
```
```bash cURL theme={null}
curl "https://api.x.com/2/lists/84839422/members?\
user.fields=created_at,username,verified&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get List members with pagination
for page in client.lists.get_members(
"84839422",
user_fields=["created_at", "username", "verified"],
max_results=100
):
for user in page.data:
print(f"{user.username} - Joined: {user.created_at}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get List members with pagination
const paginator = client.lists.getMembers("84839422", {
userFields: ["created_at", "username", "verified"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Joined: ${user.created_at}`);
});
}
```
```json theme={null}
{
"data": [
{
"id": "1319036828964454402",
"name": "Birdwatch",
"username": "birdwatch",
"created_at": "2020-10-21T22:04:47.000Z",
"verified": true
},
{
"id": "1065249714214457345",
"name": "Spaces",
"username": "TwitterSpaces",
"created_at": "2018-11-21T14:24:58.000Z",
"verified": true
}
],
"meta": {
"result_count": 2,
"next_token": "5349804505549807616"
}
}
```
***
## Include additional data
Use expansions to get related data like pinned Posts:
```bash cURL theme={null}
curl "https://api.x.com/2/lists/84839422/members?\
user.fields=created_at&\
expansions=pinned_tweet_id&\
tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get List members with expansions
for page in client.lists.get_members(
"84839422",
user_fields=["created_at"],
expansions=["pinned_tweet_id"],
tweet_fields=["created_at"]
):
for user in page.data:
print(f"{user.username}")
# Pinned Posts are in page.includes.tweets
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get List members with expansions
const paginator = client.lists.getMembers("84839422", {
userFields: ["created_at"],
expansions: ["pinned_tweet_id"],
tweetFields: ["created_at"],
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(user.username);
});
// Pinned Posts are in page.includes?.tweets
}
```
***
## Next steps
Add and remove members
Get List details
Full endpoint documentation
# Manage List Members
Source: https://docs.x.com/enterprise-api/lists/list-members/quickstart/manage-list-members
This guide walks you through adding and removing members from a List. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through adding and removing members from a List.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
* A List that you own
***
## Add a member to a List
You need the ID of your List and the user ID of the person you want to add. Find user IDs using the [user lookup endpoint](/x-api/users/lookup/introduction).
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/lists/1441162269824405510/members" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"user_id": "2244994945"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Add a member to a List
response = client.lists.add_member(
list_id="1441162269824405510",
user_id="2244994945"
)
print(f"Is member: {response.data.is_member}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Add a member to a List
const response = await client.lists.addMember("1441162269824405510", {
userId: "2244994945",
});
console.log(`Is member: ${response.data?.is_member}`);
```
```json theme={null}
{
"data": {
"is_member": true
}
}
```
***
## Remove a member from a List
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/lists/1441162269824405510/members/2244994945" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Remove a member from a List
response = client.lists.remove_member(
list_id="1441162269824405510",
user_id="2244994945"
)
print(f"Is member: {response.data.is_member}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Remove a member from a List
const response = await client.lists.removeMember(
"1441162269824405510",
"2244994945"
);
console.log(`Is member: ${response.data?.is_member}`);
```
**Response:**
```json theme={null}
{
"data": {
"is_member": false
}
}
```
***
## Important notes
* You can only manage members of Lists you own
* Adding a user to a List does not require their permission
* Users can see which public Lists they've been added to
***
## Next steps
Get List members
Create and update Lists
Full endpoint documentation
# List Members Overview
Source: https://docs.x.com/enterprise-api/lists/list-members/quickstart/overview
The List members endpoints let you look up members of a List and manage List membership. Reference for the Enterprise X API tier covering quickstart.
The List members endpoints let you look up members of a List and manage List membership.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token (for lookups)
* User Access Token (for managing members)
***
## Available endpoints
Get members of a List
Add and remove members
***
## Authentication
| Operation | Authentication |
| :----------------- | :------------------------------------------ |
| Look up members | Bearer Token, OAuth 1.0a, or OAuth 2.0 PKCE |
| Add/remove members | OAuth 1.0a or OAuth 2.0 PKCE |
***
## Quick example
```bash cURL theme={null}
# Get List members
curl "https://api.x.com/2/lists/84839422/members" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get List members
for page in client.lists.get_members("84839422"):
for user in page.data:
print(f"{user.username}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get List members
const paginator = client.lists.getMembers("84839422");
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(user.username);
});
}
```
***
## Next steps
Get List details
Get Posts from a List
# Integration guide
Source: https://docs.x.com/enterprise-api/lists/list-tweets/integrate
This page covers tools and key concepts for integrating the List Posts lookup endpoint. Reference for the Enterprise X API tier covering list tweets.
This page covers tools and key concepts for integrating the List Posts lookup endpoint.
## Helpful tools
Before we dive into some key concepts that will help you integrate this endpoint, we recommend that you become familiar with:
### Postman
Postman is a great tool that you can use to test out an endpoint. Each Postman request includes every path and body parameter to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our ["Using Postman"](/tutorials/postman-getting-started) page.
### Code samples
Are you interested in getting set up with this endpoint with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [Github page](https://github.com/xdevplatform/Twitter-API-v2-sample-code).
### Third-party libraries
Take advantage of one of our communities' [third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the proper version tag.
***
## Key concepts
### Authentication
All X API v2 endpoints require you to authenticate your requests with a set of credentials, also known as keys and tokens. You can use either OAuth 1.0a User Context, App only, or OAuth 2.0 Authorization Code with PKCE to authenticate your requests to this endpoint.
[OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2), which means that you must use a set of API Keys and user Access Tokens to make a successful request. The access tokens must be associated with the user that you are making the request on behalf of. If you would like to generate a set of Access Tokens for another user, they must authorize your App using the [3-legged OAuth flow](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow).
Please note that OAuth 1.0a can be difficult to use. If you are not familiar with this authentication method, we recommend that you use a [library](/tools-and-libraries), use a tool like Postman, or use either OAuth 2.0 or App only to authenticate your requests.
[OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) allows for greater control over an application's scope, and authorization flows across multiple devices. OAuth 2.0 allows you to pick specific fine-grained scopes which give you specific permissions on behalf of a user.
To enable OAuth 2.0 in your App, you must enable it in your App's authentication settings found in the App settings section of the Developer Console.
[App only](/resources/fundamentals/authentication#app-only-authentication-and-oauth-2-0-bearer-token) just requires that you pass an [App only Access Token](/resources/fundamentals/authentication#app-only-authentication-and-oauth-2-0-bearer-token) with your request. You can either generate an App only Access Token directly within a developer App, or generate one using the [POST oauth2/token](/resources/fundamentals/authentication#post-oauth2-token) endpoint.
### Developer Console, Projects, and developer Apps
To retrieve a set of authentication credentials that will work with the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info), set up a [Project](/resources/fundamentals/developer-apps) within that account, and created a [developer App](/resources/fundamentals/developer-apps) within that Project. You can then find your keys and tokens within your developer App.
### Rate limits
Every day, many thousands of developers make requests to the X API. To help manage the sheer volume of these requests, [rate limits](https://developer.x.com/x-api/fundamentals/rate-limits) are placed on each endpoint that limits the number of requests you can make on behalf of your app or on behalf of an authenticated user.
This endpoint is rate limited at both the App-level and the user-level. The app rate limit means that you, the developer, can only make a certain number of requests to this endpoint over a given period of time from any given App (assumed by using either the API Key and API Secret Key, or the Bearer Token). The user rate limit means that the authenticated user that you are making the request on behalf of can only perform a List Post lookup a certain number of times across any developer App.
The chart below shows the rate limits for each endpoint.
| Endpoint | HTTP method | Rate limit |
| :------------------ | :---------- | :-------------------------- |
| /2/lists/:id/tweets | GET | 900 requests per 15 minutes |
### Fields and expansions
The X API v2 GET endpoint allows users to select exactly which data they want to return from the API using a set of tools called `fields` and `expansions`. The `expansions` parameter allows you to expand objects referenced in the payload. For example, looking up List Posts allows you to pull the following [expansions](/x-api/fundamentals/expansions):
* `author_id`
The `fields` parameter allows you to select exactly which [fields](/x-api/fundamentals/fields) within the different data objects you would like to receive. This endpoint delivers Post objects primarily. By default, the Post object returns the `id`, and `text` fields. To receive additional fields such as `tweet.created_at` or `tweet.lang`, you will have to specifically request those using a fields parameter.
We've added a guide on using [fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions) together to our [X API v2 data dictionary](/x-api/fundamentals/data-dictionary).
The chart below shows the field and expansions available for the lookup endpoint:
| Endpoint | Fields | Expansions |
| :------------------ | :---------------------------- | :---------- |
| /2/lists/:id/tweets | `tweet.fields`, `user.fields` | `author_id` |
### Pagination
Looking up List Posts can return a lot of data. To ensure we are returning consistent, high-performing results at any given time, we use pagination. Pagination is a feature in X API v2 endpoints that return more results than can be returned in a single response. When that happens, the data is returned in a series of 'pages'. Learn more about how to [paginate through results.](/x-api/fundamentals/pagination)
# List Posts
Source: https://docs.x.com/enterprise-api/lists/list-tweets/introduction
The List Posts endpoint lets you retrieve Posts from a List's timeline. Reference for the Enterprise X API tier covering list tweets.
The List Posts endpoint lets you retrieve Posts from a List's timeline. Get the latest Posts from all members of a List.
## Overview
Get Posts from List members
Access your curated content feeds
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------- | :-------------------- |
| GET | [`/2/lists/:id/tweets`](/x-api/lists/get-list-posts) | Get Posts from a List |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/lists/1234567890/tweets?\
tweet.fields=created_at,author_id,public_metrics&\
expansions=author_id&\
user.fields=username&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Get Posts from a List
Key concepts and best practices
Get List details
Full endpoint documentation
# Overview
Source: https://docs.x.com/enterprise-api/lists/list-tweets/migrate/overview
The v2 List Posts lookup endpoint will replace the standard v1.1 GET lists/statuses. If you have code, apps, or tools that use this version of the endpoint.
## Comparing X API’s List Posts lookup endpoints
The v2 List Posts lookup endpoint will replace the standard v1.1 [GET lists/statuses](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-statuses). If you have code, apps, or tools that use this version of the endpoint, and are considering migrating to the newer X API v2 endpoint, then this set of guides is for you.
The following tables compare the standard v1.1 and X API v2 List endpoints:
**List Lookup by ID**
| | | |
| :----------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
| Description | Standard v1.1 | X API v2 |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint path | `/1.1/lists/statuses.json` | `/2/lists/:id/tweets` |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context
App only | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE
App only |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 900 requests per 15 min with OAuth 1.0a
900 requests per 15min with App only | 900 requests per 15 min with OAuth 1.0a
900 requests per 15 min with OAuth 2.0
900 requests per 15 min with App only |
To access the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info). When authenticating, you must use keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started](/x-api/getting-started/getting-access) page.
# v1 to v2
Source: https://docs.x.com/enterprise-api/lists/list-tweets/migrate/standard-to-twitter-api-v2
If you have been working with the standard v1.1 GET lists/statuses endpoint, the goal of this. Reference for the Enterprise X API tier covering migrate.
### List Posts lookup: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [GET lists/statuses](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/get-lists-statuses) endpoint, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 endpoints.
* **Similarities**
* Authentication methods
* Rate limits
* **Differences**
* Endpoint URLs
* App and Project requirements
* Data objects per request limits
* Response data formats
* Request parameters
#### Similarities
**Authentication**
Both endpoint versions support both [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-2-0). Therefore, if you were previously using one of the standard v1.1 List Posts lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
Depending on your authentication library/package of choice, App only authentication is probably the easiest way to get started and can be set with a simple request header. To learn how to generate an App only Access Token, see [this App only guide](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only).
**Rate limits**
| | |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Standard v1.1** | **X API v2** |
| /1.1/lists/statuses.json
900 requests per 15-minute window with OAuth 1.0a User Context
900 requests per 15-minute window with App only | /2/lists/:id/tweets
900 requests per 15-minute window with OAuth 1.0a User Context
900 requests per 15-minute window with OAuth 2.0 Authorization Code with PKCE
900 requests per 15-minute window with App only |
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* GET [https://api.x.com/1.1/lists/statuses.json](https://api.x.com/1.1/lists/statuses.json)
(Lookup Tweets from a specified List)
* X API v2 endpoint:
* GET [https://api.x.com/2/lists/:id/tweets](https://api.x.com/2/lists/:id/tweets)
(Lookup Tweets from a specified List)
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps associated with a project.
**Data objects per request limits**
The standard v1.1 /lists/statuses endpoint allows you to return up to 5000 Posts per request. The new v2 endpoints allow you to return up to 100 Posts per request. By default, 100 user objects will be returned, to change the number of results you will need to pass a query parameter max\_results= with a number between 1-100; you can then pass the next\_token returned in the response payload to the pagination\_token query parameter in your next request.
**Response data format**
One of the biggest differences between standard v1.1 and X API v2 endpoint versions is how you select which fields return in your payload.
For the standard endpoints, you receive many of the response fields by default and then have the option to use parameters to identify which additional fields or sets of fields should return in the payload.
The X API v2 version only delivers the Post id and text fields by default. To request any additional fields or objects, you will need to use the [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) parameters. Any Post fields that you request from this endpoint will return in the primary Post object. Any expanded object fields will return an includes object within your response. You can then match any expanded objects back to the primary Post object by matching the IDs from the primary object and in expanded objects.
Here are examples of possible Post fields and expansions:
* attachments
* author\_id
* context\_annotations
* created\_at
* geo
* lang
| | |
| :------------------ | :------------ |
| **Endpoint** | **Expansion** |
| /2/lists/:id/tweets | author\_id |
We encourage you to read more about these new parameters in their respective guides, or by reading our guide on [how to use fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions).
We have also put together a [data format migration guide](/x-api/migrate/data-format-migration) that can help you map standard v1.1 fields to the newer v2 fields. This guide will also provide you the specific expansion and field parameter that you will need to pass with your v2 request to return specific fields.
In addition to the changes in how you request certain fields, X API v2 is also introducing new JSON designs for the objects returned by the APIs, including [Post](/x-api/fundamentals/data-dictionary/reference#tweet) and [user](/x-api/fundamentals/data-dictionary/reference#user) objects.
* At the JSON root level, the standard endpoints return Post objects in a **statuses** array, while X API v2 returns a **data** array.
* Instead of referring to Retweeted and Quoted "statuses", X API v2 JSON refers to Retweeted and Quoted Tweets. Many legacy and deprecated fields, such as **contributors** and **user.translator\_type** are being removed.
* Instead of using both **favorites** (in Post object) and **favourites** (in user object), X API v2 uses the term **like**.
* X is adopting the convention that JSON values with no value (for example, **null**) are not written to the payload. Post and user attributes are only included if they have non-null values.
**Request parameters**
The following standard v1.1 request parameters have equivalents in X API v2:
| | |
| :------------------ | :----------------------------------------------------------- |
| Standard v1.1 | X API v2 |
| list\_id | id |
| slug | No equivalent |
| owner\_screen\_name | No equivalent |
| owner\_id | Requested with expansions parameter with value of author\_id |
| since\_id | No equivalent |
| max\_id | No equivalent |
| include\_entities | Requested with tweet.fields parameter with value of entities |
| include\_rts | No equivalent |
| count | max\_results |
***
## Code examples
### Get Posts from a List (v2)
```bash cURL theme={null}
curl "https://api.x.com/2/lists/84839422/tweets?tweet.fields=created_at,public_metrics&max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/lists/84839422/tweets"
params = {
"tweet.fields": "created_at,public_metrics",
"max_results": 100
}
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers, params=params)
print(response.json())
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get Posts from a List
for page in client.lists.get_tweets(
"84839422",
tweet_fields=["created_at", "public_metrics"],
max_results=100
):
for post in page.data:
print(f"{post.created_at}: {post.text[:50]}...")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get Posts from a List
const paginator = client.lists.getTweets("84839422", {
tweetFields: ["created_at", "public_metrics"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.created_at}: ${post.text?.slice(0, 50)}...`);
});
}
```
# Quickstart
Source: https://docs.x.com/enterprise-api/lists/list-tweets/quickstart
Quickstart guide for fetching Posts from an X List timeline with the Enterprise tier List Posts endpoint, including authentication and example calls.
This guide walks you through retrieving Posts from a List timeline.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
You can find a List ID in the URL when viewing a List on x.com:
```
https://x.com/i/lists/84839422
└── This is the List ID
```
```bash cURL theme={null}
curl "https://api.x.com/2/lists/84839422/tweets?\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id&\
user.fields=username,verified&\
max_results=10" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get Posts from a List with pagination
for page in client.lists.get_tweets(
"84839422",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id"],
user_fields=["username", "verified"],
max_results=10
):
for post in page.data:
print(f"{post.text[:50]}... - Likes: {post.public_metrics.like_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get Posts from a List with pagination
const paginator = client.lists.getTweets("84839422", {
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id"],
userFields: ["username", "verified"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}... - Likes: ${post.public_metrics?.like_count}`);
});
}
```
```json theme={null}
{
"data": [
{
"id": "1458172421115101189",
"text": "Check out our latest announcement...",
"author_id": "4172587277",
"created_at": "2024-01-15T10:30:00.000Z",
"public_metrics": {
"retweet_count": 42,
"reply_count": 5,
"like_count": 156,
"quote_count": 3
},
"edit_history_tweet_ids": ["1458172421115101189"]
}
],
"includes": {
"users": [
{
"id": "4172587277",
"username": "TechNews",
"verified": true
}
]
},
"meta": {
"result_count": 1,
"next_token": "7140dibdnow9c7btw3z2vwioavpvutgzrzm9icis4ndix"
}
}
```
The SDKs handle pagination automatically. For cURL, use the `next_token` from the response to get more Posts:
```bash theme={null}
curl "https://api.x.com/2/lists/84839422/tweets?\
max_results=10&\
pagination_token=7140dibdnow9c7btw3z2vwioavpvutgzrzm9icis4ndix" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
This endpoint returns up to 800 of the most recent Posts from the List.
***
## Next steps
Get List details
Get List members
Key concepts and best practices
Full endpoint documentation
# Integration guide
Source: https://docs.x.com/enterprise-api/lists/manage-lists/integrate
This page covers tools and key concepts for integrating the Lists endpoints. Reference for the Enterprise X API tier covering manage lists.
This page covers tools and key concepts for integrating the Lists endpoints.
## Helpful tools
Before we dive into some key concepts that will help you integrate this endpoint, we recommend that you become familiar with:
#### Postman
Postman is a great tool that you can use to test out an endpoint. Each Postman request includes every path and body parameter to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our ["Using Postman"](/tutorials/postman-getting-started) page.
#### Code samples
Are you interested in getting set up with this endpoint with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [Github page](https://github.com/xdevplatform/Twitter-API-v2-sample-code).
#### Third-party libraries
Take advantage of one of our communities' [third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the proper version tag.
### Key concepts
#### Authentication
All X API v2 endpoints require you to authenticate your requests with a set of credentials, also known as keys and tokens.
These specific endpoints requires the use of [OAuth 1.0a User Context](/resources/fundamentals/authentication), which means that you must use a set of API keys and user Access Tokens to make a successful request. The Access Tokens must be associated with the user that you are making the request on behalf of. If you would like to generate a set of Access Tokens for another user, they must authorize or authenticate your App using the [3-legged OAuth flow](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow).
Please note that OAuth 1.0a can be tricky to use. If you are not familiar with this authentication method, we recommend that you use a [library](/tools-and-libraries) or a tool like Postman to properly authenticate your requests.
#### Developer Console, Projects, and developer Apps
To retrieve a set of authentication credentials that will work with the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info), set up a [Project](/resources/fundamentals/developer-apps) within that account, and created a [developer App](/resources/fundamentals/developer-apps) within that Project. You can then find your keys and tokens within your developer App.
#### Rate limits
Every day, many thousands of developers make requests to the X API. To help manage the sheer volume of these requests, [rate limits](/x-api/fundamentals/rate-limits) are placed on each endpoint that limits the number of requests that you can make on behalf of your app or on behalf of an authenticated user.
These endpoints are rate limited at the user level, meaning that the authenticated user that you are making the request on behalf of can only call the endpoint a certain number of times across any developer App.
The chart below shows the rate limits for each endpoint.
| | | |
| :----------- | :-------------- | :-------------------------- |
| **Endpoint** | **HTTP method** | **Rate limit** |
| /2/lists | POST | 300 requests per 15 minutes |
| /2/lists/:id | DELETE / PUT | 300 requests per 15 minutes |
***
### Code examples
#### Create a List
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/lists" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"name": "My List", "description": "A list of interesting accounts"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Create a new List
response = client.lists.create(
name="My List",
description="A list of interesting accounts"
)
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Create a new List
const response = await client.lists.create({
name: "My List",
});
console.log(response.data);
```
#### Update a List
```bash cURL theme={null}
curl -X PUT "https://api.x.com/2/lists/123456789" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"name": "Updated List Name"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Update a List
response = client.lists.update(
list_id="123456789",
name="Updated List Name"
)
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Update a List
const response = await client.lists.update("123456789", {
name: "Updated List Name",
});
console.log(response.data);
```
# Manage Lists
Source: https://docs.x.com/enterprise-api/lists/manage-lists/introduction
Use the Enterprise Manage Lists endpoints to create, update, and delete X Lists on behalf of authenticated users and organize accounts into curated timelines.
The Manage Lists endpoints let you create, update, and delete Lists on behalf of authenticated users.
## Overview
Create a new List
Update List name and description
Delete a List
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :----------------------------------------- | :---------------- |
| POST | [`/2/lists`](/x-api/lists/create-list) | Create a new List |
| PUT | [`/2/lists/:id`](/x-api/lists/update-list) | Update a List |
| DELETE | [`/2/lists/:id`](/x-api/lists/delete-list) | Delete a List |
***
## Example: Create a List
```bash theme={null}
curl -X POST "https://api.x.com/2/lists" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Tech News",
"description": "My favorite tech journalists",
"private": false
}'
```
## Example response
```json theme={null}
{
"data": {
"id": "1234567890",
"name": "Tech News"
}
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
Create your first List
Key concepts and best practices
Add and remove members
Full endpoint documentation
# Overview
Source: https://docs.x.com/enterprise-api/lists/manage-lists/migrate/overview
The v2 manage Lists endpoints will eventually replace POST lists/create, POST lists/destroy, and POST lists/update. If you have code, apps, or tools that use.
## Comparing X API’s Lists endpoints
The v2 manage Lists endpoints will eventually replace [POST lists/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-create), [POST lists/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy), and [POST lists/update](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-update). If you have code, apps, or tools that use an older version of these endpoints and are considering migrating to the newer X API v2, then this guide is for you.
The following tables compare the standard v1.1 and X API v2 List endpoints:
**Create a List**
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------- | :------------------------------------- |
| HTTP methods supported | POST | POST |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/lists/create.json | /2/lists |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | None | 300 requests per 15 min (per user) |
**Delete a List**
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------- | :------------------------------------- |
| HTTP methods supported | POST | DELETE |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/lists/destroy.json | /2/lists/:id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | None | 300 requests per 15 min (per user) |
**Update a List**
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------- | :------------------------------------- |
| HTTP methods supported | POST | PUT |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/lists/update.json | /2/lists/:id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | None | 300 requests per 15 min (per user) |
To access the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info). When authenticating, you must use keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started](/x-api/getting-started/getting-access) page.
# v1 to v2
Source: https://docs.x.com/enterprise-api/lists/manage-lists/migrate/standard-to-twitter-api-v2
If you have been working with the standard v1.1 POST lists/create, POST lists/destroy, and POST. Reference for the Enterprise X API tier covering migrate.
### Manage Lists: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [POST lists/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-create), [POST lists/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy), and [POST lists/update](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/create-manage-lists/api-reference/post-lists-update) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 manage List endpoints.
* **Similarities**
* Authentication
* **Differences**
* Endpoint URLs
* App and Project requirements
* HTTP methods
* Rate limits
* Request parameters
#### Similarities
**Authentication**
Both endpoint versions support [OAuth 1.0a User Context](https://developer.x.com/content/developer-twitter/resources/fundamentals/authentication). Therefore, if you were previously using one of the standard v1.1 manage Lists endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* POST [https://api.x.com/1.1/lists/create.json](https://api.x.com/1.1/lists/create.json)
(Creates a List)
* POST [https://api.x.com/1.1/lists/destroy.json](https://api.x.com/1.1/lists/destroy.json)
(Deletes a List)
* POST [https://api.x.com/1.1/lists/update.json](https://api.x.com/1.1/lists/update.json)
(Updates a List)
* X API v2 endpoint:
* POST [https://api.x.com/2/lists](https://api.x.com/2/lists)
(Creates a List)
* DELETE [https://api.x.com/2/lists/:id](https://api.x.com/2/lists/:id)
(Deletes a List)
* PUT [https://api.x.com/2/lists/:id](https://api.x.com/2/lists/:id)
(Updates a List)
**Rate limits**
| **Standard v1.1** | **X API v2** |
| :-------------------------------------- | :------------------------------------------------------------------------------------- |
| /1.1/lists/create.json
none | /2/lists
300 requests per 15-minute window with OAuth 1.0a User Context |
| /1.1/lists/destroy.json
none | /2/lists/:id
300 requests per 15-minute window with OAuth 1.0a User Context |
| /1.1/lists/update.json
none | /2/lists/:id
300 requests per 15-minute window with OAuth 1.0a User Context |
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps related to a project.
**Request parameters**
The following standard v1.1 request parameters have equivalents in X API v2:
**Create a List**
| **Standard** | **X API v2** |
| :----------- | :----------- |
| name | name |
| mode | private |
| description | description |
**Delete/Update a List**
| **Standard** | **X API v2** |
| :------------------ | :------------ |
| owner\_screen\_name | No equivalent |
| owner\_id | No equivalent |
| list\_id | id |
| slug | No equivalent |
**Please note:** Standard v1.1 parameters are passed as query parameters, whereas the X API v2 parameters are passed as body parameters (for the POST endpoint) or path parameters (for the DELETE and PUT endpoints).
***
## Code examples
### Create a List (v2)
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/lists" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"name": "My List", "description": "A great list"}'
```
```python Python theme={null}
# Requires OAuth 1.0a User Context authentication
import requests
from requests_oauthlib import OAuth1
auth = OAuth1(
"API_KEY", "API_SECRET",
"ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"
)
url = "https://api.x.com/2/lists"
data = {"name": "My List", "description": "A great list"}
response = requests.post(url, auth=auth, json=data)
print(response.json())
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Create a List
response = client.lists.create(name="My List", description="A great list")
print(f"Created List: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Create a List
const response = await client.lists.create({
name: "My List",
});
console.log(`Created List: ${response.data?.id}`);
```
### Delete a List (v2)
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/lists/123456789" \
-H "Authorization: OAuth ..."
```
```python Python theme={null}
# Requires OAuth 1.0a User Context authentication
import requests
from requests_oauthlib import OAuth1
auth = OAuth1(
"API_KEY", "API_SECRET",
"ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"
)
url = "https://api.x.com/2/lists/123456789"
response = requests.delete(url, auth=auth)
print(response.json())
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Delete a List
response = client.lists.delete("123456789")
print(f"Deleted: {response.data.deleted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Delete a List
const response = await client.lists.delete("123456789");
console.log(`Deleted: ${response.data?.deleted}`);
```
# Quickstart
Source: https://docs.x.com/enterprise-api/lists/manage-lists/quickstart
This guide walks you through creating, updating, and deleting Lists. Reference for the Enterprise X API tier covering manage lists.
This guide walks you through creating, updating, and deleting Lists.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Create a List
Define the List name (required) and optional description and privacy settings:
```json theme={null}
{
"name": "Tech News",
"description": "Top tech journalists and publications",
"private": false
}
```
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/lists" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Tech News",
"description": "Top tech journalists and publications",
"private": false
}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Create a new List
response = client.lists.create(
name="Tech News",
description="Top tech journalists and publications",
private=False
)
print(f"List created: {response.data.id} - {response.data.name}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Create a new List
const response = await client.lists.create({
name: "Tech News",
description: "Top tech journalists and publications",
private: false,
});
console.log(`List created: ${response.data?.id} - ${response.data?.name}`);
```
```json theme={null}
{
"data": {
"id": "1441162269824405510",
"name": "Tech News"
}
}
```
Save the `id` to update or delete the List later.
***
## Update a List
Modify a List's name, description, or privacy:
```bash cURL theme={null}
curl -X PUT "https://api.x.com/2/lists/1441162269824405510" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Tech News & Insights",
"description": "Updated description"
}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Update a List
response = client.lists.update(
"1441162269824405510",
name="Tech News & Insights",
description="Updated description"
)
print(f"Updated: {response.data.updated}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Update a List
const response = await client.lists.update("1441162269824405510", {
name: "Tech News & Insights",
description: "Updated description",
});
console.log(`Updated: ${response.data?.updated}`);
```
**Response:**
```json theme={null}
{
"data": {
"updated": true
}
}
```
***
## Delete a List
You need the ID of the List you want to delete.
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/lists/1441162269824405510" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Delete a List
response = client.lists.delete("1441162269824405510")
print(f"Deleted: {response.data.deleted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Delete a List
const response = await client.lists.delete("1441162269824405510");
console.log(`Deleted: ${response.data?.deleted}`);
```
```json theme={null}
{
"data": {
"deleted": true
}
}
```
You can only delete Lists that you own.
***
## Next steps
Add and remove List members
Retrieve List details
Key concepts and best practices
Full endpoint documentation
# Integration guide
Source: https://docs.x.com/enterprise-api/lists/pinned-lists/integrate
This page covers tools and key concepts for integrating the pinned Lists endpoints. Reference for the Enterprise X API tier covering pinned lists.
This page covers tools and key concepts for integrating the pinned Lists endpoints.
## Helpful tools
Before we dive into some key concepts that will help you integrate this endpoint, we recommend that you become familiar with:
### Postman
Postman is a great tool that you can use to test out an endpoint. Each Postman request includes every path and body parameter to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our ["Using Postman"](/tutorials/postman-getting-started) page.
### Code samples
Interested in getting set up with this endpoint with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [Github page](https://github.com/xdevplatform/Twitter-API-v2-sample-code).
### Third-party libraries
Take advantage of one of our communities' [third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the proper version tag.
***
## Key concepts
### Authentication
All X API v2 endpoints require you to authenticate your requests with a set of credentials, also known as keys and tokens. You can use OAuth 1.0a User Context to authenticate your requests to this endpoint.
[OAuth 1.0a User Context](/resources/fundamentals/authentication), which means that you must use a set of API Keys and user Access Tokens to make a successful request. The access tokens must be associated with the user that you are making the request on behalf of. If you would like to generate a set of Access Tokens for another user, they must authorize your App using the [3-legged OAuth flow](https://developer.x.com/resources/fundamentals/authentication/obtaining-user-access-tokens).
Please note that OAuth 1.0a can be difficult to use. If you are not familiar with this authentication method, we recommend that you use a [library](/tools-and-libraries), use a tool like Postman.
### Developer Console, Projects, and developer Apps
To retrieve a set of authentication credentials that will work with the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info), set up a [Project](/resources/fundamentals/developer-apps) within that account, and created a [developer App](/resources/fundamentals/developer-apps) within that Project. You can then find your keys and tokens within your developer App.
### Rate limits
Every day, many thousands of developers make requests to the X API. To help manage the sheer volume of these requests, [rate limits](/x-api/fundamentals/rate-limits) are placed on each endpoint that limits the number of requests you can make on behalf of your app or on behalf of an authenticated user.
These endpoints are rate limited at the user level, meaning that the authenticated user that you are making the request on behalf of can only call the endpoint a certain number of times across any developer App.
The chart below shows the rate limits for each endpoint.
| Endpoint | HTTP method | Rate limit |
| :----------------------------------- | :---------- | :------------------------- |
| /2/users/:id/pinned\_lists | POST | 50 requests per 15 minutes |
| /2/users/:id/pinned\_lists/:list\_id | DELETE | 50 requests per 15 minutes |
| /2/users/:id/pinned\_lists | GET | 15 requests per 15 minutes |
### Fields and expansions
The X API v2 GET endpoint allows users to select exactly which data they want to return from the API using a set of tools called `fields` and `expansions`. The `expansions` parameter allows you to expand objects referenced in the payload. For example, looking up pinned Lists allows you to pull the following [expansions](/x-api/fundamentals/expansions):
* `owner_id`
The `fields` parameter allows you to select exactly which [fields](/x-api/fundamentals/fields) within the different data objects you would like to receive. This endpoint delivers user objects primarily. By default, the List object returns the `id`, and `name` fields. To receive additional fields such as `list.created_at` or `list.description`, you will have to specifically request those using a fields parameter.
We've added a guide on using [fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions) together to our [X API v2 data dictionary](/x-api/fundamentals/data-dictionary).
The chart below shows the field and expansions available for the lookup endpoint:
| Endpoint | Fields | Expansions |
| :------------------------- | :--------------------------- | :--------- |
| /2/users/:id/pinned\_lists | `list.fields`, `user.fields` | `owner_id` |
# Pinned Lists
Source: https://docs.x.com/enterprise-api/lists/pinned-lists/introduction
The Pinned Lists endpoints let you view, pin, and unpin Lists for the authenticated user. Reference for the Enterprise X API tier covering pinned lists.
The Pinned Lists endpoints let you view, pin, and unpin Lists for the authenticated user. Pinned Lists appear prominently in the user's X interface.
## Overview
Get user's pinned Lists
Pin a List
Unpin a List
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------------------- | :--------------- |
| GET | [`/2/users/:id/pinned_lists`](/x-api/users/get-pinned-lists) | Get pinned Lists |
| POST | [`/2/users/:id/pinned_lists`](/x-api/users/pin-list) | Pin a List |
| DELETE | [`/2/users/:id/pinned_lists/:list_id`](/x-api/users/unpin-list) | Unpin a List |
***
## Example: Get pinned Lists
```bash theme={null}
curl "https://api.x.com/2/users/123456789/pinned_lists?\
list.fields=name,description,member_count" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
## Example: Pin a List
```bash theme={null}
curl -X POST "https://api.x.com/2/users/123456789/pinned_lists" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"list_id": "9876543210"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
Get pinned Lists
Pin and unpin Lists
Key concepts and best practices
Full endpoint documentation
# Manage Pinned Lists
Source: https://docs.x.com/enterprise-api/lists/pinned-lists/quickstart/manage-pinned-lists
Quickstart for pinning and unpinning X Lists on an authenticated user account using the Enterprise tier pinned Lists endpoints with example requests.
This guide walks you through pinning and unpinning Lists.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Pin a List
You need your authenticated user's ID and the ID of the List you want to pin. Find List IDs in the URL when viewing a List.
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/2244994945/pinned_lists" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"list_id": "1454155907651158017"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Pin a List
response = client.lists.pin(
user_id="2244994945",
list_id="1454155907651158017"
)
print(f"Pinned: {response.data.pinned}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Pin a List
const response = await client.lists.pin("2244994945", {
listId: "1454155907651158017",
});
console.log(`Pinned: ${response.data?.pinned}`);
```
```json theme={null}
{
"data": {
"pinned": true
}
}
```
***
## Unpin a List
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/2244994945/pinned_lists/1454155907651158017" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Unpin a List
response = client.lists.unpin(
user_id="2244994945",
list_id="1454155907651158017"
)
print(f"Pinned: {response.data.pinned}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Unpin a List
const response = await client.lists.unpin("2244994945", "1454155907651158017");
console.log(`Pinned: ${response.data?.pinned}`);
```
**Response:**
```json theme={null}
{
"data": {
"pinned": false
}
}
```
***
## Important notes
* You can only pin Lists you follow or own
* Pinned Lists appear at the top of your Lists in the X app
* There's a limit on how many Lists you can pin
***
## Next steps
Get your pinned Lists
Get List details
Full endpoint documentation
# Pinned Lists Overview
Source: https://docs.x.com/enterprise-api/lists/pinned-lists/quickstart/overview
The pinned Lists endpoints let you look up a user's pinned Lists and manage which Lists are. Reference for the Enterprise X API tier covering quickstart.
The pinned Lists endpoints let you look up a user's pinned Lists and manage which Lists are pinned.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Available endpoints
Get your pinned Lists
Pin and unpin Lists
***
## Authentication
| Operation | Authentication |
| :------------------- | :--------------------------- |
| Look up pinned Lists | OAuth 1.0a or OAuth 2.0 PKCE |
| Pin/unpin Lists | OAuth 1.0a or OAuth 2.0 PKCE |
Both lookup and manage operations require user context authentication. App-only (Bearer Token) authentication is not supported.
***
## Quick example
```bash cURL theme={null}
# Get pinned Lists
curl "https://api.x.com/2/users/2244994945/pinned_lists" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get pinned Lists
response = client.lists.get_pinned("2244994945")
for lst in response.data:
print(f"{lst.name}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get pinned Lists
const response = await client.lists.getPinned("2244994945");
response.data?.forEach((lst) => {
console.log(lst.name);
});
```
***
## Next steps
Get List details
Create and update Lists
# Pinned Lists Lookup
Source: https://docs.x.com/enterprise-api/lists/pinned-lists/quickstart/pinned-list-lookup
Quickstart for retrieving a user's pinned X Lists with the Enterprise tier pinned Lists lookup endpoint, including authentication and sample responses.
This guide walks you through retrieving a user's pinned Lists.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Get pinned Lists
You need your authenticated user's ID. You can find it using the [user lookup endpoint](/x-api/users/lookup/introduction) or from your Access Token (the numeric part is your user ID).
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/pinned_lists?\
list.fields=follower_count,member_count,owner_id&\
expansions=owner_id&\
user.fields=created_at,username" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get pinned Lists
response = client.lists.get_pinned(
"2244994945",
list_fields=["follower_count", "member_count", "owner_id"],
expansions=["owner_id"],
user_fields=["created_at", "username"]
)
for lst in response.data:
print(f"{lst.name} - {lst.follower_count} followers")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get pinned Lists
const response = await client.lists.getPinned("2244994945", {
listFields: ["follower_count", "member_count", "owner_id"],
expansions: ["owner_id"],
userFields: ["created_at", "username"],
});
response.data?.forEach((lst) => {
console.log(`${lst.name} - ${lst.follower_count} followers`);
});
```
```json theme={null}
{
"data": [
{
"id": "1454155907651158017",
"name": "Tech News",
"follower_count": 150,
"member_count": 25,
"owner_id": "2244994945"
}
],
"includes": {
"users": [
{
"id": "2244994945",
"username": "XDevelopers",
"name": "X Developers",
"created_at": "2013-12-14T04:35:55.000Z"
}
]
},
"meta": {
"result_count": 1
}
}
```
***
## Available List fields
| Field | Description |
| :--------------- | :---------------------- |
| `description` | List description |
| `owner_id` | Owner's user ID |
| `private` | Whether List is private |
| `member_count` | Number of members |
| `follower_count` | Number of followers |
| `created_at` | List creation date |
***
## Next steps
Pin and unpin Lists
Get List details
Full endpoint documentation
# Remove List member
Source: https://docs.x.com/enterprise-api/lists/remove-list-member
delete /2/lists/{id}/members/{user_id}
Removes a User from a specific List by its ID and the User’s ID.
# Update List
Source: https://docs.x.com/enterprise-api/lists/update-list
put /2/lists/{id}
Updates the details of a specific List owned by the authenticated user by its ID.
# Check Marketplace handle availability
Source: https://docs.x.com/enterprise-api/marketplace/get-marketplace-handle-availability
get /2/marketplace/handles/{handle}/availability
Check whether a specific X handle is available for purchase through the Marketplace handle availability endpoint of the Enterprise X API.
# Append Media upload
Source: https://docs.x.com/enterprise-api/media/append-media-upload
post /2/media/upload/{id}/append
Appends data to a Media upload request.
# Create Media metadata
Source: https://docs.x.com/enterprise-api/media/create-media-metadata
post /2/media/metadata
Creates metadata for a Media file.
# Create Media subtitles
Source: https://docs.x.com/enterprise-api/media/create-media-subtitles
post /2/media/subtitles
Creates subtitles for a specific Media file.
# Delete Media subtitles
Source: https://docs.x.com/enterprise-api/media/delete-media-subtitles
delete /2/media/subtitles
Deletes subtitles for a specific Media file.
# Finalize Media upload
Source: https://docs.x.com/enterprise-api/media/finalize-media-upload
post /2/media/upload/{id}/finalize
Finalizes a Media upload request.
# Get Media analytics
Source: https://docs.x.com/enterprise-api/media/get-media-analytics
get /2/media/analytics
Retrieves analytics data for media.
# Get Media by media key
Source: https://docs.x.com/enterprise-api/media/get-media-by-media-key
get /2/media/{media_key}
Retrieves details of a specific Media file by its media key.
# Get Media by media keys
Source: https://docs.x.com/enterprise-api/media/get-media-by-media-keys
get /2/media
Retrieves details of Media files by their media keys.
# Get Media upload status
Source: https://docs.x.com/enterprise-api/media/get-media-upload-status
get /2/media/upload
Retrieves the status of a Media upload by its ID.
# Initialize media upload
Source: https://docs.x.com/enterprise-api/media/initialize-media-upload
post /2/media/upload/initialize
Initializes a media upload.
# Media upload and attachments on the Enterprise API
Source: https://docs.x.com/enterprise-api/media/introduction
Learn how media objects represent photos, videos, and GIFs on X, including upload size limits, chunked uploads, and attaching media_id to Posts or DMs.
A media object represents a single photo, video or animated GIF. Media objects are used by many endpoints within the X API, and may be included in Posts, Direct Messages, user profiles, advertising creatives and elsewhere. Each media object may have multiple display or playback variants, with different resolutions or formats.
## Media types & size restrictions
Size restrictions for uploading via API
* **Image**: `5 MB`
* **GIF**: `15 MB`
* **Video**: `512 MB` (when using `media_category=amplify_video`)
## Creation
Objects such as Posts, Direct Messages, user profile pictures, hosted Ads cards, etc. can contain one or more media objects. These top-level objects are collectively known as entities. The relevant entity creation API (e.g. [`POST /2/tweets`](/x-api/posts/creation-of-a-post)) can be passed one or more media objects using a unique `media_id`.
An entity which contains media object(s) can be created by following these steps:
1. Upload the media file(s) using either the recommended [chunked](/x-api/media/quickstart/media-upload-chunked) upload (images/GIF/video), or the older [simple](/x-api/media/upload-media) upload (images only).
2. Receive a `media_id` from step 1. This step may be repeated multiple times with different media if the entity allows multiple `media_id` parameters to be passed in.
3. Create the entity by calling the appropriate endpoint, including the `media_id` and other required parameters. For example, attach a `media_id` to a Post using the [`POST /2/tweets`](/x-api/posts/creation-of-a-post) endpoint.
## Retrieving
Please refer to the [Media Object](/x-api/fundamentals/data-dictionary/reference#media) in the data dictionary.
# Best practices
Source: https://docs.x.com/enterprise-api/media/quickstart/best-practices
Important concepts and best practices for using the POST /2/media/upload endpoint. Reference for the Enterprise X API tier covering quickstart.
There are a few important concepts to understand when using the [`POST /2/media/upload`](/x-api/media/upload-media) endpoint. Uploading media with OAuth can be a bit tricky, so we’ve outlined some things to keep in mind as well as a working sample of how to use this endpoint here.
## Keep in mind
* You may attach up to 4 photos, 1 animated GIF or 1 video in a Post.
* The image passed should be the raw binary of the image or binary base64 encoded, no need to otherwise encode or escape the contents as long as the Content-Type is set appropriately (when in doubt: `application/octet-stream`).
* When posting base64 encoded images, be sure to set the “Content-Transfer-Encoding: base64” on the image part of the message.
* Multi-part message boundaries must be on their own line and terminated by a CRLF.
* For working examples of how to POST using this endpoint, we recommend testing with [xurl](https://github.com/xdevplatform/xurl). Also, take a look at the [X Libraries](/resources/tools-and-libraries) available.
* Use the `media_id_string` provided in the API response for Javascript and any other languages that cannot accurately represent a long integer.
## Media categories
The Media Category parameter defines the use case of the media file to be uploaded, and can affect file size limits or other constraints enforced for media uploads. It’s important to use the correct media category when uploading media to avoid problems when trying to use the media. It is an optional value passed in the INIT request as part of the upload flow. If media category is not specified, the uploaded media is assumed to be media for a Post (`tweet_image`, `tweet_video`, or `tweet_gif`), depending on the content type.
The most common media categories are as follows:
* `tweet_image`
* `tweet_video`
* `tweet_gif`
* `dm_image`
* `dm_video`
* `dm_gif`
* `subtitles`
If you are an Ads API partner please refer to [these docs](/x-ads-api/creatives#promoted-video) for more information on recommended media category for promoted video.
## Image specifications and recommendations
Image files must meet all of the following criteria:
* **Supported image media types**: `JPG`, `PNG`, `GIF`, `WEBP`
* **Image size**: `<= 5 MB`
* **Animated GIF size**: `<= 15 MB`
The file size limit above is enforced by the media upload endpoint. In addition, there is a separate product entity specific file size limit which is applied when calling the Post creation (or similar) endpoints with `media_id`. The file size limit and other constraints may vary depending on the `media_category` parameter.
## Animated GIF recommendations
A GIF may fail during Post creation even if it is within the file size limit. Adhere to the following constraints to improve success rates.
* **Resolution**: `<= 1280x1080` (`width` x `height`)
* **Number of frames**: `<= 350`
* **Number of pixels**: `<= 300 million` (`width` \* `height` \* `num_frames`)
* **File size**: `<= 15Mb`
In order to process larger GIFs, use the [chunked upload](/x-api/media/quickstart/media-upload-chunked) endpoint with the `media_category` parameter. This allows the server to process the GIF file asynchronously, which is a requirement for processing larger files. Pass `media_category=tweet_gif` to enable async upload behavior for Posts with an animated GIF.
## Video specifications and recommendations
Please use the Async Path for media uploads.
### Recommended
* **Video Codec**: `H264 High Profile`
* **Frame Rates**: `30 FPS`, `60 FPS`
* **Video Resolution**: `1280x720` (landscape), `720x1280` (portrait), `720x720` (square). Subscribed users can upload a 1080p video and get 1080p playback. Unsubscribed users can upload a 720p video and get a 720p playback.
* **Minimum Video Bitrate**: `5,000 kbps`
* **Minimum Audio Bitrate**: `128 kbps`
* **Audio Codec**: `AAC LC`
* **Aspect Ratio**: `16:9` (landscape or portrait), `1:1` (square)
### Advanced
* **Frame rate**: must be `60 FPS` or less
* **Dimensions**: must be between `32x32` and `1280x1024`
* **File size**: must not exceed `512 mb`
* **Duration**: must be between `0.5 seconds` and `140 seconds`
* **Aspect ratio**: must be between `1:3` and `3:1`
* **[Pixel aspect ratio](https://en.wikipedia.org/wiki/Pixel_aspect_ratio)**: must have `1:1`
* **Pixel format**: Only [YUV](https://en.wikipedia.org/wiki/YUV) 4:2:0 is supported
* Audio must be [`AAC` with Low Complexity profile](https://en.wikipedia.org/wiki/Advanced_Audio_Coding#Modular_encoding). (High-Efficiency `AAC` is not supported)
* Audio must be `mono` or `stereo`, not 5.1 or greater
* Must not have [`open GOP`](https://en.wikipedia.org/wiki/Group_of_pictures)
* Must use [`progressive scan`](https://en.wikipedia.org/wiki/Progressive_scan)
### Additional Information
In the table below each row represents an upload recommendation, but is not a requirement. All uploads are processed for optimization across multiple platforms.
| Orientation | Width | Height | Video Bitrate | Audio Bitrate |
| :---------- | :---- | :----- | :------------ | :------------ |
| Landscape | 1280 | 720 | 2048K | 128K |
| Landscape | 640 | 360 | 768K | 64K |
| Landscape | 320 | 180 | 256K | 64K |
| Portrait | 720 | 1280 | 2048K | 128K |
| Portrait | 360 | 640 | 768K | 64K |
| Portrait | 180 | 320 | 256K | 64K |
| Square | 720 | 720 | 2048K | 128K |
| Square | 480 | 480 | 768K | 64K |
| Square | 240 | 240 | 256K | 32K |
For an example of how to upload media, please see the [chunked media upload documentation](/x-api/media/quickstart/media-upload-chunked).
### Troubleshooting
For issues with the Media APIs, browse the [Media API category](https://devcommunity.x.com/c/x-api/media-apis) in the developer forums for an answer.
# Chunked Media Upload
Source: https://docs.x.com/enterprise-api/media/quickstart/media-upload-chunked
This guide walks you through uploading videos and large media files using the chunked upload. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through uploading videos and large media files using the chunked upload workflow.
For video or large media uploads, you must:
1. **INIT** — Initialize the upload and get a `media_id`
2. **APPEND** — Upload each chunk of the file
3. **FINALIZE** — Complete the upload
4. **STATUS** — (If needed) Wait for processing to complete
See [this sample code](https://github.com/xdevplatform/large-video-upload-python) for a complete Python example.
***
## Step 1: Initialize upload (INIT)
Start the upload session to get a `media_id`:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/media/upload" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: multipart/form-data" \
-F "command=INIT" \
-F "media_type=video/mp4" \
-F "total_bytes=1048576" \
-F "media_category=amplify_video"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Initialize chunked upload
response = client.media.init_upload(
media_type="video/mp4",
total_bytes=1048576,
media_category="amplify_video"
)
media_id = response.data.id
print(f"Media ID: {media_id}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Initialize chunked upload
const response = await client.media.initUpload({
mediaType: "video/mp4",
totalBytes: 1048576,
mediaCategory: "amplify_video",
});
const mediaId = response.data?.id;
console.log(`Media ID: ${mediaId}`);
```
**Response:**
```json theme={null}
{
"data": {
"id": "1880028106020515840",
"media_key": "13_1880028106020515840",
"expires_after_secs": 1295999
}
}
```
***
## Step 2: Upload chunks (APPEND)
Upload each chunk of the file. For example, split a 3 MB file into 3 chunks:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/media/upload" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: multipart/form-data" \
-F "command=APPEND" \
-F "media_id=1880028106020515840" \
-F "segment_index=0" \
-F "media=@/path/to/chunk1.mp4"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Upload chunks
chunk_size = 1024 * 1024 # 1 MB chunks
with open("video.mp4", "rb") as f:
segment_index = 0
while True:
chunk = f.read(chunk_size)
if not chunk:
break
client.media.append_upload(
media_id=media_id,
segment_index=segment_index,
media=chunk
)
segment_index += 1
print(f"Uploaded chunk {segment_index}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
import fs from "fs";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Upload chunks
const chunkSize = 1024 * 1024; // 1 MB chunks
const fileBuffer = fs.readFileSync("video.mp4");
let segmentIndex = 0;
for (let offset = 0; offset < fileBuffer.length; offset += chunkSize) {
const chunk = fileBuffer.slice(offset, offset + chunkSize);
await client.media.appendUpload({
mediaId,
segmentIndex,
media: chunk,
});
console.log(`Uploaded chunk ${segmentIndex + 1}`);
segmentIndex++;
}
```
**Chunking advantages:**
* Improved reliability on slow networks
* Uploads can be paused and resumed
* Failed chunks can be retried individually
***
## Step 3: Finalize upload (FINALIZE)
Complete the upload after all chunks are sent:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/media/upload" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: multipart/form-data" \
-F "command=FINALIZE" \
-F "media_id=1880028106020515840"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Finalize upload
response = client.media.finalize_upload(media_id=media_id)
print(f"Processing state: {response.data.processing_info.state}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Finalize upload
const response = await client.media.finalizeUpload({ mediaId });
console.log(`Processing state: ${response.data?.processing_info?.state}`);
```
**Response:**
```json theme={null}
{
"data": {
"id": "1880028106020515840",
"media_key": "13_1880028106020515840",
"size": 1048576,
"expires_after_secs": 86400,
"processing_info": {
"state": "pending",
"check_after_secs": 1
}
}
}
```
If `processing_info` is returned, proceed to Step 4 to wait for processing. If not, the media is ready to use.
***
## Step 4: Check status (STATUS)
If `processing_info` was returned, poll for processing completion:
```bash cURL theme={null}
curl "https://api.x.com/2/media/upload?command=STATUS&media_id=1880028106020515840" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
import time
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Wait for processing to complete
while True:
response = client.media.get_status(media_id=media_id)
state = response.data.processing_info.state
if state == "succeeded":
print("Media ready!")
break
elif state == "failed":
print("Processing failed")
break
else:
check_after = response.data.processing_info.check_after_secs
print(f"Processing... checking again in {check_after}s")
time.sleep(check_after)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Wait for processing to complete
while (true) {
const response = await client.media.getStatus({ mediaId });
const state = response.data?.processing_info?.state;
if (state === "succeeded") {
console.log("Media ready!");
break;
} else if (state === "failed") {
console.log("Processing failed");
break;
} else {
const checkAfter = response.data?.processing_info?.check_after_secs ?? 1;
console.log(`Processing... checking again in ${checkAfter}s`);
await new Promise((r) => setTimeout(r, checkAfter * 1000));
}
}
```
**Processing states:** `pending` → `in_progress` → `succeeded` or `failed`
***
## Step 5: Create Post with media
Once processing is complete, create a Post with the media:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Check out this video!",
"media": {
"media_ids": ["1880028106020515840"]
}
}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Create Post with media
response = client.posts.create(
text="Check out this video!",
media={"media_ids": [media_id]}
)
print(f"Posted: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Create Post with media
const response = await client.posts.create({
text: "Check out this video!",
media: { mediaIds: [mediaId] },
});
console.log(`Posted: ${response.data?.id}`);
```
***
## Media categories
| Category | Description |
| :-------------- | :---------------------- |
| `tweet_image` | Image for a Post |
| `tweet_gif` | Animated GIF for a Post |
| `tweet_video` | Video for a Post |
| `amplify_video` | Amplify video |
***
## Next steps
File constraints and requirements
Post with media
Full endpoint documentation
# Upload media
Source: https://docs.x.com/enterprise-api/media/upload-media
post /2/media/upload
Uploads a media file for use in posts or other content.
# Get news stories by ID
Source: https://docs.x.com/enterprise-api/news/get-news-stories-by-id
get /2/news/{id}
Retrieves news story by its ID.
# News lookup endpoint on the Enterprise API
Source: https://docs.x.com/enterprise-api/news/introduction
Use the X news lookup endpoint to fetch breaking headlines, story summaries, contexts, tickers, and clustered Post results with bearer token authentication.
The news lookup endpoint allows developers to get news and headlines breaking on X.
This endpoint supports app-auth and user-auth authentication for OAuth1 and OAuth2 PKCE.
## Getting started
To use the endpoint, you need a [bearer token](/fundamentals/authentication/oauth-2-0/application-only) from the [Developer Console](https://developer.x.com/en/portal/dashboard).
Once you have the bearer token, you can call the news API as shown below:
```bash theme={null}
curl 'https://api.x.com/2/news/1989418137272422538?news.fields=contexts,cluster_posts_results' --header 'Authorization: Bearer XXXXX'
```
If the request is successful, you should see the JSON response as shown below:
```json theme={null}
{
"data":{
"category":"News",
"name":"Nebius Group Stock Plunges 30% Despite Q3 Revenue Surge and Meta Deal",
"summary":"Nebius Group announced third-quarter revenue of $214 million, a fourfold increase year-over-year, alongside a $3 billion five-year GPU cloud services contract with Meta Platforms on November 11, 2025. Despite these positives, shares fell over 30% to $83.58 by November 14, driven by AI sector cooling and a $119.6 million net loss. Analysts hold a strong Buy rating with an average price target of $139.67, while X users see the dip as a buying opportunity.",
"hook":"Nebius Group's shares cratered 30% after blockbuster Q3 earnings and a $3 billion Meta deal—yet analysts and investors are calling it a golden buying chance amid AI hype.",
"contexts":{
"sports":{
"teams":[]
},
"entities":{
"events":[],
"organizations":[
"Goldman Sachs",
"Nebius Group N.V."
],
"people":[],
"places":[],
"products":[]
},
"topics":[
"Stocks"
],
"finance":{
"tickers":[
"NBIS"
]
}
},
"cluster_posts_results":[
{
"post_id":"1989409257394245835"
},
{
"post_id":"1989410019562197162"
},
{
"post_id":"1989413132993999177"
},
{
"post_id":"1989411147179610400"
},
{
"post_id":"1989409829937656067"
},
{
"post_id":"1989415596249985296"
},
{
"post_id":"1989415537781477721"
},
{
"post_id":"1989413002739691628"
},
{
"post_id":"1989414454644363445"
},
{
"post_id":"1989411489988710860"
}
],
"disclaimer":"This story is a summary of posts on X and may evolve over time. Grok can make mistakes, verify its outputs.",
"last_updated_at_ms":"2025-11-17T16:21:41.000Z",
"id":"1989418137272422538"
}
}
```
# Search News
Source: https://docs.x.com/enterprise-api/news/search-news
get /2/news/search
Retrieves a list of News stories matching the specified search query.
# Integration guide
Source: https://docs.x.com/enterprise-api/posts/bookmarks/integrate
This page contains information on several tools and critical concepts that you should know as. Reference for the Enterprise X API tier covering bookmarks.
This page contains information on several tools and critical concepts that you should know as you integrate the manage Bookmarks endpoints into your system. We've broken the page into a couple of different sections:
* [Helpful tools](/x-api/users/blocks/integrate#helpful-tools)
* Key Concepts
* [Authentication](/x-api/users/blocks/integrate#authentication)
* [Developer Console, Projects, and Apps](/x-api/users/blocks/integrate#developer-console-projects-and-developer-apps)
* [Rate limits](/x-api/users/blocks/integrate#rate-limits)
### Helpful tools
Before we dive into some key concepts that will help you integrate this endpoint, we recommend that you become familiar with:
#### Postman
Postman is a great tool that you can use to test out an endpoint. Each Postman request includes every path and body parameter to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our ["Using Postman"](/tutorials/postman-getting-started) page.
#### Code samples
Are you interested in getting set up with this endpoint with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [Github page](https://github.com/xdevplatform/Twitter-API-v2-sample-code).
#### Third-party libraries
Take advantage of one of our communities' [third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the proper version tag.
### Key concepts
#### Authentication
All X API v2 endpoints require you to authenticate your requests with a set of credentials, also known as keys and tokens.
These specific endpoints require the
# Bookmarks
Source: https://docs.x.com/enterprise-api/posts/bookmarks/introduction
The Bookmarks endpoints let you view, add, and remove bookmarked Posts for the authenticated. Reference for the Enterprise X API tier covering bookmarks.
The Bookmarks endpoints let you view, add, and remove bookmarked Posts for the authenticated user. Bookmarks are private and only visible to the user who created them.
## Overview
Get all bookmarked Posts
Bookmark a Post
Remove a bookmarked Post
Organize bookmarks into folders
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------------------------------- | :-------------------- |
| GET | [`/2/users/:id/bookmarks`](/x-api/users/get-bookmarks) | Get user's bookmarks |
| POST | [`/2/users/:id/bookmarks`](/x-api/users/create-bookmark) | Bookmark a Post |
| DELETE | [`/2/users/:id/bookmarks/:tweet_id`](/x-api/users/delete-bookmark) | Remove a bookmark |
| GET | [`/2/users/:id/bookmarks/folders`](/x-api/users/get-bookmark-folders) | Get bookmark folders |
| GET | [`/2/users/:id/bookmarks/folders/:folder_id`](/x-api/users/get-bookmarks-by-folder-id) | Get Posts in a folder |
***
## Example: Get bookmarks
```bash theme={null}
curl "https://api.x.com/2/users/123456789/bookmarks?\
tweet.fields=created_at,author_id,public_metrics" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
## Example: Add bookmark
```bash theme={null}
curl -X POST "https://api.x.com/2/users/123456789/bookmarks" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1234567890"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) or [3-legged OAuth](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow)
Get a user's bookmarks
Add and remove bookmarks
Key concepts and best practices
Full endpoint documentation
# Bookmarks Lookup
Source: https://docs.x.com/enterprise-api/posts/bookmarks/quickstart/bookmarks-lookup
This guide walks you through retrieving your bookmarked Posts using the X API. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through retrieving your bookmarked Posts using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token with `bookmark.read` scope (OAuth 2.0 PKCE)
***
## Get your bookmarks
You need your authenticated user's ID. You can find it using the `/2/users/me` endpoint or from the [user lookup endpoint](/x-api/users/lookup/introduction).
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/bookmarks?\
tweet.fields=created_at,public_metrics,author_id&\
max_results=10" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get bookmarked Posts with pagination
for page in client.bookmarks.get(
"2244994945",
tweet_fields=["created_at", "public_metrics", "author_id"],
max_results=10
):
for post in page.data:
print(f"{post.text[:50]}... - Likes: {post.public_metrics.like_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get bookmarked Posts with pagination
const paginator = client.bookmarks.get("2244994945", {
tweetFields: ["created_at", "public_metrics", "author_id"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}... - Likes: ${post.public_metrics?.like_count}`);
});
}
```
```json theme={null}
{
"data": [
{
"id": "1501258597237342208",
"text": "Have you built a project using the X API you'd like to share with the community? We'd love to hear from you!",
"created_at": "2024-01-15T10:30:00.000Z",
"author_id": "2244994945",
"public_metrics": {
"retweet_count": 15,
"reply_count": 8,
"like_count": 89,
"quote_count": 3
}
},
{
"id": "1501258542258348032",
"text": "This is just one way developer innovation helps make X a better place...",
"created_at": "2024-01-15T09:15:00.000Z",
"author_id": "2244994945",
"public_metrics": {
"retweet_count": 22,
"reply_count": 5,
"like_count": 156,
"quote_count": 7
}
}
],
"meta": {
"result_count": 2,
"next_token": "7140dibdnow9c7btw4539n0vybdnx19ylpayqf16fjt4l"
}
}
```
***
## Include author information
Use expansions to get data about Post authors:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/bookmarks?\
tweet.fields=created_at,author_id&\
expansions=author_id&\
user.fields=username,verified" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get bookmarks with author info
for page in client.bookmarks.get(
"2244994945",
tweet_fields=["created_at", "author_id"],
expansions=["author_id"],
user_fields=["username", "verified"]
):
for post in page.data:
print(f"{post.text[:50]}...")
# Author info is in page.includes.users
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get bookmarks with author info
const paginator = client.bookmarks.get("2244994945", {
tweetFields: ["created_at", "author_id"],
expansions: ["author_id"],
userFields: ["username", "verified"],
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}...`);
});
// Author info is in page.includes?.users
}
```
***
## Required scopes
When using OAuth 2.0 PKCE, your access token must have these scopes:
| Scope | Description |
| :-------------- | :------------------------------ |
| `bookmark.read` | Read bookmarks |
| `tweet.read` | Read Post data |
| `users.read` | Read user data (for expansions) |
***
## Next steps
Add and remove bookmarks
Full endpoint documentation
# Manage Bookmarks
Source: https://docs.x.com/enterprise-api/posts/bookmarks/quickstart/manage-bookmarks
This guide walks you through adding and removing bookmarks using the X API. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through adding and removing bookmarks using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token with `bookmark.write` scope (OAuth 2.0 PKCE)
***
## Add a bookmark
You need your authenticated user's ID. You can find it using the `/2/users/me` endpoint or the [user lookup endpoint](/x-api/users/lookup/introduction).
Find the Post ID in the URL when viewing a Post:
```
https://x.com/XDevelopers/status/1460323737035677698
└── This is the Post ID
```
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/2244994945/bookmarks" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1460323737035677698"}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Add a bookmark
response = client.bookmarks.create(
user_id="2244994945",
tweet_id="1460323737035677698"
)
print(f"Bookmarked: {response.data.bookmarked}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Add a bookmark
const response = await client.bookmarks.create("2244994945", {
tweetId: "1460323737035677698",
});
console.log(`Bookmarked: ${response.data?.bookmarked}`);
```
```json theme={null}
{
"data": {
"bookmarked": true
}
}
```
***
## Remove a bookmark
Delete a Post from your bookmarks:
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/2244994945/bookmarks/1460323737035677698" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Remove a bookmark
response = client.bookmarks.delete(
user_id="2244994945",
tweet_id="1460323737035677698"
)
print(f"Bookmarked: {response.data.bookmarked}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Remove a bookmark
const response = await client.bookmarks.delete("2244994945", "1460323737035677698");
console.log(`Bookmarked: ${response.data?.bookmarked}`);
```
**Response:**
```json theme={null}
{
"data": {
"bookmarked": false
}
}
```
***
## Required scopes
When using OAuth 2.0 PKCE, your access token must have these scopes:
| Scope | Description |
| :--------------- | :----------------------- |
| `bookmark.write` | Add and remove bookmarks |
| `tweet.read` | Read Post data |
| `users.read` | Read user data |
***
## Next steps
Get your bookmarked Posts
Full endpoint documentation
# Build a query
Source: https://docs.x.com/enterprise-api/posts/counts/integrate/build-a-query
Your queries will be limited depending on which access level you are using. Reference for the Enterprise X API tier covering integrate.
#### Building a query
**Query limitations!**
Your queries will be limited depending on which [access level](/x-api/getting-started/about-x-api) you are using.
Your query can be 512 characters long for pay-per-use customers, or up to 4,096 characters for Enterprise customers.
If you have Enterprise access, please reach out to your account manager.
**Operator availability**
While most operators are available to any developer, there are several that are reserved for those that have been approved for Enterprise access. We list which access level each operator is available to in the [list of operators](/x-api/posts/search/integrate/build-a-query) table using the following labels:
* Core operators: Available when using any [Project](/resources/fundamentals/developer-apps).
* Advanced operators: Available when using a Project with Enterprise access
#### Operator types: standalone and conjunction-required
**Standalone operators** can be used alone or together with any other operators (including those that require conjunction).
For example, the following query will work because it uses the #hashtag operator, which is standalone:
\#xapiv2
**Conjunction-required** operators cannot be used by themselves in a query; they can only be used when at least one standalone operator is included in the query. This is because using these operators alone would be far too general, and would match on an extremely high volume of Posts.
For example, the following queries are not supported since they contain only conjunction-required operators:
has:media
has:links OR is:retweet
If we add in a standalone operator, such as the phrase "X data", the query would then work properly.
"X data" has:mentions (has:media OR has:links)
#### Boolean operators and grouping
If you would like to string together multiple operators in a single query, you have the following tools at your disposal:
| | |
| :---------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **AND logic** | Successive operators with a space between them will result in boolean "AND" logic, meaning that Posts will match only if both conditions are met. For example, snow day #NoSchool will match Posts containing the terms snow and day and the hashtag #NoSchool. |
| **OR logic** | Successive operators with OR between them will result in OR logic, meaning that Posts will match if either condition is met. For example, specifying grumpy OR cat OR #meme will match any Posts containing at least the terms grumpy or cat, or the hashtag #meme. |
| **NOT logic, negation** | Prepend a dash (-) to a keyword (or any operator) to negate it (NOT). For example, cat #meme -grumpy will match Posts containing the hashtag #meme and the term cat, but only if they do not contain the term grumpy. One common query clause is -is:retweet, which will not match on Retweets, thus matching only on original Posts, Quote Tweets, and replies. All operators can be negated, but negated operators cannot be used alone. |
| **Grouping** | You can use parentheses to group operators together. For example, (grumpy cat) OR (#meme has:images) will return either Posts containing the terms grumpy and cat, or Posts with images containing the hashtag #meme. Note that ANDs are applied first, then ORs are applied. |
**A note on negations**
The operators -is:nullcast must always be negated.
Negated operators cannot be used alone.
Do not negate a set of operators grouped together in a set of parentheses. Instead, negate each individual operator. For example, instead of using skiing -(snow OR day OR noschool), we suggest that you use skiing -snow -day -noschool.
**Order of operations**
When combining AND and OR functionality, the following order of operations will dictate how your query is evaluated.
1. Operators connected by AND logic are combined first
2. Then, operators connected with OR logic are applied
For example:
* apple OR iphone ipad would be evaluated as apple OR (iphone ipad)
* ipad iphone OR android would be evaluated as (iphone ipad) OR android
To eliminate uncertainty and ensure that your query is evaluated as intended, group terms together with parentheses where appropriate.
For example:
* (apple OR iphone) ipad
* iphone (ipad OR android)
**Punctuation, diacritics, and case sensitivity**
If you specify a keyword or hashtag query with character accents or diacritics, it will match Post text that contains both the term with the accents and diacritics, as well as those terms with normal characters. For example, queries with a keyword Diacrítica or hashtag #cumpleaños will match *Diacrítica* or *#cumpleaños*, as well as with *Diacritica* or *#cumpleanos* without the tilde í or eñe.
Characters with accents or diacritics are treated the same as normal characters and are not treated as word boundaries. For example, a query with the keyword cumpleaños would only match activities containing the word *cumpleaños* and would not match activities containing *cumplea*, *cumplean*, or *os*.
All operators are evaluated in a case-insensitive manner. For example, the query cat will match Posts with all of the following: *cat*, *CAT*, *Cat*.
The [filtered stream](/x-api/posts/filtered-stream) matching behavior acts differently from Post counts. When [building a filtered stream rule](/x-api/posts/filtered-stream/integrate/build-a-rule), know that keywords and hashtags that include accents and diacritics will only match on terms that also include the accent and diacritic, and will not match on terms that use normal characters instead.
For example, filtered stream rules that include a keyword Diacrítica or hashtag #cumpleaños will only match the terms *Diacrítica* and *#cumpleaños*, and will not match on *Diacritica* or *#cumpleanos* without the tilde í or eñe.
**Specificity and efficiency**
When you start to build your query, it is important to keep a few things in mind.
* Using broad, standalone operators for your query such as a single keyword or #hashtag is generally not recommended since it will likely match on a massive volume of Posts. Creating a more robust query will result in a more specific set of matching Posts, and will hopefully increase the accuracy of your Post counts to help you find more valuable insights.
* For example, if your query was just the keyword happy you will likely get anywhere from 200,000 - 300,000 Posts per day.
* Adding more conditional operators narrows your results, for example (happy OR happiness) place\_country:GB -birthday -is:retweet
* Writing efficient queries is also beneficial for staying within the characters query length restriction. The character count includes the entire query string including spaces and operators.
* For example, the following query is 59 characters long: (happy OR happiness) place\_country:GB -birthday -is:retweet
**Quote Tweet matching behavior**
When using the Post counts endpoints, operators will not match on the content from the original Post that was quoted, but will match on the content included in the Quote Tweet.
However, please note that [filtered stream](/x-api/posts/filtered-stream) will match on both the content from the original Post that was quoted and the Quote Tweet's content.
**Iteratively building a query**
**Test your query early and often**
Getting a query to return the "right" results the first time is rare. There is so much on X that may or may not be obvious at first and the query syntax described above may be hard to match to your desired query.
As you build a query, it is important for you to periodically test it out using one of the [Search Post](/x-api/posts/search/introduction) endpoints to ensure that the Posts that are matching your query are relevant to your use case.
For this section, we are going to start with the following query and adjust it based on the results that we receive during our test:
happy OR happiness
**Use results to narrow the query**
As you test the query with Search Posts, you should scan the returned Posts to see if they include the data that you are expecting and hoping to receive. Starting with a broad query and a superset of Post matches allows you to review the result and narrow the query to filter out undesired results.
When we tested the example query, we noticed that we were getting Posts in a variety of different languages. In this situation, we want to only receive Posts that are in english, so we’re going to add the lang: operator:
(happy OR happiness) lang:en
The test delivered a number of Posts wishing people a happy birthday, so we are going to add -birthday as a negated keyword operator. We also want to only receive original Posts, so we’ve added the negated -is:retweet operator:
(happy OR happiness) lang:en -birthday -is:retweet
**Adjust for inclusion where needed**
If you notice that you are not receiving data via Search Posts that you expect and know that there are existing Posts that should return, you may need to broaden your query by removing operators that may be filtering out the desired data.
For our example, we noticed that there were other Posts in our personal timeline that expressed the emotion that we are looking for and weren’t included in the test results. To ensure we have greater coverage, we are going to add the keywords, excited and elated.
(happy OR happiness OR excited OR elated) lang:en -birthday -is:retweet
**Adjust for popular trends/bursts over the time period**
Trends come and go on X quickly. Maintaining your query should be an active process. If you plan to use a query for a while, we suggest that you periodically check in on the data that you are receiving to see if you need to make any adjustments.
In our example, we notice that we started to receive some Posts that are wishing people a “happy holidays”. Since we don’t want these Posts included in our results, we are going to add a negated -holidays keyword.
(happy OR happiness OR excited OR elated) lang:en -birthday -is:retweet -holidays
Once you've properly tested and iterated upon your query, you can start sending it with the Post counts endpoints to start to receive just the volume of Posts rather than the full Post payloads.
#### Adding a query to your request
To add your query to your request, you must use the query parameter. As with any query parameters, you must make sure to HTTP encode the query that you developed.
Here is an example of what this might look like using a cURL command. If you would like to use this command, please make sure to replace \$BEARER\_TOKEN with your own [Bearer Token](/resources/fundamentals/authentication#oauth-2-0):
```
curl https://api.x.com/2/tweets/counts/recent?query=cat%20has%3Amedia%20-grumpy&tweet.fields=created_at&max_results=100 -H "Authorization: Bearer $BEARER_TOKEN"
```
#### Query examples
**Tracking a natural disaster**
The following query matched on original Posts coming from weather agencies and gauges that discuss Hurricane Harvey, which hit Houston in 2017.
Here is what the query would look like without the HTTP encoding:
has:geo (from:NWSNHC OR from:NHC\_Atlantic OR from:NWSHouston OR from:NWSSanAntonio OR from:USGS\_TexasRain OR from:USGS\_TexasFlood OR from:JeffLindner1) -is:retweet
And here is what the query would look like with the HTTP encoding, the query parameter, and the recent Post counts URI:
[https://api.x.com/2/tweets/counts/recent?query=-is%3Aretweet%20has%3Ageo%20(from%3ANWSNHC%20OR%20from%3ANHC\\\_Atlantic%20OR%20from%3ANWSHouston%20OR%20from%3ANWSSanAntonio%20OR%20from%3AUSGS\\\_TexasRain%20OR%20from%3AUSGS\_TexasFlood%20OR%20from%3AJeffLindner1)](https://api.x.com/2/tweets/counts/recent?query=-is%3Aretweet%20has%3Ageo%20\(from%3ANWSNHC%20OR%20from%3ANHC\\_Atlantic%20OR%20from%3ANWSHouston%20OR%20from%3ANWSSanAntonio%20OR%20from%3AUSGS\\_TexasRain%20OR%20from%3AUSGS_TexasFlood%20OR%20from%3AJeffLindner1\))
**Reviewing the sentiment of a conversation**
The next rule could be used to better understand the sentiment of the conversation developing around the hashtag, *#nowplaying*, but scoped to just Posts published within
# Overview
Source: https://docs.x.com/enterprise-api/posts/counts/integrate/overview
This page covers tools and key concepts for integrating the Post counts endpoints. Reference for the Enterprise X API tier covering integrate.
This page covers tools and key concepts for integrating the Post counts endpoints.
## Helpful tools
Before we start to explore some key concepts, we recommend that you use one of the following tools or code samples to start testing the functionality of these endpoints.
### Code samples
Interested in getting set up with these endpoints with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [GitHub page](https://github.com/xdevplatform/Twitter-API-v2-sample-code), including a [Python client](https://github.com/xdevplatform/search-tweets-python).
### Libraries
Take advantage of one of our many [community third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the appropriate version tag.
### Postman
Postman is a great tool that you can use to test out these endpoints. Each Postman request includes all of the given endpoint's parameters to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our [Using Postman](/tutorials/postman-getting-started) page.
***
## Key concepts
### Authentication
All X API v2 endpoints require requests to be [authenticated](/resources/fundamentals/authentication) with a set of credentials, also known as keys and tokens. This specific endpoint requires the use of [OAuth 2.0 Bearer Token](/resources/fundamentals/authentication#oauth-2-0), which means that you must pass a [Bearer Token](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only) to make a successful request. You can either generate a Bearer Token from directly within a developer App, or generate one using the [POST oauth2/token](/resources/fundamentals/authentication#post-oauth2-token) endpoint.
### Developer Console, Projects, and developer Apps
To work with any X API v2 endpoints, you must have a [developer account](/resources/fundamentals/developer-portal), set up a [Project](/resources/fundamentals/developer-apps) within that account, and created a [developer App](/resources/fundamentals/developer-apps) within that Project. Your keys and tokens within that developer App will work for the recent Post counts endpoints. If you would like to use the full-archive Post counts endpoint, or utilize the advanced operators and longer query length, you will need to have been approved for enterprise access.
Please visit our section on enterprise access to learn more.
### Rate limits
Every day, many thousands of developers make requests to the X API. To help manage the volume, [rate limits](/x-api/fundamentals/rate-limits) are placed on each endpoint that limits the number of requests that every developer can make on behalf of an app or on behalf of an authenticated user.
This endpoint is rate limited at the App-level, meaning that you, the developer, can only make a certain number of requests to this endpoint over a given period of time from any given App (assumed by the credentials that you are using).
### Building queries
The central feature of these endpoints is their use of a single query to filter the Posts into the counts that deliver to you. These queries are made up of operators that match on Post and user attributes, such as message keywords, hashtags, and URLs. Operators can be combined into queries with boolean logic and parentheses to help refine the query's matching behavior.
You can use our guide on [how to build a query](/x-api/posts/counts/integrate/build-a-query) to learn more.
### Pagination
For recent Post counts, there is no next\_token returned, which means that regardless of the granularity, you will get the Post volume for the last 7 days in one API call.
For full-archive Post counts, you will get data for the last 30 days. For data more than 30 days, you will get a next\_token which you can then use to paginate to get the additional data.
# Post Counts
Source: https://docs.x.com/enterprise-api/posts/counts/introduction
The Post counts endpoints return the volume of Posts matching a query over time, without returning. Reference for the Enterprise X API tier covering counts.
The Post counts endpoints return the volume of Posts matching a query over time, without returning the Posts themselves. Use these endpoints to analyze trends, understand conversation size, and refine queries before searching.
## Overview
Build trendlines and visualizations showing Post volume over time
Estimate result size before running full search queries
Identify when conversations peaked around events
Understand conversation scale without retrieving all Posts
***
## Endpoints
| Endpoint | Description | Access |
| :---------------------------------------------------------------------- | :-------------------------------- | :---------------------- |
| GET [`/2/tweets/counts/recent`](/x-api/posts/get-count-of-recent-posts) | Count Posts from last 7 days | All developers |
| GET [`/2/tweets/counts/all`](/x-api/posts/get-count-of-all-posts) | Count Posts from complete archive | Pay-per-use, Enterprise |
***
## Granularity options
Specify how counts are grouped using the `granularity` parameter:
| Granularity | Description | Use case |
| :---------- | :------------------------ | :------------------- |
| `minute` | Counts per minute | Real-time monitoring |
| `hour` | Counts per hour (default) | Daily analysis |
| `day` | Counts per day | Long-term trends |
***
## Recent counts
Count Posts from the **last 7 days**. Available to all developers.
### Features
* Counts grouped by minute, hour, or day
* Same query operators as recent search
* 512-character query length
### Example response
```json theme={null}
{
"data": [
{ "start": "2024-01-15T00:00:00.000Z", "end": "2024-01-15T01:00:00.000Z", "tweet_count": 1523 },
{ "start": "2024-01-15T01:00:00.000Z", "end": "2024-01-15T02:00:00.000Z", "tweet_count": 1247 },
{ "start": "2024-01-15T02:00:00.000Z", "end": "2024-01-15T03:00:00.000Z", "tweet_count": 892 }
],
"meta": {
"total_tweet_count": 3662
}
}
```
Make your first recent counts request
Full endpoint documentation
***
## Full-archive counts
Count Posts from the **complete archive** back to 2006.
Full-archive counts are available to pay-per-use and Enterprise customers.
### Features
* Count historical Posts from any time period
* All query operators available
* 1,024-character query length (4,096 for Enterprise)
### Pagination
Results paginate at 31 days per response:
* **Day granularity**: 31 days per page
* **Hour granularity**: 744 hours (31 days) per page
* **Minute granularity**: 44,640 minutes (31 days) per page
Make your first full-archive counts request
Full endpoint documentation
***
## Query operators
Post counts use the same query syntax as search endpoints:
```
python lang:en -is:retweet
```
Learn query syntax and operators
***
## Important notes
**Counts vs search results**
Counts may not exactly match search results. Search endpoints apply additional compliance filtering that counts endpoints do not perform.
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [Bearer Token](/resources/fundamentals/authentication)
Count Posts from the last 7 days
Count historical Posts
Key concepts and best practices
Working code examples
# v1 to v2 (Enterprise)
Source: https://docs.x.com/enterprise-api/posts/counts/migrate/enterprise-to-twitter-api-v2
Granularity Pagination Timezone Endpoint URLs App and Project requirement Available time periods. Reference for the Enterprise X API tier covering migrate.
### Enterprise compared to X API v2
**Similarities**
* Granularity
* Pagination
* Timezone
**Differences**
* Endpoint URLs
* App and Project requirement
* Available time periods
* Response data format
* HTTP methods
* Request time formats
* Request parameters
* Filtering operators
#### Similarities
**Granularity**
While the parameter for selecting granularity of the returned data is different (`bucket` for the enterprise version, `granularity` for the v2 version), the values that you can pass with that parameter are the same, as well as the default behavior:
* `day`
* `hour` (default)
* `minute`
**Pagination**
While v2 has additional pagination features (new pagination parameters that allow you to navigate using Post IDs with `since_id` and `until_id`), both enterprise and v2 allow you to paginate using time (`fromDate` and `toDate` with enterprise, and `start_time` and `end_time` for v2).
If you are using the enterprise version, you will use the `next` parameter to paginate, the next token field will be called `next`, and it will be located at the root in the response.
If you are using v2, you can use either the `next_token` or `pagination_token` parameter to paginate, and your next token will be located at `meta.next_token` in the response.
**Timezone**
As noted in the pagination section, you can navigate different pages of data using time for both enterprise and v2. In both cases, you will be using UTC as the timezone when using these parameters.
#### Differences
**Endpoint URLs**
* Enterprise endpoints:
* 30 day - `http://gnip-api.x.com/search/30day/accounts/:account_name/:label/counts.json`
* Full-archive - `http://gnip-api.x.com/search/fullarchive/accounts/:account_name/:label/counts.json`
* X API v2 endpoints
\*
# Overview
Source: https://docs.x.com/enterprise-api/posts/counts/migrate/overview
The v2 Post counts endpoint will eventually replace the enterprise Search API’s counts endpoint. Reference for the Enterprise X API tier covering migrate.
## Comparing X API’s Post counts endpoints
The v2 Post counts endpoint will eventually replace the [enterprise Search API’s counts endpoint](/x-api/enterprise-gnip-2.0/fundamentals/search-api#counts-requests-post-count). If you have code, apps, or tools that use an older version of a Post counts endpoint and are considering migrating to the newer X API v2 endpoints, then this guide is for you.
***
## Recent Post counts comparison
The enterprise version of the Post counts endpoints allow you to pull counts for either 30 days or from the full-archive. Therefore, the v2 recent Post counts endpoint, which looks at a 7 day time period, is not a direct replacement for either of the aforementioned endpoints.
However, to help with comparisons, we will look at how the v2 recent Post counts endpoint compares to the enterprise 30-day endpoint.
The following table compares the various types of recent Post counts endpoints:
| **Description** | **Enterprise** | **X API v2** |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------- |
| Host domain | [https://gnip-api.x.com](https://gnip-api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /search/30day/accounts/:account\_name/:label/counts.json | /2/tweets/counts/recent |
| [Authentication](/resources/fundamentals/authentication) | Basic authentication | OAuth 2.0 Bearer Token |
| Timestamp format | YYYYMMDDhhmm | YYYY-MM-DDTHH:mm:ssZ [ISO 8601 / RFC 3339](https://tools.ietf.org/html/rfc3339#section-5.6) |
| Returns counts of Posts that are no older than | 31 days | 7 days |
| HTTP methods supported | GET | GET |
| Default request rate limits | 20 requests per 1 sec, aggregated across search data and counts requests The per minute rate limit will vary by partner as specified in your contract. | 180 requests per 15 min per user 450 requests per 15 min per App |
| Supports filtering using [annotations](/x-api/fundamentals/post-annotations) | | ✔ |
| Supports filtering using [conversation\_id](/x-api/fundamentals/conversation-id) | | ✔ |
| JSON key name for Post data array | results | data |
| Time granularity | Day, hour, or minute | Day, hour, or minute |
| Timezone | UTC | UTC |
| Request parameters for selecting time period | fromDate toDate | start\_time end\_time |
| Request parameters for navigating by Post ID | | since\_id until\_id |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [project](/resources/fundamentals/developer-apps) | | ✔ |
### Full-archive Post counts comparison
The following table compares the various types of full-archive search endpoints:
| Description | Enterprise | X API v2 |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |
| Host domain | [https://gnip-api.x.com](https://gnip-api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /search/fullarchive/accounts/:account\_name/:label/counts | /2/tweets/counts/all |
| [Authentication](/resources/fundamentals/authentication) | Basic auth | OAuth 2.0 Bearer Token |
| Timestamp format | YYYYMMDDHHMM | YYYY-MM-DDTHH:mm:ssZ [ISO 8601 / RFC 3339](https://tools.ietf.org/html/rfc3339#section-5.6) |
| Returns Post counts that are no older than | The full archive since March 2006 | The full archive since March 2006 |
| HTTP methods supported | GET POST | GET |
| Default request rate limits | The per minute rate limit will vary by partner as specified in your contract. 20 requests per sec | 300 requests per 15 min per App 1 request per 1 sec per App |
| Granularity | Day, hour, minute | Day, hour, minute |
| Supports filtering using [annotations](/x-api/fundamentals/post-annotations) | | ✔ |
| Supports filtering using [conversation\_id](/x-api/fundamentals/conversation-id) | | ✔ |
| JSON key name for Post data array | results | data |
| Request parameters for selecting time period | fromDate toDate | start\_time end\_time |
| Request parameters for navigating by Post ID | | since\_id until\_id |
| JSON key name for pagination | next | meta.next\_token |
| Request parameter for pagination | next\_token | next\_token or pagination\_token |
| Timezone | UTC | UTC |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) that has [Academic Research access](/x-api/getting-started/about-x-api) | | ✔ |
### Filtering operator comparison
The two different versions (enterprise, and v2) of Post counts differ in which operators are available, and also have varying levels of operator availability within each version, which are explained below.
Enterprise
* There are no sub-tiers of enterprise operators. All enterprise operators are available to all enterprise users.
X API v2
* **Core:** These operators are available to any v2 user.
* **Advanced:** These operators are only available to users that have been approved for Academic Research access.
You can learn more about each of these sets of operators in their respective guides:
* [Enterprise operators](/x-api/enterprise-gnip-2.0/fundamentals/search-api#building-search-queries)
* [X API v2 operators](/x-api/posts/search/integrate/build-a-query)
Now that we understand these different operator levels within X API v2, here is the table that maps out operator availability for Post counts (note that if the cell is left blank, the operator is not available):
| | Enterprise | v2 |
| :---------------- | :--------- | :--------------------------------------- |
| keyword | Available | Core |
| emoji | Available | Core |
| “exact phrase” | Available | Core |
| # | Available | Core |
| \$ | Available | Advanced |
| @ | Available | Core |
| from: | Available | Core |
| to: | Available | Core |
| url: | Available | Core |
| retweets\_of: | Available | Core |
| context: | | Core |
| entity: | | Core - Only available with recent search |
| conversation\_id: | | Core |
| place: | Available | Advanced |
| place\_country: | Available | Advanced |
| point\_radius: | Available | Advanced |
| bounding\_box: | Available | Advanced |
| is:retweet | Available | Core |
| is:reply | Available | Core |
| is:quote | Available | Core |
| is:verified | Available | Core |
| -is:nullcast | Available | Advanced |
| has:hashtags | Available | Core |
| has:cashtags | Available | Advanced |
| has:links | Available | Core |
| has:mentions | Available | Core |
| has:media | Available | Core |
| has:images | Available | Core |
| has:videos | Available | Core |
| has:geo | Available | Advanced |
| lang: | Available | Core |
| list: | | Advanced |
| has:profile\_geo | Available | |
| profile\_country | Available | |
| profile\_locality | Available | |
| profile\_region | Available | |
| proximity | Available | |
**Other migration resources**
[X API migration hub](/x-api/migrate/overview)
[Check out some sample code for these endpoints](https://github.com/xdevplatform/Twitter-API-v2-sample-code "Check out some sample code for these endpoints")
[Post counts: Enterprise to X API v2](/x-api/posts/counts/migrate/overview)
# Full-Archive Post Counts
Source: https://docs.x.com/enterprise-api/posts/counts/quickstart/full-archive-tweet-counts
This guide walks you through getting historical Post counts back to March 2006. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through getting historical Post counts back to March 2006.
Full-archive Post counts requires [Self-serve](/x-api/getting-started/about-x-api) or [Enterprise](/x-api/getting-started/about-x-api) access.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with Self-serve or Enterprise access
* Your App's Bearer Token
***
## Get full-archive Post counts
Use the same query syntax as full-archive search. For example, to count Posts from @XDevelopers:
```
from:XDevelopers
```
Specify `start_time` and `end_time` to search specific historical periods:
| Parameter | Format | Example |
| :----------- | :------- | :--------------------- |
| `start_time` | ISO 8601 | `2020-01-01T00:00:00Z` |
| `end_time` | ISO 8601 | `2020-12-31T23:59:59Z` |
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/counts/all?\
query=from%3AXDevelopers&\
start_time=2020-01-01T00%3A00%3A00Z&\
end_time=2020-12-31T23%3A59%3A59Z&\
granularity=day" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get full-archive Post counts
response = client.posts.count_all(
query="from:XDevelopers",
start_time="2020-01-01T00:00:00Z",
end_time="2020-12-31T23:59:59Z",
granularity="day"
)
for bucket in response.data:
print(f"{bucket.start}: {bucket.tweet_count} Posts")
print(f"Total: {response.meta.total_tweet_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get full-archive Post counts
const response = await client.posts.countAll({
query: "from:XDevelopers",
startTime: "2020-01-01T00:00:00Z",
endTime: "2020-12-31T23:59:59Z",
granularity: "day",
});
response.data?.forEach((bucket) => {
console.log(`${bucket.start}: ${bucket.tweet_count} Posts`);
});
console.log(`Total: ${response.meta?.total_tweet_count}`);
```
```json theme={null}
{
"data": [
{
"end": "2020-01-02T00:00:00.000Z",
"start": "2020-01-01T00:00:00.000Z",
"tweet_count": 3
},
{
"end": "2020-01-03T00:00:00.000Z",
"start": "2020-01-02T00:00:00.000Z",
"tweet_count": 5
}
],
"meta": {
"total_tweet_count": 8
}
}
```
***
## Granularity options
Control how counts are grouped:
| Granularity | Description |
| :---------- | :------------------------ |
| `minute` | Counts per minute |
| `hour` | Counts per hour (default) |
| `day` | Counts per day |
***
## Paginate through results
For large time ranges, use the `next_token` from the response:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/counts/all?\
query=from%3AXDevelopers&\
start_time=2015-01-01T00%3A00%3A00Z&\
end_time=2020-12-31T23%3A59%3A59Z&\
granularity=day&\
next_token=abc123" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get counts with pagination
next_token = None
while True:
response = client.posts.count_all(
query="from:XDevelopers",
start_time="2015-01-01T00:00:00Z",
end_time="2020-12-31T23:59:59Z",
granularity="day",
next_token=next_token
)
for bucket in response.data:
print(f"{bucket.start}: {bucket.tweet_count}")
next_token = response.meta.next_token
if not next_token:
break
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get counts with pagination
let nextToken = undefined;
do {
const response = await client.posts.countAll({
query: "from:XDevelopers",
startTime: "2015-01-01T00:00:00Z",
endTime: "2020-12-31T23:59:59Z",
granularity: "day",
nextToken,
});
response.data?.forEach((bucket) => {
console.log(`${bucket.start}: ${bucket.tweet_count}`);
});
nextToken = response.meta?.next_token;
} while (nextToken);
```
***
## Key differences from recent counts
| Feature | Recent Counts | Full-Archive Counts |
| :----------------- | :------------- | :---------------------- |
| Time range | Last 7 days | March 2006 to now |
| Access required | All developers | Pay-per-use, Enterprise |
| Default time range | Last 7 days | Last 30 days |
***
## Common parameters
| Parameter | Description | Default |
| :------------ | :-------------------------- | :---------- |
| `query` | Search query (required) | — |
| `granularity` | Time bucket size | `hour` |
| `start_time` | Oldest timestamp (ISO 8601) | 30 days ago |
| `end_time` | Newest timestamp (ISO 8601) | Now |
| `next_token` | Pagination token | — |
***
## Next steps
Get recent Post counts
Master query syntax
Full endpoint documentation
# Recent Post Counts
Source: https://docs.x.com/enterprise-api/posts/counts/quickstart/recent-tweet-counts
This guide walks you through getting Post counts (volume) for the last 7 days. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through getting Post counts (volume) for the last 7 days.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
## Get recent Post counts
Use the same query syntax as recent search. For example, to count Posts from @XDevelopers:
```
from:XDevelopers
```
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/counts/recent?\
query=from%3AXDevelopers&\
granularity=day" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get recent Post counts
response = client.posts.count_recent(
query="from:XDevelopers",
granularity="day"
)
for bucket in response.data:
print(f"{bucket.start}: {bucket.tweet_count} Posts")
print(f"Total: {response.meta.total_tweet_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get recent Post counts
const response = await client.posts.countRecent({
query: "from:XDevelopers",
granularity: "day",
});
response.data?.forEach((bucket) => {
console.log(`${bucket.start}: ${bucket.tweet_count} Posts`);
});
console.log(`Total: ${response.meta?.total_tweet_count}`);
```
```json theme={null}
{
"data": [
{
"end": "2024-01-16T00:00:00.000Z",
"start": "2024-01-15T00:00:00.000Z",
"tweet_count": 5
},
{
"end": "2024-01-17T00:00:00.000Z",
"start": "2024-01-16T00:00:00.000Z",
"tweet_count": 3
},
{
"end": "2024-01-18T00:00:00.000Z",
"start": "2024-01-17T00:00:00.000Z",
"tweet_count": 8
}
],
"meta": {
"total_tweet_count": 16
}
}
```
***
## Granularity options
Control how counts are grouped:
| Granularity | Description |
| :---------- | :------------------------ |
| `minute` | Counts per minute |
| `hour` | Counts per hour (default) |
| `day` | Counts per day |
```bash cURL theme={null}
# Get hourly counts
curl "https://api.x.com/2/tweets/counts/recent?\
query=python%20lang%3Aen&\
granularity=hour" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get hourly counts
response = client.posts.count_recent(
query="python lang:en",
granularity="hour"
)
for bucket in response.data:
print(f"{bucket.start}: {bucket.tweet_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get hourly counts
const response = await client.posts.countRecent({
query: "python lang:en",
granularity: "hour",
});
response.data?.forEach((bucket) => {
console.log(`${bucket.start}: ${bucket.tweet_count}`);
});
```
***
## Filter by time range
Limit counts to a specific time period:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/counts/recent?\
query=from%3AXDevelopers&\
start_time=2024-01-10T00%3A00%3A00Z&\
end_time=2024-01-15T00%3A00%3A00Z&\
granularity=day" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get counts for a specific time range
response = client.posts.count_recent(
query="from:XDevelopers",
start_time="2024-01-10T00:00:00Z",
end_time="2024-01-15T00:00:00Z",
granularity="day"
)
print(f"Total Posts: {response.meta.total_tweet_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get counts for a specific time range
const response = await client.posts.countRecent({
query: "from:XDevelopers",
startTime: "2024-01-10T00:00:00Z",
endTime: "2024-01-15T00:00:00Z",
granularity: "day",
});
console.log(`Total Posts: ${response.meta?.total_tweet_count}`);
```
***
## Common parameters
| Parameter | Description | Default |
| :------------ | :-------------------------- | :--------- |
| `query` | Search query (required) | — |
| `granularity` | Time bucket size | `hour` |
| `start_time` | Oldest timestamp (ISO 8601) | 7 days ago |
| `end_time` | Newest timestamp (ISO 8601) | Now |
***
## Next steps
Get historical Post counts
Master query syntax
Full endpoint documentation
# Create or Edit Post
Source: https://docs.x.com/enterprise-api/posts/create-or-edit-post
post /2/tweets
Creates a new Post for the authenticated user, or edits an existing Post when edit_options are provided. Supports paid partnership disclosure via the paid_partnership field.
# Create or Edit Post
Source: https://docs.x.com/enterprise-api/posts/create-post
post /2/tweets
Creates a new Post for the authenticated user, or edits an existing Post when edit_options are provided. Supports paid partnership disclosure via the paid_partnership field.
# Delete Post
Source: https://docs.x.com/enterprise-api/posts/delete-post
delete /2/tweets/{id}
Deletes a specific Post by its ID, if owned by the authenticated user.
# Build a rule
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/integrate/build-a-rule
Learn how to build Enterprise Filtered Stream rules using operators, conjunctions, negations, and semantic embedding queries to match Posts in real time.
The filtered stream endpoints deliver Posts that match a set of rules applied to the stream. Rules are made up of operators that match on a variety of Post attributes.
Multiple rules can be applied using the [POST /tweets/search/stream/rules](/x-api/stream/update-stream-rules) endpoint. Once you've added rules and connected using [GET /tweets/search/stream](/x-api/stream/get-stream-rules), only Posts matching your rules will be delivered. You do not need to disconnect to add or remove rules.
***
## Rule limitations
Limits on the number of rules depend on your [access level](/x-api/getting-started/about-x-api). See the [filtered stream introduction](/x-api/posts/filtered-stream/introduction) for specific limits.
***
## Operator types: standalone and conjunction-required
**Standalone operators** can be used alone or together with any other operators (including those that require conjunction).
For example, this rule works because `#hashtag` is a standalone operator:
```
#xapiv2
```
**Conjunction-required operators** cannot be used by themselves in a rule; they can only be used when at least one standalone operator is included. This is because using these operators alone would match an extremely high volume of Posts.
For example, the following rules are **not supported** since they contain only conjunction-required operators:
```
has:media
```
```
has:links OR is:retweet
```
```
embedding_threshold:0.45
```
If we add a standalone operator, such as the phrase `"X data"`, the rule works properly:
```
"X data" has:mentions (has:media OR has:links)
```
The `embedding_threshold:` operator (used with semantic `embedding:` rules) is also conjunction-required.
***
## Boolean operators and grouping
String together multiple operators using these tools:
| Operator | Description | Example |
| :------------------------- | :------------------------------------ | :---------------------------------------------------------------------- |
| **AND** (space) | Posts must match both conditions | `snow day #NoSchool` matches Posts with "snow" AND "day" AND #NoSchool |
| **OR** | Posts must match either condition | `grumpy OR cat OR #meme` matches Posts with "grumpy" OR "cat" OR #meme |
| **NOT** (dash) | Exclude Posts matching this condition | `cat #meme -grumpy` matches Posts with "cat" and #meme but NOT "grumpy" |
| **Grouping** (parentheses) | Group operators together | `(grumpy cat) OR (#meme has:images)` matches either group |
**A note on negations**
* All operators can be negated except for `sample:` and `embedding:`
* The operator `-is:nullcast` must always be negated
* Negated operators cannot be used alone
* Do not negate grouped operators. Instead of `skiing -(snow OR day OR noschool)`, use `skiing -snow -day -noschool`
* Writing `-embedding:"query"` is not supported
***
## Order of operations
When combining AND and OR:
1. Operators connected by AND logic are combined first
2. Then, operators connected with OR logic are applied
**Examples:**
| Query | Evaluated as |
| :----------------------- | :------------------------- |
| `apple OR iphone ipad` | `apple OR (iphone ipad)` |
| `ipad iphone OR android` | `(iphone ipad) OR android` |
To eliminate uncertainty, use parentheses:
```
(apple OR iphone) ipad
```
```
iphone (ipad OR android)
```
***
## Punctuation, diacritics, and case sensitivity
**Diacritics:** Filtered stream rules with accents only match Posts that also include the accent. For example, `diacrítica` matches *diacrítica* but **not** *diacritica*.
**Case sensitivity:** All operators are case-insensitive. The rule `cat` matches *cat*, *CAT*, and *Cat*.
**Search Posts behaves differently**
When [building search queries](/x-api/posts/search/integrate/build-a-query), keywords with accents match Posts both with and without the accents. For example, `Diacrítica` matches both *Diacrítica* and *Diacritica*.
***
## Quote Tweet matching
When using filtered stream, operators match on both the Quote Tweet's content **and** the content from the original Post that was quoted.
[Search Posts](/x-api/posts/search/introduction) behaves differently—it only matches on the Quote Tweet's content, not the original Post.
***
## Specificity and efficiency
Using broad operators like a single keyword or hashtag is not recommended—it will match a massive volume of Posts and quickly consume your connection.
**Tips for building effective rules:**
1. **Start specific, then broaden** — Create targeted rules that return relevant results
2. **Use multiple operators** — Combine operators to narrow results
3. **Watch your character count** — The entire rule string counts toward the limit
**Example progression:**
```
# Too broad - 200,000+ Posts per day
happy
# Better - adds language filter and exclusions
(happy OR happiness) lang:en -birthday -is:retweet
# Even better - 59 characters, more specific
(happy OR happiness) place_country:GB -birthday -is:retweet
```
***
## Iteratively building a rule
### Step 1: Start with a basic rule
```
happy OR happiness
```
### Step 2: Test and narrow based on results
We noticed Posts in many languages. Add a language filter:
```
(happy OR happiness) lang:en
```
We're getting birthday wishes. Exclude them and Retweets:
```
(happy OR happiness) lang:en -birthday -is:retweet
```
### Step 3: Broaden for better coverage
We want to capture more sentiment. Add related keywords:
```
(happy OR happiness OR excited OR elated) lang:en -birthday -is:retweet
```
### Step 4: Adjust for trends
Holiday Posts are appearing. Exclude them:
```
(happy OR happiness OR excited OR elated) lang:en -birthday -is:retweet -holidays
```
***
## Adding and removing rules
Use [POST /2/tweets/search/stream/rules](/x-api/stream/update-stream-rules) to add or remove rules.
### Adding rules
Submit an `add` JSON body with the `value` (the rule) and optional `tag` (to identify matching Posts):
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-d '{
"add": [
{"value": "cat has:media", "tag": "cats with media"},
{"value": "cat has:media -grumpy", "tag": "happy cats with media"},
{"value": "meme", "tag": "funny things"},
{"value": "meme has:images"}
]
}'
```
### Removing rules
Submit a `delete` JSON body with the rule IDs to remove:
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-d '{
"delete": {
"ids": [
"1165037377523306498",
"1165037377523306499"
]
}
}'
```
***
## Rule examples
### Tracking a natural disaster
Match Posts from weather agencies about Hurricane Harvey:
```json theme={null}
{
"value": "-is:retweet has:geo (from:NWSNHC OR from:NHC_Atlantic OR from:NWSHouston OR from:NWSSanAntonio OR from:USGS_TexasRain OR from:USGS_TexasFlood OR from:JeffLindner1)",
"tag": "Hurricane Harvey - weather agencies with geo"
}
```
### Sentiment analysis for #nowplaying
**Positive sentiment:**
```json theme={null}
{
"value": "#nowplaying (happy OR exciting OR excited OR favorite OR fav OR amazing OR lovely OR incredible) (place_country:US OR place_country:MX OR place_country:CA) -horrible -worst -sucks -bad -disappointing",
"tag": "#nowplaying positive"
}
```
**Negative sentiment:**
```json theme={null}
{
"value": "#nowplaying (horrible OR worst OR sucks OR bad OR disappointing) (place_country:US OR place_country:MX OR place_country:CA) -happy -exciting -excited -favorite -fav -amazing -lovely -incredible",
"tag": "#nowplaying negative"
}
```
### Using Post annotations
Find Japanese Posts about pets (not cats) with images using the `context:` operator:
First, use [Post lookup](/x-api/posts/lookup/introduction) with `tweet.fields=context_annotations` to identify domain.entity IDs:
* Cats: `domain` 66, `entity` 852262932607926273
* Pets: `domain` 65, `entity` 852262932607926273
```json theme={null}
{
"value": "context:65.852262932607926273 -context:66.852262932607926273 -is:retweet has:images lang:ja",
"tag": "Japanese pets with images - no cats"
}
```
### Semantic matching with embeddings
Use the `embedding:` operator to match Posts by conceptual meaning rather than keywords. This requires Embedding tier access.
```json theme={null}
{
"value": "embedding:\"climate change policy\" embedding_threshold:0.4",
"tag": "climate-semantic"
}
```
Combine with structural operators for precision:
```json theme={null}
{
"value": "embedding:\"quarterly earnings surprises\" lang:en has:links -is:retweet",
"tag": "earnings-en"
}
```
See the [operators reference](/x-api/posts/filtered-stream/integrate/operators) for full details and best practices.
***
## Next steps
Complete list of available operators
Connect to your stream
Code examples in multiple languages
# Matching Posts to Rules
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/integrate/matching-returned-tweets
Map Posts delivered by Enterprise Filtered Stream back to the rules they matched, including embedding_similarity scores for semantic embedding rules.
### Matching returned Posts to their associated rule
The filtered stream endpoint gives you the ability to have multiple rules in place through a single connection. Before you start receiving Posts in your stream, you’ll need to create a rule which specifies what types of Posts you’re interested in.
When you specify your rules to match Posts based on a wide variety of attributes, including user attributes, geo-location, language, and many others, you can attach a tag to distinguish this rule at a higher level. Tags are a good way to contextualize your rule, especially if you have many rules in place. The filtering rules determine which Post activities will be sent through the connection.
If you need to add a new filtering rule to capture a different type of Post, or remove an existing rule, your app can send a request to the [POST tweets/search/stream/rules](/x-api/stream/update-stream-rules) endpoint to make it happen. When that request is sent, the filtering rules are automatically modified and the changes simply take effect in the data stream with no need to reconnect. Most rule additions take effect about 20 seconds or less. It’s unlikely, but depending on external factors (for example, network connectivity), it may take longer before you start receiving matching Posts. If you can’t find a rule in the list rule endpoint, make sure that the rule creation request succeeded; this can be done by checking your logs for any error messages.
#### Matching rules
When an activity is delivered through your filtered stream connection, in a matching\_rules array, it contains which list of filters matched against the Post delivered.
In the Post payload there is additional string metadata which includes the rule id and tag that caused a specific Post to be delivered. If multiple rules match a single Post, the activity is delivered a single time with each of the matching rules included in this metadata. The matching rules provide an easy way to associate a specific Post with specific rules, which is especially helpful if you have many distinct rules. Since the data is delivered through a single stream in this manner, ensuring you have unique id and tag is essential for matching.
**Here is an example of how the "matching\_rules" array appears in the Post payload:**
```json theme={null}
"matching_rules": [
{
"id": "1166916266197536768",
"tag": "test-rule-tag-00000"
},
{
"id": "1166916266197536769",
"tag": "test-rule-tag-12345"
}
]
```
#### Embedding rule matches
When a Post matches a rule containing the `embedding:` operator, the `matching_rules` entry for that rule includes two additional fields (only present for embedding-based matches):
| Field | Description |
| :--------------------- | :----------------------------------------------------------------------------------- |
| `embedding_similarity` | The cosine similarity score (0.0–1.0) between the rule's query and the matched Post. |
| `embedding_threshold` | The threshold applied (your value or the default `0.3`). |
Example payload excerpt for an embedding match:
```json theme={null}
{
"data": {
"id": "1784600000000000001",
"text": "The new carbon tax proposal could reshape how industries approach emissions..."
},
"matching_rules": [
{
"id": "1784567890123456789",
"tag": "climate-semantic",
"embedding_similarity": 0.4523,
"embedding_threshold": 0.4
}
]
}
```
For keyword, `from:`, `has:`, and other non-embedding rules, `matching_rules` entries contain only `id` and `tag`.
#### Rule tags
At the time they are created, each filtering rule may be created with a tag. Rule tags have no special meaning as they are simply treated as opaque strings carried along with a rule. They will be included in the matching\_rules metadata in activities returned, and are aimed at making distinguishing your rules easier at a higher level.
Tags provide an easy way to create logical groupings of filtering rules. For example, you may generate a unique ID for a specific rule as its tag, and allow your app to reference that ID within activities it processes to associate a result with specific customers, campaigns, categories, or other related groups.
Note that tags cannot be updated on an existing rule and can only be included when a rule is created. In order to “update” or “rename” a tag, you need to first delete the rule, then add it again with the desired tag. The best solution is to simply use a unique identifier as your tag, which your system can associate with various other data points within your own app, all without having to change anything in the rule set.
### Filtered stream - Recovery and redundancy features
Note: These recovery and redundancy features are only available to those that have Enterprise access.
# Filtered Stream Operators
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/integrate/operators
Complete Enterprise Filtered Stream operator reference, including keyword, has:, is:, and semantic embedding: operators for matching Posts in real time.
This page provides a complete list of operators available when [building rules](/x-api/posts/filtered-stream/integrate/build-a-rule) for Filtered Stream.
## Overview
Operators are used to match on specific Post attributes. There are two types:
* **Standalone operators** — Can be used alone or with any other operators
* **Conjunction-required operators** — Must be used with at least one standalone operator
Some advanced operators (such as semantic embedding) require Embedding tier access in addition to Enterprise.
***
## Keyword and phrase operators
| Operator | Type | Summary | Example |
| :---------------------- | :--------- | :----------------------------------------------------------------- | :------------------------------------ |
| `keyword` | Standalone | Matches a keyword within the Post body (tokenized match) | `pepsi OR cola OR "coca cola"` |
| `emoji` | Standalone | Matches an emoji within the Post body | `(😃 OR 😡) 😬` |
| `"exact phrase"` | Standalone | Matches the exact phrase within the Post body | `("X API" OR #v2) -"filtered stream"` |
| `"keyword1 keyword2"~N` | Standalone | Proximity match — keywords within N tokens of each other (max N=6) | `"social media"~5` |
***
## Entity operators
| Operator | Type | Summary | Example |
| :------- | :--------- | :----------------------------------------------- | :--------------------------- |
| `#` | Standalone | Matches Posts containing a hashtag (exact match) | `#thankunext #fanart` |
| `@` | Standalone | Matches Posts mentioning a username | `(@XDevelopers OR @api) -@x` |
| `$` | Standalone | Matches Posts containing a cashtag | `$twtr OR @XDevelopers -$fb` |
***
## User operators
| Operator | Type | Summary | Example |
| :------------- | :--------- | :---------------------------------------- | :----------------------------- |
| `from:` | Standalone | Matches Posts from a specific user | `from:XDevelopers OR from:api` |
| `to:` | Standalone | Matches Posts in reply to a specific user | `to:XDevelopers OR to:api` |
| `retweets_of:` | Standalone | Matches Retweets of a specific user | `retweets_of:XDevelopers` |
***
## URL operators
| Operator | Type | Summary | Example |
| :----------------- | :--------- | :-------------------------------------------------------------- | :------------------------------ |
| `url:` | Standalone | Tokenized match on URL (matches `url` or `expanded_url` fields) | `url:"https://developer.x.com"` |
| `url_title:` | — | Keyword match on expanded URL HTML title metadata | `url_title:snow` |
| `url_description:` | — | Keyword match on expanded page description metadata | `url_description:weather` |
| `url_contains:` | — | Literal match on URL content | `url_contains:photos` |
***
## Context and entity operators
| Operator | Type | Summary | Example |
| :----------------- | :--------- | :------------------------------------------------ | :------------------------------------------------ |
| `context:` | Standalone | Matches Posts with a specific domain/entity pair | `context:10.799022225751871488` or `context:47.*` |
| `entity:` | Standalone | Matches Posts with a specific entity string value | `entity:"Michael Jordan"` |
| `conversation_id:` | Standalone | Matches Posts in a conversation thread | `conversation_id:1334987486343299072` |
***
## User profile operators
| Operator | Type | Summary | Example |
| :-------------- | :--------- | :---------------------------------------- | :--------------------------------------------- |
| `bio:` | Standalone | Matches keyword in Post author's bio | `bio:developer OR bio:"data engineer"` |
| `bio_name:` | Standalone | Matches keyword in Post author's name | `bio_name:phd OR bio_name:md` |
| `bio_location:` | Standalone | Matches keyword in Post author's location | `bio_location:"big apple" OR bio_location:nyc` |
***
## Location operators
| Operator | Type | Summary | Example |
| :--------------- | :--------- | :--------------------------------------- | :---------------------------------------------------------- |
| `place:` | Standalone | Matches Posts tagged with a location | `place:"new york city" OR place:seattle` |
| `place_country:` | Standalone | Matches Posts with a country code | `place_country:US OR place_country:MX` |
| `point_radius:` | Standalone | Matches Posts within a radius of a point | `point_radius:[2.355128 48.861118 16km]` |
| `bounding_box:` | Standalone | Matches Posts within a bounding box | `bounding_box:[-105.301758 39.964069 -105.178505 40.09455]` |
***
## Post type operators
| Operator | Type | Summary | Example |
| :------------- | :------------------- | :------------------------------------------- | :------------------------------ |
| `is:retweet` | Conjunction required | Matches Retweets | `data @XDevelopers -is:retweet` |
| `is:reply` | Conjunction required | Matches replies | `from:XDevelopers is:reply` |
| `is:quote` | Conjunction required | Matches Quote Tweets | `"sentiment analysis" is:quote` |
| `is:verified` | Conjunction required | Matches Posts from verified authors | `#nowplaying is:verified` |
| `-is:nullcast` | Conjunction required | Excludes promotional Posts (must be negated) | `"mobile games" -is:nullcast` |
***
## Content type operators
| Operator | Type | Summary | Example |
| :--------------- | :------------------- | :------------------------------------------- | :----------------------------------- |
| `has:hashtags` | Conjunction required | Matches Posts with hashtags | `from:XDevelopers -has:hashtags` |
| `has:cashtags` | Conjunction required | Matches Posts with cashtags | `#stonks has:cashtags` |
| `has:links` | Conjunction required | Matches Posts with links | `from:XDevelopers has:links` |
| `has:mentions` | Conjunction required | Matches Posts with mentions | `#nowplaying has:mentions` |
| `has:media` | Conjunction required | Matches Posts with media (photo, GIF, video) | `(kittens OR puppies) has:media` |
| `has:images` | Conjunction required | Matches Posts with images | `#meme has:images` |
| `has:video_link` | Conjunction required | Matches Posts with native X videos | `#icebucketchallenge has:video_link` |
| `has:geo` | Conjunction required | Matches Posts with geolocation data | `recommend #paris has:geo` |
***
## Sampling and language operators
| Operator | Type | Summary | Example |
| :-------- | :------------------- | :---------------------------------------------- | :------------------------------- |
| `sample:` | Conjunction required | Returns a random percent sample (1-100) | `#nowplaying @spotify sample:15` |
| `lang:` | Conjunction required | Matches Posts classified as a specific language | `recommend #paris lang:en` |
***
## User metrics operators
| Operator | Type | Summary | Example |
| :----------------- | :--- | :----------------------------------------------------- | :---------------------------- |
| `followers_count:` | — | Matches Posts from users with follower count in range | `followers_count:1000..10000` |
| `tweets_count:` | — | Matches Posts from users with Post count in range | `tweets_count:1000..10000` |
| `following_count:` | — | Matches Posts from users with following count in range | `following_count:1000..10000` |
| `listed_count:` | — | Matches Posts from users in specified number of Lists | `listed_count:10..100` |
***
## Post reference operators
| Operator | Type | Summary | Example |
| :---------------------- | :--- | :----------------------------------------------- | :----------------------------------------- |
| `in_reply_to_tweet_id:` | — | Matches replies to a specific Post | `in_reply_to_tweet_id:1539382664746020864` |
| `retweets_of_tweet_id:` | — | Matches Retweets of a specific Post | `retweets_of_tweet_id:1539382664746020864` |
| `source:` | — | Matches Posts from a specific source application | `source:"X for iPhone"` |
***
## Logical operators
| Operator | Summary | Example |
| :---------- | :------------------------------- | :------------------------- |
| `OR` | Logical OR between expressions | `cat OR dog` |
| Space (AND) | Logical AND between expressions | `cat dog` (both required) |
| `()` | Grouping for complex expressions | `(cat OR dog) -is:retweet` |
| `-` | Negation/exclusion | `cat -grumpy` |
***
## Semantic operators
**Requires Embedding tier**
The `embedding:` and `embedding_threshold:` operators require Embedding tier access on your Enterprise Filtered Stream instance. If not provisioned, rule creation will fail with an "'embedding' is not an available operator" error.
These operators use a neural embedding model to match Posts by *semantic similarity* to a query, rather than requiring exact keyword matches.
| Operator | Type | Summary | Example |
| :------------------------- | :------------------- | :---------------------------------------------------------------------------------------------- | :--------------------------------------------------------------- |
| `embedding:"query"` | Standalone | Matches Posts semantically similar to the query. Multi-word queries must be quoted. | `embedding:"climate change policy"` |
| `embedding_threshold:X.XX` | Conjunction required | Minimum cosine similarity for a match (0.0–1.0). Defaults to `0.3`. Use values between 0.3–0.6. | `embedding:"cryptocurrency regulation" embedding_threshold:0.45` |
### Key requirements and notes
* `embedding_threshold:` **cannot** be the only operator in a rule. Pair it with `embedding:` (or another standalone operator).
* **Do not negate** `embedding:` (e.g. `-embedding:"..."` is unsupported).
* Longer, descriptive natural language queries produce better results than short keywords.
* Embedding query processing is asynchronous — newly created rules may take a few seconds before they begin matching.
* When a Post matches via an embedding rule, the delivered payload's `matching_rules` entries will contain `embedding_similarity` and `embedding_threshold` (see [Matching Posts to Rules](/x-api/posts/filtered-stream/integrate/matching-returned-tweets)).
**Example rules:**
* `embedding:"electric vehicle announcements" lang:en -is:retweet has:links`
* `embedding:"natural disaster relief" embedding_threshold:0.45 has:media`
* `embedding:"renewable energy" embedding_threshold:0.4 OR embedding:"solar power investment"`
***
## Supported languages
The `lang:` operator supports these BCP 47 language codes:
| Language | Code | Language | Code | Language | Code |
| :-------- | :--- | :--------- | :--- | :------------------ | :------ |
| Amharic | `am` | Greek | `el` | Portuguese | `pt` |
| Arabic | `ar` | Gujarati | `gu` | Romanian | `ro` |
| Armenian | `hy` | Hebrew | `iw` | Russian | `ru` |
| Basque | `eu` | Hindi | `hi` | Serbian | `sr` |
| Bengali | `bn` | Hungarian | `hu` | Simplified Chinese | `zh-CN` |
| Bulgarian | `bg` | Indonesian | `in` | Slovak | `sk` |
| Catalan | `ca` | Italian | `it` | Slovenian | `sl` |
| Croatian | `hr` | Japanese | `ja` | Spanish | `es` |
| Czech | `cs` | Kannada | `kn` | Swedish | `sv` |
| Danish | `da` | Korean | `ko` | Tamil | `ta` |
| Dutch | `nl` | Latvian | `lv` | Telugu | `te` |
| English | `en` | Lithuanian | `lt` | Thai | `th` |
| Estonian | `et` | Malayalam | `ml` | Traditional Chinese | `zh-TW` |
| Finnish | `fi` | Marathi | `mr` | Turkish | `tr` |
| French | `fr` | Norwegian | `no` | Ukrainian | `uk` |
| German | `de` | Persian | `fa` | Urdu | `ur` |
| Georgian | `ka` | Polish | `pl` | Vietnamese | `vi` |
***
## Next steps
Learn rule syntax and best practices
Get started with Filtered Stream
Handle streaming disconnections
# Filtered Stream
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/introduction
Stream Posts in near real time with Enterprise Filtered Stream, featuring higher rule limits and semantic embedding operators for conceptual matching.
The Filtered Stream endpoints let you receive near real-time Posts that match your filter rules. Enterprise customers get higher rule limits plus semantic embedding operators (for Filtered Stream only) to match by conceptual similarity. Create rules using powerful operators, then connect to a persistent stream to receive matching Posts as they're published.
Filtered Stream prioritizes data hydration and delivery, with approximately 6-7 seconds of P99 latency. For lower latency requirements, see [Powerstream](/x-api/powerstream/introduction).
## Overview
Receive Posts within seconds of publication
Add and remove rules without disconnecting
Match on keywords, hashtags, users, and semantic similarity via `embedding:` (Enterprise + Embedding tier)
Optionally receive Posts via webhooks
***
## How it works
1. **Create rules** — Define filter rules using operators
2. **Connect to stream** — Establish a persistent HTTP connection
3. **Receive Posts** — Get matching Posts in near real-time
```mermaid actions={false} theme={null}
flowchart LR
A["Create/manage rules"] --> B["Connect to streaming endpoint"] --> C["Receive matching Posts"]
```
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------------- | :-------------------- |
| GET | [`/2/tweets/search/stream`](/x-api/stream/stream-filtered-posts) | Connect to the stream |
| POST | [`/2/tweets/search/stream/rules`](/x-api/stream/update-stream-rules) | Add or delete rules |
| GET | [`/2/tweets/search/stream/rules`](/x-api/stream/get-stream-rules) | List current rules |
***
## Access levels
| Feature | Pay-per-use | Enterprise |
| :--------------------------- | :---------- | :-------------------------- |
| Rules per project | 1,000 | 25,000+ |
| Rule length | 1,024 chars | 2,048 chars |
| Connections | 1 | Multiple |
| Core operators | ✓ | ✓ |
| Semantic embedding operators | — | ✓ (requires Embedding tier) |
Get higher limits and additional features
The `embedding:` semantic operator is available **only for Filtered Stream**. It requires Embedding tier access in addition to Enterprise. If your Filtered Stream instance is not provisioned for the Embedding tier, attempts to use it will return an "unavailable operator" error.
***
## Building rules
Rules use the same operators as search queries:
```
(AI OR "machine learning") lang:en -is:retweet
```
### Example rules
| Rule | Matches |
| :---------------------------------- | :---------------------------------------------------------------- |
| `#python` | Posts with #python hashtag |
| `from:elonmusk` | Posts by @elonmusk |
| `"breaking news" has:images` | Posts with phrase and images |
| `(@XDevelopers OR @X) -is:retweet` | Mentions, excluding retweets |
| `embedding:"climate change policy"` | Posts semantically about climate policy (requires Embedding tier) |
Learn rule syntax and operators
***
## Connecting to the stream
Establish a persistent HTTP connection to receive Posts:
```python theme={null}
import requests
def stream_posts(bearer_token):
url = "https://api.x.com/2/tweets/search/stream"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers, stream=True)
for line in response.iter_lines():
if line:
print(line.decode("utf-8"))
```
### Keep-alive signals
The stream sends blank lines (`\r\n`) every 20 seconds to maintain the connection. If you don't receive data or a keep-alive for 20 seconds, reconnect.
Reconnect gracefully
Process Posts efficiently
***
## Webhook delivery
Instead of maintaining a persistent connection, you can receive Posts via webhooks:
Set up webhook delivery for filtered stream
***
## Post edits
The stream delivers edited Posts with their edit history. Each edit creates a new Post ID:
```json theme={null}
{
"data": {
"id": "1234567893",
"text": "Hello world! (edited)",
"edit_history_tweet_ids": ["1234567890", "1234567891", "1234567893"]
}
}
```
Learn more about Post edits
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [Bearer Token](/resources/fundamentals/authentication)
Connect to the stream in minutes
Learn rule syntax
All available operators
Working code examples
***
## Advanced topics
Reconnect gracefully
Handle high throughput
Build resilient applications
Identify which rules matched
# Enterprise filtered stream v2 migration
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/migrate/overview
Compare filtered stream endpoints across Standard v1.1, PowerTrack, and X API v2, and plan a migration of your real-time streaming integration.
## Comparing X API's filtered stream endpoints
The v2 filtered stream endpoints group is replacing the [standard v1.1 statuses/filter](https://developer.x.com/en/docs/x-api/v1/tweets/filter-realtime/api-reference/post-statuses-filter) and [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api). If you have code, apps, or tools that use an older version of the filtered stream endpoint, and are considering migrating to the newer X API v2 endpoint, then this comparison can help you get started.
See our more in depth migration guides for:
[Migrating from Standard v1.1 compared to X API v2](x-api/posts/filtered-stream#standard-v1-1-compared-to-x-api-v2)
[Migrating from PowerTrack API migration to X API v2](/x-api/enterprise-gnip-2.0/powertrack-api#powertrack-operators)
The following table compares the filtered streaming endpoints X offers:
| **Description** | **Standard v1.1** | **PowerTrack API** | **X API v2** |
| :------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Access | X App | Requires an enterprise contract and account | Requires a developer account ([sign up](https://developer.x.com/en/portal/petition/essential/basic-info)), and [X App](/resources/fundamentals/developer-apps) within a [Project](/resources/fundamentals/developer-apps) |
| :--- | :--- | :--- | :--- |
| Host domain | **[https://stream.x.com](https://stream.x.com)** | **[https://gnip-stream.x.com](https://gnip-stream.x.com)** | **[https://api.x.com](https://api.x.com)** |
| Endpoint path | **1.1/statuses/filter.json** | **/stream/powertrack/accounts//publishers/twitter/.json**
**/2/tweets/search/stream/rules** |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | HTTP Basic Authentication | OAuth 2.0 App-Only |
| HTTP methods supported | POST | GET POST | GET POST |
| Required parameters | Rule defined on connection as parameter, at least one of:
\* **follow** \* **track** \* **locations** | No required parameters for streaming connection, optional backfill parameter.
Rules managed separately | No required parameters for streaming connection, optional parameters to define response format and add [backfill recovery feature](/x-api/fundamentals/recovery-and-redundancy) for Academic Research access.
REST (for rules management) |
| Default request rate limits | 5 connection attempts per 5 min | 60 requests per min aggregated for both POST and GET requests
/rules: 60 requests per minute, aggregated across all requests to /rules endpoint for the specific stream's API (POST and GET). | Depends on the endpoint. See [rate limits](/x-api/fundamentals/rate-limits) for current limits. |
| Maximum allowed connections | 2 concurrent per authorized user | Supports multiple/redundant connections, determined by contract | Pay-per-use: 1 |
| [Recovery and redundancy features](/x-api/fundamentals/recovery-and-redundancy) | None | Backfill, redundant connections, and the Replay API | |
| Keep-alive signal/heartbeats | blank lines (\r\n or similar) at least every 20 seconds | blank lines (\r\n or similar) every 10 seconds | blank lines (\r\n or similar) at least every 20 seconds |
| Latency | 10 seconds | 2 seconds
At least 10 seconds for URL unwinding enrichment | 10 seconds |
| Maximum allowed rules | 1 rule (within the endpoint connection request) | Determined by contract up to 250,000 | Pay-per-use: 1,000 rules |
| Rule filter limitations | One query per connection, up to either:
- 400 track keywords
- 5000 follow user IDs
- 25 location boxes | Up to 2,048 characters per rule | Pay-per-use: 1,024 characters per rule |
| [Post JSON format](/x-api/fundamentals/data-dictionary) | Standard v1.1 format | [Native Enriched](/x-api/enterprise-gnip-2.0/fundamentals/data-dictionary#native-enriched-tweet-object) or Activity Streams (selected within the [console](/x-api/enterprise-gnip-2.0/fundamentals/overview)) | [X API v2 format](/x-api/fundamentals/data-dictionary) (determined by **fields** and **expansions** request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). We will be releasing additional data format migration guides for Native Enriched and Activity Streams soon. |
| Provides Post edit history and metadata | ✔ | ✔ | ✔ |
| Unique Features | Filtering done via query parameters on connection request
No configuration UI | Filtering done via rules created through an independent endpoint
[Enrichment](/x-api/enterprise-gnip-2.0/enterprise-gnip#enrichments) features available in contract
Configuration on console.gnip.com UI | Filtering done via [rules](/x-api/posts/filtered-stream/integrate/build-a-rule) created through an independent endpoint
[Metrics](/x-api/fundamentals/metrics) and URL enrichment features included
Object [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) specified with request parameters
Post [Annotations](/x-api/fundamentals/post-annotations)
[Conversation ID](/x-api/fundamentals/conversation-id) operator and field
Configuration through [Developer Console](/resources/fundamentals/developer-portal) |
# v1 to v2 (Enterprise)
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/migrate/powertrack-api-migration-to-twitter-api-v2
Use this migration guide to understand the similarities and differences between PowerTrack API and. Reference for the Enterprise X API tier covering migrate.
### PowerTrack API migration to X API v2 filtered stream
Use this migration guide to understand the similarities and differences between [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) and X API v2 [filtered stream](/x-api/posts/filtered-stream), and to help migrate a current PowerTrack API integration to v2 filtered stream.
* **Similarities**
* Streaming delivery method
* Integration process
* Persistent stream connection with separate rules management endpoints
* Rule syntax
* Rule operators (with exceptions)
* Rule matching logic
* Support for Post edit history and metadata
* **Differences**
* Rule length
* Rule volume
* Endpoint URLs
* App and Project requirement for access
* Authentication method
* Request parameters
* Usage tracking
* Multiple streams, redundant conections, backfill and Replay recovery
* Request parameters and response format
* Response JSON data structure
#### Similarities
**Streaming delivery method**
Both PowerTrack and X API v2 filtered stream use streaming data delivery, which require the client to establish an open connection to an endpoint and keeping a very long lived HTTP request, and parsing the response incrementally from the server in real time. Both PowerTrack and X API v2 filtered stream filter publicly available Posts matching rules that exist on the stream in real time, and use keep-alive signals as new line characters (\r\n) to signal the connection is still active. Both PowerTrack and X API v2 filtered stream endpoint connections deliver data in real time and should be read by the connecting client quickly.
**Integration process**
Integrating with filtered stream is similar to integrating with P
# v1 to v2
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/migrate/standard-to-twitter-api-v2
If you have been working with the v1.1 statuses/filter endpoint, this guide can help you. Reference for the Enterprise X API tier covering migrate.
### Standard v1.1 compared to X API v2
If you have been working with the v1.1 [statuses/filter](https://developer.x.com/en/docs/x-api/v1/tweets/filter-realtime/api-reference/post-statuses-filter) endpoint, this guide can help you understand the similarities and differences between the standard and X API v2 filtered stream endpoints.
* **Similarities**
* Request parameters and operators
* Support for Post edit history and metadata
* **Differences**
* Endpoint URLs
* App and Project requirement
* Authentication method
* Rule volume and persistent stream
* Response data format
* Request parameters
* Availability of recovery and redundancy features
* Query operators
#### Similarities
**Request parameters and operators**
The standard v1.1 statuses/filter endpoint features a few parameters that can be passed along with the request to filter the stream. With v2 filtered stream, you instead use a set of [operators](/x-api/posts/filtered-stream/integrate/operators) that can be connected together using boolean logic to filter for desired Posts. The available operators include some that are direct replacements for the existing standard v1.1 parameters.
The following standard v1.1 request parameters have equivalent operators in X API v2:
| **Standard** | **X API v2** |
| :-------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- |
| follow - A comma-separated list of user IDs, indicating the users whose Posts should be delivered on the stream. | Many operators that can help you find Posts related to specific users:
\* @ \* from: \* to: \* etc. |
| track - A comma-separated list of phrases which will be used to determine what Posts will be delivered on the stream. | Many operators that can help you find Posts related to specific keywords:
\* keyword \* "exact phrase match" \* # \* etc. |
**Support for Post edit history and metadata**
Both versions provide metadata that describes any edit history. Check out the [filtered stream API References](/x-api/posts/filtered-stream/introduction) and the [Post edits fundamentals page](/x-api/fundamentals/edit-posts) for more details.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* [https://stream.x.com/1.1/statuses/filter.json](https://stream.x.com/1.1/statuses/filter.json)
* X API v2 endpoint:
* [https://api.x.com/2/tweets/search/stream](https://api.x.com/2/tweets/search/stream)
* [https://api.x.com/2/tweets/search/stream/rule](https://api.x.com/2/tweets/search/stream/rule)
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated to a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps associated with an App.
**Authentication method**
The standard endpoint supports [OAuth 1.0a User Context](/resources/fundamentals/authentication), whereas the X API v2 filtered stream endpoints support [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) (also referred to as Application-only authentication). To make requests to the X API v2 version you must use an App Access Token to authenticate your requests.
If you no longer have the App Access Token that was presented to you when you created your App and app in the Developer Console, you can generate a new one by navigating to your app's “Keys and tokens” page on the Developer Console. If you’d like to generate an App Access Token programmatically, see this [OAuth 2.0 App-Only guide](/resources/fundamentals/authentication#app-only-authentication-and-oauth-2-0-bearer-token).
**Rule volume and persistent stream**
The standard v1.1 endpoint supports a single rule to filter the streaming connection. To change the rule, you have to disconnect the stream and submit a new request with the revised filtering rules submitted as parameters.
The X API v2 filtered stream endpoint allows you to apply multiple rules to a single stream and add and remove rules to your stream while maintaining the stream connection.
**Response data format**
One of the biggest differences between standard v1.1 and X API v2 endpoint versions is how you select which fields return in your payload.
For the standard endpoints, you receive many of the response fields by default, and then have the option to use parameters to identify which fields or sets of fields should return in the payload.
The X API v2 version only delivers the Post id and text fields by default. To request any additional fields or objects, you will need to use the [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) parameters. Any Post fields that you request from these endpoints will return in the primary Post object. Any expanded user, media, poll, or place objects and fields will return in an includes object within your response. You can then match any expanded objects back to the Post object by matching the IDs located in both the Post and the expanded object.
We encourage you to read more about these new parameters in their respective guides, or by reading our guide on [how to use fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions).
We have also put together a [data format migration guide](/x-api/migrate/data-format-migration#migrating-from-standard-v1-1s-data-format-to-v2) which can help you map standard v1.1 fields to the newer v2 fields. This guide will also provide you the specific expansion and field parameter that you will need to pass with your v2 request to return specific fields.
In addition to the changes in how you request certain fields, X API v2 is also introducing new JSON designs for the objects returned by the APIs, including Post and [user](/x-api/fundamentals/data-dictionary/reference#user) objects.
* At the JSON root level, the standard endpoints return Post objects in a statuses array, while X API v2 returns a data array.
* Instead of referring to Retweeted and Quoted "statuses", X API v2 JSON refers to Retweeted and Quoted Tweets. Many legacy and deprecated fields, such as contributors and user.translator\_type are being removed.
* Instead of using both favorites (in Post object) and favourites (in user object), X API v2 uses the term like.
* X is adopting the convention that JSON values with no value (for example, null) are not written to the payload. Post and user attributes are only included if they have a non-null values.
We also introduced a new set of fields to the [Post object](/x-api/fundamentals/data-dictionary/reference#tweet) including the following:
* A [conversation\_id](/x-api/fundamentals/conversation-id) field
* Two new [annotations](/x-api/fundamentals/post-annotations) fields, including context and entities
* Several new [metrics](/x-api/fundamentals/metrics) fields
* A new reply\_setting field, which shows you who can reply to a given Post
**Request parameters**
There are also a set of standard filtered stream request parameters **not** supported in X API v2:
| Standard v1.1 parameter | Details |
| :-------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| locations - A comma-separated list of longitude,latitude pairs specifying a set of bounding boxes to filter Posts by. | We have not released location-based operators for X API v2 yet. |
| Delimited | With the v1.1 endpoint, setting this to the string length indicates that statuses should be delimited in the stream, so that clients know how many bytes to read before the end of the status message.
This functionality is not available with X API v2. |
| Stall\_warnings | With the v1.1 endpoint, setting this parameter to true will cause periodic messages to be delivered if the client is in danger of being disconnected.
With X API v2, stall warnings are sent by default with the new line sent every so often. |
**Availability of recovery and redundancy features**
The X API v2 version of filtered stream introduces recovery and redundancy features that can help you maximize streaming up-time as well as recover any Posts that might have been missed due to a disconnection that lasted five minutes or less.
Redundant connections allows you to connect to a given stream up to two times, which can help ensure that you maintain a connection to the stream at all times, even if one of your connections fails.
The backfill\_minutes parameter can be used to recover up to five minutes of missed data.
Both of these features are only available via [Academic Research access](/x-api/getting-started/about-x-api). You can learn more about this functionality via our [recovery and redundancy features](/x-api/fundamentals/recovery-and-redundancy) integration guide.
**New query operators**
X API v2 introduces new operators in support of two new features:
* **[Conversation IDs](/x-api/fundamentals/conversation-id)** - As conversations unfold on X, a conservation ID will be available to mark Posts that are part of the conversation. All Posts in the conversation will have their conversation\_id set to the Post ID that started it.
* conversation\_id:
* **[X Annotations](/x-api/fundamentals/post-annotations)** provide contextual information about Posts, and include entity and context annotations. Entities are comprised of people, places, products and organizations. Contexts are domains, or topics, that surfaced entities are a part of. For example, people mentioned in a Post may have a context that indicates whether they are an athlete, actor, or politician.
* context: - matches on Posts that have been annotated with a context of interest.
* entity: - matches on Posts that have been annotated with an entity of interest.
***
## Code examples
### Add a rule to filtered stream (v2)
**Standard v1.1 vs v2 examples**
See the full migration examples in the official X API documentation.
# Quickstart
Source: https://docs.x.com/enterprise-api/posts/filtered-stream/quickstart
This guide walks you through connecting to the filtered stream to receive near real-time. Reference for the Enterprise X API tier covering filtered stream.
This guide walks you through connecting to the filtered stream to receive near real-time Posts matching your filter rules.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* Your App's Bearer Token (found in the Developer Console under "Keys and tokens")
***
Rules define which Posts to receive. Use operators to match on keywords, hashtags, users, and more.
**Example rule:** Match Posts containing "cat" with images:
```
cat has:images
```
Learn rule syntax and operators
Add your rule using the rules endpoint. Include a `tag` to identify which rule matched each Post:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"add": [
{"value": "cat has:images", "tag": "cats with images"}
]
}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Add a rule to the filtered stream
response = client.filtered_stream.add_rules(
add=[{"value": "cat has:images", "tag": "cats with images"}]
)
for rule in response.data:
print(f"Rule added: {rule.id} - {rule.value}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Add a rule to the filtered stream
const response = await client.filteredStream.addRules({
add: [{ value: "cat has:images", tag: "cats with images" }],
});
response.data?.forEach((rule) => {
console.log(`Rule added: ${rule.id} - ${rule.value}`);
});
```
**Response:**
```json theme={null}
{
"data": [
{
"id": "1273026480692322304",
"value": "cat has:images",
"tag": "cats with images"
}
],
"meta": {
"sent": "2024-01-15T10:30:00.000Z",
"summary": {
"created": 1,
"not_created": 0,
"valid": 1,
"invalid": 0
}
}
}
```
List all active rules to confirm your rule was added:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get all active rules
response = client.filtered_stream.get_rules()
for rule in response.data:
print(f"Active rule: {rule.id} - {rule.value}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get all active rules
const response = await client.filteredStream.getRules();
response.data?.forEach((rule) => {
console.log(`Active rule: ${rule.id} - ${rule.value}`);
});
```
Open a persistent connection to receive matching Posts:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/search/stream?\
tweet.fields=created_at,author_id&\
expansions=author_id&\
user.fields=username" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Connect to the filtered stream
for post in client.filtered_stream.stream(
tweet_fields=["created_at", "author_id"],
expansions=["author_id"],
user_fields=["username"]
):
print(f"New post: {post.data.text}")
print(f"Matching rules: {post.matching_rules}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Connect to the filtered stream
const stream = client.filteredStream.stream({
tweetFields: ["created_at", "author_id"],
expansions: ["author_id"],
userFields: ["username"],
});
for await (const post of stream) {
console.log(`New post: ${post.data?.text}`);
console.log(`Matching rules: ${post.matching_rules}`);
}
```
Matching Posts stream as JSON objects:
```json theme={null}
{
"data": {
"id": "1234567890",
"text": "Look at this cute cat! 🐱",
"author_id": "9876543210",
"created_at": "2024-01-15T10:35:00.000Z",
"edit_history_tweet_ids": ["1234567890"]
},
"includes": {
"users": [
{
"id": "9876543210",
"username": "catperson"
}
]
},
"matching_rules": [
{
"id": "1273026480692322304",
"tag": "cats with images"
}
]
}
```
The `matching_rules` array shows which rules matched the Post, using the tags you defined.
Remove rules by their ID:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"delete": {
"ids": ["1273026480692322304"]
}
}'
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Delete rules by ID
response = client.filtered_stream.delete_rules(
delete={"ids": ["1273026480692322304"]}
)
print(f"Deleted: {response.meta.summary.deleted}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Delete rules by ID
const response = await client.filteredStream.deleteRules({
delete: { ids: ["1273026480692322304"] },
});
console.log(`Deleted: ${response.meta?.summary?.deleted}`);
```
***
## Managing your connection
The stream sends blank lines (`\r\n`) every 20 seconds. If you don't receive data or a keep-alive for 20 seconds, reconnect.
Press `Ctrl+C` to close the connection, or close your terminal window.
Only one connection per App is allowed. Opening a new connection will close any existing one.
***
## Next steps
Learn rule syntax
All available operators
Reconnect gracefully
Full endpoint documentation
# Get 28-hour Post insights
Source: https://docs.x.com/enterprise-api/posts/get-28-hour-post-insights
get /2/insights/28hr
Retrieves engagement metrics for specified Posts over the last 28 hours.
# Get count of all Posts
Source: https://docs.x.com/enterprise-api/posts/get-count-of-all-posts
get /2/tweets/counts/all
Retrieves the count of Posts matching a search query from the full archive.
# Get count of recent Posts
Source: https://docs.x.com/enterprise-api/posts/get-count-of-recent-posts
get /2/tweets/counts/recent
Retrieves the count of Posts from the last 7 days matching a search query.
# Get historical Post insights
Source: https://docs.x.com/enterprise-api/posts/get-historical-post-insights
get /2/insights/historical
Retrieves historical engagement metrics for specified Posts within a defined time range.
# Get Liking Users
Source: https://docs.x.com/enterprise-api/posts/get-liking-users
get /2/tweets/{id}/liking_users
Retrieves a list of Users who liked a specific Post by its ID.
# Get Post analytics
Source: https://docs.x.com/enterprise-api/posts/get-post-analytics
get /2/tweets/analytics
Retrieves analytics data for specified Posts within a defined time range.
# Get Post by ID
Source: https://docs.x.com/enterprise-api/posts/get-post-by-id
get /2/tweets/{id}
Retrieves details of a specific Post by its ID.
# Get Posts by IDs
Source: https://docs.x.com/enterprise-api/posts/get-posts-by-ids
get /2/tweets
Retrieves details of multiple Posts by their IDs.
# Get Quoted Posts
Source: https://docs.x.com/enterprise-api/posts/get-quoted-posts
get /2/tweets/{id}/quote_tweets
Retrieves a list of Posts that quote a specific Post by its ID.
# Get Reposted by
Source: https://docs.x.com/enterprise-api/posts/get-reposted-by
get /2/tweets/{id}/retweeted_by
Retrieves a list of Users who reposted a specific Post by its ID.
# Get Reposts
Source: https://docs.x.com/enterprise-api/posts/get-reposts
get /2/tweets/{id}/retweets
Retrieves a list of Posts that repost a specific Post by its ID.
# Apps
Source: https://docs.x.com/enterprise-api/posts/hide-replies/apps
Here's a collection of noteworthy apps built by developers who integrated the hide replies. Reference for the Enterprise X API tier covering hide replies.
## Apps using the hide replies endpoint
Here's a collection of noteworthy apps built by developers who integrated the hide replies endpoint. By matching their technology with the X API, they created useful experiences to help all users enhance the public conversation.

**Clarabridge**
Clarabridge integrates hide replies so that companies can keep their X feed clean and interesting to read. Replies can be hidden manually, and agents can also use Clarabridge’s text analytics to automatically detect profanity and other language that is not in line with brand policy.
[Go to website ▸](https://www.clarabridge.com/ "Go to website ▸")
[Clarabridge on X](https://x.com/Clarabridge "Clarabridge on X")

**Perspective API template app**
Perspective is an artificial intelligence trained by Jigsaw (a unit within Alphabet) to detect toxic comments. This app detects a person's incoming replies, and automatically hides a reply based on the “score” that indicates how confident Perspective is that a comment is similar to toxic comments it’s seen in the past. This is an open source template app developed by X. We encourage you to personalize it to build tools for your users.
[Use app ▸](https://quintessential-yoke.glitch.me "Use app ▸")
[Jigsaw on X](https://x.com/jigsaw "Jigsaw on X")
!\[Reshuffle]\(data:image/svg+xml,%3Csvg xmlns=%22[http://www.w3.org/2000/svg%22](http://www.w3.org/2000/svg%22) viewBox=%220 0 150 150%22%3E%3C/svg%3E)
**Reshuffle**
Reshuffle is a platform to connect business applications with flexible scripts. They built an integration script to detect and hide replies that include keywords you define. To try it out, make sure you have a valid app enabled for Hide replies, then follow the instructions in the repo.
[Go to app ▸](https://github.com/reshufflehq/reshuffle "Go to app ▸")
[Reshuffle on X](https://x.com/reshufflehq "Reshuffle on X")
!\[Hide unwanted replies]\(data:image/svg+xml,%3Csvg xmlns=%22[http://www.w3.org/2000/svg%22](http://www.w3.org/2000/svg%22) viewBox=%220 0 396 397%22%3E%3C/svg%3E)
**Hide unwanted replies**
Dara Oladosu, the developer behind the popular app QuotedReplies, built an app that automatically hides replies that meet some of the criteria that he’s determined are more likely to exhibit abusive behavior, including replies that contain certain keywords he’s muted in the past.
[Go to app ▸](https://hideunwantedreplies.com/ "Go to app ▸")
[Dara Oladosu on X](https://x.com/dara_tobi "Dara Oladosu on X")
!\[Pandaflow]\(data:image/svg+xml,%3Csvg xmlns=%22[http://www.w3.org/2000/svg%22](http://www.w3.org/2000/svg%22) viewBox=%220 0 94 94%22%3E%3C/svg%3E)
**Pandaflow**
Pandaflow is a no code platform to automate workflows. They integrate the endpoint so users can programmatically hide replies based on a custom flow they define.
[Go to app ▸](https://pandaflow.io/ "Go to app ▸")
[Pandaflow on X](https://x.com/pandaflowio "Pandaflow on X")
# Manage replies by topic
Source: https://docs.x.com/enterprise-api/posts/hide-replies/integrate/manage-replies-by-topic
Through the hide replies endpoint, you can build integrations to help people and brands keep. Reference for the Enterprise X API tier covering integrate.
### Manage replies by topic
Through the hide replies endpoint, you can build integrations to help people and brands keep their conversation on topic. This page shows how to manage a conversation using the hide replies and [recent search](/x-api/posts/recent-search) endpoints.
Recent search has functionality to a conversation and its replies, and the Post payload returns [Post annotations](/x-api/fundamentals/post-annotations) to help you understand the context and topic of each Post, regardless of language.
The app's flow will have controls to display and manage a conversation:
1. It asks the user’s permission to read their Posts and manage their replies.
2. It pulls a recent conversation from a Post URL, and checks that the conversation is from the authenticating user.
3. It will call the recent search endpoint to display each Post in the conversation. The request will include a conversation ID search query and the annotation expansion to determine if the Post is sports-related or not, according to X's interpretation of the Post.
4. It calls Hide replies to hide a reply when the user chooses to do so. It will also provide a way to undo this action in case, so that the user is always in control.
5. For longer conversations, it will provide controls to [paginate through search results](/x-api/posts/search/integrate/paginate).
#### Optimize for the user (and for usage)
You can design a flow in a way that puts the user in control of any action they intend to make. Keeping this principle in mind also helps you build an integration that can optimize for Post consumption.
1. Because the authenticated user can only manage conversations they started, your flow should terminate early when that's not the case.
* Make an initial Post lookup request. Terminate the flow early if the Post URL is not valid or the conversation was not started by the authenticating user.
* This way, your app doesn't have to make a recent search request if the conversation cannot be moderated by the authenticated user.
2. Request [user and Post fields](/x-api/fundamentals/fields) in the same request to avoid making separate requests. This approach can also improve your app's performance.
3. Avoid making requests when needed. This app caches a reply's hidden status in the user's browser. This is useful for larger conversations, where the user may want to pick up their moderation efforts at a later stage, and it helps your app optimize requests to hide or unhide replies.
# Manage replies by topic
Source: https://docs.x.com/enterprise-api/posts/hide-replies/integrate/manage-replies-in-realtime
With the hide replies endpoint, you can build a workflow to help your users hide replies that. Reference for the Enterprise X API tier covering integrate.
### Manage replies in realtime
With the hide replies endpoint, you can build a workflow to help your users hide replies that have a very high-probability of being irrelevant.
Useful apps often combine technologies so that they can be valuable to their users. This page shows how to hide replies by using the [Perspective API](https://www.perspectiveapi.com/). This API is an artificial intelligence trained by [Jigsaw](https://jigsaw.google.com/), a unit within Google, to detect toxic comments. The application logic will work in the following way:
1. It asks the user’s permission to read their Posts and hide or unhide their replies.
2. It uses the [Account Activity API](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/subscribe-account-activity/overview) to detect incoming replies.
3. It asks the Perspective API to give a “score” (a number between 0 and 1) that indicates how confident their algorithm is that a comment is similar to toxic comments it’s seen in the past. (Perspective does not store the text sent to the service).
4. It calls hide replies if the algorithm’s score is very high.
#### Strive for transparency
Because Perspective is not trained on actual Posts, certain language nuances may cause this app to hide a reply that a user wants to remain unhidden. Regardless of the technology or the approach you use when designing your app, always make the best possible effort to ensure that your users understand what your app has hidden and can make changes.
* The best option is to always trust the user and to give them full control over their decisions. This means your user experience should include controls to undo any action taken by your app on behalf of the user.
* When using an artificial intelligence, your app should use a very high confidence threshold to detect and hide Posts.
* Not everybody uses the same words, and your app should be designed to avoid any bias. Be mindful of reclaimed words and slang that may lead to false positives.
* If you are training an artificial intelligence, consider adopting a model that closely reflects language often used on X.
# Hide Replies
Source: https://docs.x.com/enterprise-api/posts/hide-replies/introduction
Use the Enterprise Hide Replies endpoint to hide or unhide replies to Posts authored by the authenticated user and moderate conversations on X.
The Hide Replies endpoint lets you hide or unhide replies to Posts authored by the authenticated user. Hidden replies are still accessible but require an extra click to view.
## Overview
Hide a reply to your Post
Unhide a previously hidden reply
Moderate discussions on your Posts
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------ | :--------------------- |
| PUT | [`/2/tweets/:tweet_id/hidden`](/x-api/posts/hide-reply) | Hide or unhide a reply |
***
## How it works
Send a PUT request with `hidden: true` to hide a reply, or `hidden: false` to unhide it:
```json theme={null}
{
"hidden": true
}
```
***
## Example: Hide a reply
```bash theme={null}
curl -X PUT "https://api.x.com/2/tweets/1234567890/hidden" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"hidden": true}'
```
## Example response
```json theme={null}
{
"data": {
"hidden": true
}
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
Hide your first reply
Full endpoint documentation
# Migration guide
Source: https://docs.x.com/enterprise-api/posts/hide-replies/migrate
The v2 hide replies endpoint is replacing the Labs hide replies endpoint. Reference for the Enterprise X API tier covering hide replies.
## Comparing X API's hide replies endpoints
The v2 hide replies endpoint is replacing the Labs hide replies endpoint. If you have code, apps, or tools that use the Labs version of this endpoint, and are considering migrating to the newer X API v2 endpoint, then this guide is for you.
In order to use the new X API v2 (including the hide replies endpoint), you will need to [opt in to the new Developer Console](https://developer.x.com/en/portal/opt-in), create a [Project](/resources/fundamentals/developer-apps), and add an App to that Project. You can then use the credentials associated with that App to make requests to the hide replies endpoint. Adding the same App that's enrolled for the Labs v2 hide replies endpoint will keep your users authenticated.
The following table compares the differences between Labs and the newer X API v2 endpoint:
| **Description** | **Labs v2** | **X API v2** |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------- | :--------------------------------------------------- |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /labs/2/tweets/:id/hidden | /2/tweets/:id/hidden |
| Authentication | OAuth 1.0a User context | OAuth 1.0a User context |
| HTTP methods supported | PUT | PUT |
| Default request rate limits | 10 requests per 15 minutes (shared across all authenticated users) | 50 requests per 15 min (for each authenticated user) |
| Can hide replies | ✔︎ | ✔︎ |
| Can unhide a previously hidden reply | ✔︎ | ✔︎ |
| Can hide or unhide replies multiple times | ✔︎ | ✔︎ |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [project](/resources/fundamentals/developer-apps) | | ✔ |
***
## Code examples
### Hide a reply (v2)
```bash cURL theme={null}
curl -X PUT "https://api.x.com/2/tweets/1234567890/hidden" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"hidden": true}'
```
```python Python theme={null}
# Requires OAuth 1.0a User Context authentication
import requests
from requests_oauthlib import OAuth1
auth = OAuth1(
"API_KEY", "API_SECRET",
"ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"
)
url = "https://api.x.com/2/tweets/1234567890/hidden"
response = requests.put(url, auth=auth, json={"hidden": True})
print(response.json())
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Hide a reply
response = client.posts.hide_reply("1234567890", hidden=True)
print(f"Hidden: {response.data.hidden}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Hide a reply
const response = await client.posts.hideReply("1234567890", { hidden: true });
console.log(`Hidden: ${response.data?.hidden}`);
```
**Other migration resources**
[X API migration hub](/x-api/migrate/overview)
# Quickstart
Source: https://docs.x.com/enterprise-api/posts/hide-replies/quickstart
This guide walks you through hiding and unhiding replies to Posts in conversations you. Reference for the Enterprise X API tier covering hide replies.
This guide walks you through hiding and unhiding replies to Posts in conversations you started.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Hide a reply
Get the ID of the reply you want to hide. You can only hide replies to conversations started by the authenticated user.
```
https://x.com/user/status/1232720193182412800
└── This is the Post ID
```
```bash cURL theme={null}
curl -X PUT "https://api.x.com/2/tweets/1232720193182412800/hidden" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"hidden": true}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Hide a reply
response = client.posts.hide_reply("1232720193182412800", hidden=True)
print(f"Hidden: {response.data.hidden}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Hide a reply
const response = await client.posts.hideReply("1232720193182412800", {
hidden: true,
});
console.log(`Hidden: ${response.data?.hidden}`);
```
```json theme={null}
{
"data": {
"hidden": true
}
}
```
The reply is now hidden from the main conversation view. Users can still see it by clicking "View hidden replies."
***
## Unhide a reply
To make a hidden reply visible again:
```bash cURL theme={null}
curl -X PUT "https://api.x.com/2/tweets/1232720193182412800/hidden" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"hidden": false}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Unhide a reply
response = client.posts.hide_reply("1232720193182412800", hidden=False)
print(f"Hidden: {response.data.hidden}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Unhide a reply
const response = await client.posts.hideReply("1232720193182412800", {
hidden: false,
});
console.log(`Hidden: ${response.data?.hidden}`);
```
**Response:**
```json theme={null}
{
"data": {
"hidden": false
}
}
```
***
## Important notes
* You can only hide replies to conversations **you started**
* Hidden replies are still visible via "View hidden replies"
* The reply author is not notified when their reply is hidden
***
## Next steps
Moderate replies based on content
Moderate replies as they arrive
Full endpoint documentation
# Hide reply
Source: https://docs.x.com/enterprise-api/posts/hide-reply
put /2/tweets/{tweet_id}/hidden
Hides or unhides a reply to a conversation owned by the authenticated user.
# Likes
Source: https://docs.x.com/enterprise-api/posts/likes/introduction
The Likes endpoints let you like and unlike Posts, see which users liked a Post, and get Posts liked. Reference for the Enterprise X API tier covering likes.
The Likes endpoints let you like and unlike Posts, see which users liked a Post, and get Posts liked by a user.
## Overview
Like a Post on behalf of a user
Remove a like from a Post
See who liked a Post
Get Posts a user has liked
***
## Endpoints
### Likes lookup
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------ | :------------------------- |
| GET | [`/2/tweets/:id/liking_users`](/x-api/posts/get-liking-users) | Get users who liked a Post |
| GET | [`/2/users/:id/liked_tweets`](/x-api/users/get-liked-posts) | Get Posts liked by a user |
### Manage likes
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------- | :------------ |
| POST | [`/2/users/:id/likes`](/x-api/users/like-post) | Like a Post |
| DELETE | [`/2/users/:id/likes/:tweet_id`](/x-api/users/unlike-post) | Unlike a Post |
***
## Important notes
The liking users endpoint returns a maximum of **100 users** per Post for all time, regardless of the actual number of likes.
***
## Example: Get liking users
```bash theme={null}
curl "https://api.x.com/2/tweets/1234567890/liking_users?\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example: Like a Post
```bash theme={null}
curl -X POST "https://api.x.com/2/users/123456789/likes" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1234567890"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Get likes for a Post
Like and unlike Posts
Full endpoint documentation
Working code examples
# Likes lookup
Source: https://docs.x.com/enterprise-api/posts/likes/migrate/likes-lookup-standard-to-twitter-api-v2
If you have been working with the standard v1.1 GET favorites/list endpoint, the goal of this. Reference for the Enterprise X API tier covering migrate.
### Likes lookup: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [GET favorites/list](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/get-favorites-list) endpoint, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 Likes lookup endpoints.
With v2, we’ve also introduced a new liked users endpoint which allows you to get information about a Post's liking users.
* **Similarities**
* Authentication
* Rate limits
* **Differences**
* Endpoint URLs
* Request limitations
* App and Project requirements
* Request parameters
* New JSON format
#### Similarities
**Authentication**
Both the standard v1.1 and X API v2 Likes lookup endpoints use [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2) or [OAuth 2.0 Bearer Token](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only). Therefore, if you were previously using the [GET favorites/list endpoints](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/get-favorites-list) standard v1.1 endpoints, you can continue using the same authentication method if you migrate to the X API v2 version if you wish.
Depending on your authentication library/package of choice, Bearer Token authentication is probably the easiest way to get started and can be set with a simple request header. To learn how to generate a Bearer Token, see [this OAuth 2.0 Bearer Token guide](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only).
**Rate limits**
The standard v1.1 GET favorites/list endpoint has a 75 requests per 15 minutes per user rate limit. The corresponding liked Posts endpoint in v2 also has this sam
# Manage Likes
Source: https://docs.x.com/enterprise-api/posts/likes/migrate/manage-likes-standard-to-twitter-api-v2
If you have been working with the standard v1.1 POST favorites/create and POST favorites/destroy. Reference for the Enterprise X API tier covering migrate.
### Manage Likes: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [POST favorites/create](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-favorites-create) and [POST favorites/destroy](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-favorites-destroy) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 manage Likes endpoints.
* **Similarities**
* OAuth 1.0a User Context
* **Differences**
* Endpoint URLs and HTTP methods
* App and Project requirements
* Request parameters
#### Similarities
**OAuth 1.0a User Context authentication method**
Both the endpoint versions support [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2). Therefore, if you were previously using one of the standard v1.1 manage favorites endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs and HTTP methods**
* Standard v1.1 endpoints:
* POST [https://api.x.com/1.1/favorites/create.json](https://api.x.com/1.1/favorites/create.json)
(like a Post)
* POST [https://api.x.com/1.1/favorites/destroy.json](https://api.x.com/1.1/favorites/destroy.json)
(unlike a Post)
* X API v2 endpoint:
* POST [https://api.x.com/2/tweets/:id/likes](https://api.x.com/2/tweets/:id/likes)
(like a Post)
* DELETE [https://api.x.com/2/tweets/:id/likes/:tweet\_id](https://api.x.com/2/tweets/:id/likes/:tweet_id)
(unlike a Post)
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated to a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps associated
# Enterprise Likes endpoints v2 migration
Source: https://docs.x.com/enterprise-api/posts/likes/migrate/overview
Compare Standard v1.1 and X API v2 Likes endpoints, including liked Posts lookup and manage Likes, with parameter and rate limit differences.
## Comparing X API’s Likes endpoints
These guides will focus on the following areas:
* **API request parameters** - The X API v2 endpoint introduces a new set of request parameters. While some parameters will be familiar, especially for those integrating with Labs, there are many important differences such as the introduction of the [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) parameters.
* **App and Project requirements** - To access the X API v2, you will need to use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps)
#### Likes lookup
**Users who have liked a Post**
The liked users endpoint is new functionality for v2, allowing you to get information about a Post's liking users.
| Description | X API v2 |
| :----------------------------------------------------------------- | :---------------------------------------------------------------------------- |
| HTTP methods supported | GET |
| Host domain | [https://api.x.com](https://api.x.com) |
| Endpoint path | /2/tweets/:id/liking\_users |
| [Authentication](/resources/fundamentals/authentication) | OAuth 2.0 Bearer Token
OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 75 requests per 15 min (per App)
75 requests per 15 min (per user) |
**Posts liked by a user**
The following tables compare the standard v1.1 [GET favorites/list](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-favorites-list) endpoint and the X API v2 liked Posts endpoints:
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP methods supported | GET | GET |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/favorites/list.json | /2/users/:id/liked\_tweets |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 2.0 Bearer Token
OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 75 requests per 15 min | 75 requests per 15 min (per App)
75 requests per 15 min (per user) |
| Data formats | Standard v1.1 format | [X API v2 format](/x-api/fundamentals/data-dictionary) (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
#### Manage Likes
The v2 manage Likes endpoints replace the v1.1 [POST favorites/create](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-favorites-create) and [POST favorites/destroy](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-favorites-destroy) endpoints.
The following tables compare the standard v1.1 and X API v2 manage Like endpoints:
#### Like a Post
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------- |
| HTTP methods supported | POST | POST |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/favorites/create.json | /2/users/:id/likes |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 1000 requests per 24 hours (per user)
1000 requests per 24 hours (per App) | 50 requests per 15 min (per user)
1000 requests per 24 hours (per user, shared with DELETE) |
#### Unlike a Post
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------- | :------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------- |
| HTTP methods supported | POST | DELETE |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/favorites/destroy.json | /2/users/:id/likes/:tweet\_id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 1000 requests per 24 hours (per user)
1000 requests per 24 hours (per App) | 50 requests per 15 min (per user)
1000 requests per 24 hours (per user, shared with POST) |
**Other migration resources**
[Likes lookup: Standard v1.1 to X API v2](/x-api/posts/likes/migrate/likes-lookup-standard-to-twitter-api-v2)
[Manage Likes: Standard v1.1 to X API v2](/x-api/posts/likes#manage-likes-standard-v1-1-compared-to-x-api-v2)
[X API migration hub](/x-api/migrate/overview)
# Likes Lookup
Source: https://docs.x.com/enterprise-api/posts/likes/quickstart/likes-lookup
Quickstart guide for retrieving like data from the X API, including liking users and liked Posts, using the Enterprise tier likes lookup endpoints.
This guide walks you through retrieving likes data using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token (for public data) or User Access Token (for private metrics)
***
## Get users who liked a Post
Retrieve the list of users who liked a specific Post:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1354143047324299264/liking_users?\
user.fields=created_at,username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get users who liked a Post with pagination
for page in client.posts.get_liking_users(
"1354143047324299264",
user_fields=["created_at", "username", "verified"]
):
for user in page.data:
print(f"{user.username} - Joined: {user.created_at}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get users who liked a Post with pagination
const paginator = client.posts.getLikingUsers("1354143047324299264", {
userFields: ["created_at", "username", "verified"],
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Joined: ${user.created_at}`);
});
}
```
### Response
```json theme={null}
{
"data": [
{
"created_at": "2008-12-04T18:51:57.000Z",
"id": "17874544",
"username": "TwitterSupport",
"name": "Twitter Support",
"verified": true
},
{
"created_at": "2007-02-20T14:35:54.000Z",
"id": "783214",
"username": "Twitter",
"name": "Twitter",
"verified": true
}
],
"meta": {
"result_count": 2,
"next_token": "7140dibdnow9c7btw3z2vwioavpvutgzrzm9icis4ndix"
}
}
```
***
## Get a user's liked Posts
Retrieve Posts that a specific user has liked:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/liked_tweets?\
tweet.fields=created_at,public_metrics&\
max_results=10" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a user's liked Posts with pagination
for page in client.users.get_liked_tweets(
"2244994945",
tweet_fields=["created_at", "public_metrics"],
max_results=10
):
for post in page.data:
print(f"{post.text[:50]}... - Likes: {post.public_metrics.like_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get a user's liked Posts with pagination
const paginator = client.users.getLikedTweets("2244994945", {
tweetFields: ["created_at", "public_metrics"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}... - Likes: ${post.public_metrics?.like_count}`);
});
}
```
### Response
```json theme={null}
{
"data": [
{
"id": "1362449997430542337",
"text": "Honored to be the first developer to be featured...",
"created_at": "2021-02-18T17:45:00.000Z",
"public_metrics": {
"retweet_count": 5,
"reply_count": 2,
"like_count": 42,
"quote_count": 1
}
}
],
"meta": {
"result_count": 1,
"next_token": "7140dibdnow9c7btw4539n0vybdnx19ylpayqf16fjt4l"
}
}
```
***
## Include additional data
Use expansions to get related data like pinned Posts:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1354143047324299264/liking_users?\
user.fields=created_at&\
expansions=pinned_tweet_id&\
tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get liking users with pinned Post expansion
for page in client.posts.get_liking_users(
"1354143047324299264",
user_fields=["created_at"],
expansions=["pinned_tweet_id"],
tweet_fields=["created_at"]
):
for user in page.data:
print(f"{user.username}")
# Pinned Posts are in page.includes.tweets
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get liking users with pinned Post expansion
const paginator = client.posts.getLikingUsers("1354143047324299264", {
userFields: ["created_at"],
expansions: ["pinned_tweet_id"],
tweetFields: ["created_at"],
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(user.username);
});
// Pinned Posts are in page.includes?.tweets
}
```
***
## Next steps
Like and unlike Posts
Full endpoint documentation
# Manage Likes
Source: https://docs.x.com/enterprise-api/posts/likes/quickstart/manage-likes
This guide walks you through liking and unliking Posts using the X API. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through liking and unliking Posts using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Like a Post
You need your authenticated user's ID. You can find it using the [user lookup endpoint](/x-api/users/lookup/introduction) or from your Access Token (the numeric part is your user ID).
Find the Post ID in the URL when viewing a Post:
```
https://x.com/XDevelopers/status/1228393702244134912
└── This is the Post ID
```
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/123456789/likes" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1228393702244134912"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Like a Post
response = client.posts.like(
user_id="123456789",
tweet_id="1228393702244134912"
)
print(f"Liked: {response.data.liked}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Like a Post
const response = await client.posts.like("123456789", {
tweetId: "1228393702244134912",
});
console.log(`Liked: ${response.data?.liked}`);
```
```json theme={null}
{
"data": {
"liked": true
}
}
```
***
## Unlike a Post
Remove a like from a Post:
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/123456789/likes/1228393702244134912" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Unlike a Post
response = client.posts.unlike(
user_id="123456789",
tweet_id="1228393702244134912"
)
print(f"Liked: {response.data.liked}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Unlike a Post
const response = await client.posts.unlike("123456789", "1228393702244134912");
console.log(`Liked: ${response.data?.liked}`);
```
**Response:**
```json theme={null}
{
"data": {
"liked": false
}
}
```
***
## Next steps
Get users who liked a Post
Full endpoint documentation
# Integration Guide
Source: https://docs.x.com/enterprise-api/posts/lookup/integrate
This guide covers the key concepts you need to integrate the Post lookup endpoints into your. Reference for the Enterprise X API tier covering lookup.
This guide covers the key concepts you need to integrate the Post lookup endpoints into your application.
***
## Authentication
All X API v2 endpoints require authentication. Choose the method that fits your use case:
| Method | Best for | Can access private metrics? |
| :----------------------------------------------------------------------------------------------------------------------------- | :---------------------------- | :-------------------------------- |
| [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) | Server-to-server, public data | No |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | User-facing apps | Yes (for authorized user's Posts) |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Legacy integrations | Yes (for authorized user's Posts) |
### App-Only authentication
For public Post data, use a Bearer Token:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1234567890" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a single Post by ID
response = client.posts.get("1234567890")
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.posts.get("1234567890");
console.log(response.data);
```
### User Context authentication
To access private metrics, authenticate on behalf of the Post author:
The following fields require User Context authentication:
* `tweet.fields.non_public_metrics`
* `tweet.fields.promoted_metrics`
* `tweet.fields.organic_metrics`
* `media.fields.non_public_metrics`
* `media.fields.promoted_metrics`
* `media.fields.organic_metrics`
***
## Fields and expansions
The X API v2 returns minimal data by default. Use `fields` and `expansions` to request exactly what you need.
### Default response
```json theme={null}
{
"data": {
"id": "1234567890",
"text": "Hello world!",
"edit_history_tweet_ids": ["1234567890"]
}
}
```
### Available fields
| Field | Description |
| :-------------------- | :--------------------------------- |
| `created_at` | Post creation timestamp |
| `author_id` | Author's user ID |
| `public_metrics` | Like, retweet, reply, quote counts |
| `entities` | Hashtags, mentions, URLs, cashtags |
| `attachments` | Media keys, poll IDs |
| `conversation_id` | Thread identifier |
| `context_annotations` | Topic/entity classifications |
| `in_reply_to_user_id` | User being replied to |
| `lang` | Detected language |
| `source` | Posting client |
| `possibly_sensitive` | Sensitive content flag |
| `reply_settings` | Who can reply |
| Field | Description |
| :------------------ | :------------------------ |
| `username` | @handle |
| `name` | Display name |
| `profile_image_url` | Avatar URL |
| `verified` | Verification status |
| `description` | Bio |
| `public_metrics` | Follower/following counts |
| `created_at` | Account creation date |
| Field | Description |
| :------------------ | :-------------------------- |
| `url` | Media URL |
| `preview_image_url` | Thumbnail URL |
| `type` | photo, video, animated\_gif |
| `duration_ms` | Video duration |
| `height`, `width` | Dimensions |
| `alt_text` | Accessibility text |
### Example with fields
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1234567890?\
tweet.fields=created_at,public_metrics,entities&\
expansions=author_id,attachments.media_keys&\
user.fields=username,verified&\
media.fields=url,type" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a Post with additional fields and expansions
response = client.posts.get(
"1234567890",
tweet_fields=["created_at", "public_metrics", "entities"],
expansions=["author_id", "attachments.media_keys"],
user_fields=["username", "verified"],
media_fields=["url", "type"]
)
print(response.data)
print(response.includes) # Contains expanded user and media objects
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.posts.get("1234567890", {
tweetFields: ["created_at", "public_metrics", "entities"],
expansions: ["author_id", "attachments.media_keys"],
userFields: ["username", "verified"],
mediaFields: ["url", "type"],
});
console.log(response.data);
console.log(response.includes); // Contains expanded user and media objects
```
***
## Post edits
Posts can be edited up to 5 times within 30 minutes of creation.
### How it works
* Each edit creates a new Post ID
* `edit_history_tweet_ids` contains all versions (oldest first)
* The endpoint always returns the most recent version
### Example response
```json theme={null}
{
"data": {
"id": "1234567893",
"text": "Hello world! (edited twice)",
"edit_history_tweet_ids": [
"1234567890",
"1234567891",
"1234567893"
]
}
}
```
Posts retrieved after their 30-minute edit window represent the final version. For real-time use cases, be aware that recently-published Posts may still be edited.
***
## Error handling
### Common errors
| Status | Error | Solution |
| :----- | :---------------- | :-------------------------------- |
| 400 | Invalid request | Check parameter formatting |
| 401 | Unauthorized | Verify authentication credentials |
| 403 | Forbidden | Check App permissions |
| 404 | Not Found | Post deleted or doesn't exist |
| 429 | Too Many Requests | Wait and retry (see rate limits) |
### Deleted or protected Posts
If a Post is deleted or from a protected account you don't follow:
* Single Post lookup returns `404`
* Multi-Post lookup omits the Post from results with an `errors` array
```json theme={null}
{
"data": [
{ "id": "1234567890", "text": "Available post" }
],
"errors": [
{
"resource_id": "1234567891",
"resource_type": "tweet",
"title": "Not Found Error",
"detail": "Could not find tweet with id: [1234567891]."
}
]
}
```
***
## Best practices
Use the multi-Post endpoint to fetch up to 100 Posts at once, reducing API calls.
Specify only the fields you need to minimize response size and processing time.
Cache Post data locally to reduce repeated requests for the same content.
For real-time apps, consider re-fetching Posts after the 30-minute edit window.
***
## Next steps
Complete endpoint documentation
All available objects and fields
Working code examples
Handle errors gracefully
# Post Lookup
Source: https://docs.x.com/enterprise-api/posts/lookup/introduction
The Post lookup endpoints allow you to retrieve one or more Posts by their IDs. Reference for the Enterprise X API tier covering lookup.
The Post lookup endpoints allow you to retrieve one or more Posts by their IDs. Use these endpoints to get up-to-date Post details, verify Post availability, or examine edit history.
## Overview
Posts are the core content on X. Each Post can contain:
* Up to 280 characters of text
* Attached media (images, videos, GIFs)
* Polls, places, and URLs
* Replies, quotes, and mentions
Posts can be edited up to 5 times within 30 minutes of creation. Each edit generates a new Post ID, and the edit history is preserved.
Retrieve a specific Post by ID
Retrieve up to 100 Posts in one request
Access the complete edit history of a Post
Include author, media, polls, and more
***
## Use cases
* **Display Post content** — Show Post details in your application
* **Verify availability** — Check if a Post still exists or was deleted
* **Compliance management** — Track Post changes for compliance events
* **Analytics** — Retrieve engagement metrics for specific Posts
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :--------------------------------------------- | :----------------------------------------- |
| GET | [`/2/tweets/:id`](/x-api/posts/get-post-by-id) | Retrieve a single Post by ID |
| GET | [`/2/tweets`](/x-api/posts/get-posts-by-ids) | Retrieve multiple Posts by IDs (up to 100) |
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Make your first Post lookup request
Learn key concepts and best practices
See full endpoint documentation
Explore code examples
# Overview
Source: https://docs.x.com/enterprise-api/posts/lookup/migrate/overview
The v2 Posts lookup endpoints replace the standard v1.1 GET statuses/lookup and GET statuses/show. Reference for the Enterprise X API tier covering migrate.
## Comparing X API’s Posts lookup endpoints
The v2 Posts lookup endpoints replace the standard v1.1 [GET statuses/lookup](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-lookup) and [GET statuses/show](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-show-id) endpoints. This guide is for developers migrating from these older versions to X API v2.
***
## Endpoint comparison table
| Description | Standard v1.1 | X API v2 |
| :------------------------------------------------------------------------------------------------------ | :----------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |
| **HTTP methods supported** | `GET` | `GET` |
| **Host domain** | `https://api.x.com` | `https://api.x.com` |
| **Endpoint path** | `/1.1/statuses/show.json`, `/1.1/statuses/lookup.json` | `/2/tweets` |
| **[Authentication](resources/fundamentals/authentication)** | OAuth 1.0a User Context | OAuth 1.0a User Context, OAuth 2.0 App-Only, OAuth 2.0 Authorization Code with PKCE |
| **Post [JSON format](/x-api/fundamentals/data-dictionary)** | Standard v1.1 format | [X API v2 format](/x-api/fundamentals/data-dictionary), determined by `fields` and `expansions` parameters (not backward-compatible with v1.1) |
| **Supports selecting specific [fields](/x-api/fundamentals/data-dictionary)** | | ✔ |
| **Supports the [annotations](/x-api/fundamentals/post-annotations) fields** | | ✔ |
| **Supports new [metrics](/x-api/fundamentals/metrics) fields** | | ✔ |
| **Supports `conversation_id` field** | | ✔ |
| **Provides Post edit history** | ✔ | ✔ |
| **Requires credentials from a [developer App](/fundamentals/developer-apps) associated with a Project** | | ✔ |
***
## Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 GET statuses/show and GET statuses/lookup, this guide will help you understand the similarities and differences between the standard and X API v2 Posts lookup endpoints.
You may also be interested in our [visual data format migration tool](/x-api/migrate/data-format-migration) to help you quickly see the differences between the [X API v1.1 data format](/x-api/fundamentals/data-dictionary) and the [X API v2 format](/x-api/fundamentals/data-dictionary).
* **Similarities**
* OAuth 1.0a User Context
* Posts per request limits
* Support for Post edit history and metadata
* **Differences**
* Endpoint URLs
* App and Project requirements
* Response data format
* Request parameters
### Similarities
#### OAuth 1.0a User Context Authentication Method
The standard endpoint supports [OAuth 1.0a User Context](/resources/fundamentals/authentication), while the new X API v2 Post lookup endpoint supports both OAuth 1.0a User Context and [OAuth 2.0 App-Only](/resources/fundamentals/authentication). Therefore, if you were previously using one of the standard v1.1 Post lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
App-Only authentication is likely the easiest way to get started. To learn how to generate an App Access Token, see [this OAuth 2.0 App-only guide](/resources/fundamentals/authentication).
#### Posts per Request Limits
The v1.1 [GET statuses/lookup](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-lookup) endpoint allows you to specify up to 100 Posts per request. This also applies to the GET /tweets endpoint. To specify a full 100 Posts, use the `ids` parameter as a query parameter with a comma-separated list of [Post IDs](/resources/fundamentals/x-ids).
**Support for Post Edit History and Metadata**
Both versions provide metadata that describes any edit history. Check out the Post lookup API References and the [Edit Posts fundamentals page](/x-api/fundamentals/edit-posts) for more details.
### Differences
#### Endpoint URLs
* **Standard v1.1 endpoints:**
* `https://api.x.com/1.1/statuses/show`
* `https://api.x.com/1.1/statuses/lookup`
* **X API v2 endpoint:**
* `https://api.x.com/2/tweets`
* `https://api.x.com/2/tweets/:id`
#### App and Project Requirements
X API v2 endpoints require credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) for authentication. X API v1.1 endpoints can use credentials from Apps or Apps associated with an App.
#### Response data format
A significant difference between standard v1.1 and X API v2 endpoint versions is how fields are selected in the payload.
For standard endpoints, many response fields are included by default, with options to use parameters to specify additional fields.
X API v2, however, only delivers the Post `id` and `text` fields by default. Additional fields and objects require the use of [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) parameters. The expanded fields return in an `includes` object within the response, which can be matched to the primary Post object by matching IDs.
For more on using fields and expansions, see the [guide on how to use fields and expansions](/x-api/fundamentals/data-dictionary). A [data format migration guide](/x-api/fundamentals/fields) also maps standard v1.1 fields to the newer v2 fields.
Additionally, X API v2 introduces new JSON designs for objects, including the Post and [user](/x-api/fundamentals/fields) objects:
* Standard endpoints return Post objects in a `statuses` array, while X API v2 uses a `data` array.
* Retweeted and Quoted Tweets in X API v2 replace "statuses" terminology.
* New terminology such as `like` replaces terms like `favorites` and `favourites`.
* Attributes with no values (e.g., `null`) are not included in X API v2 payloads.
The Post object in X API v2 includes new fields such as:
* `conversation_id`
* Two new [annotations](/x-api/fundamentals/post-annotations) fields (`context` and `entities`)
* New [metrics](/x-api/fundamentals/metrics) fields
* `reply_setting` field showing who can reply to a given Post
#### Request Parameters
The following standard v1.1 request parameters have equivalents in X API v2:
| Standard | X API v2 |
| :------- | :------- |
| `id` | `ids` |
Certain standard v1.1 parameters are **not** supported in X API v2:
| Standard | Comment |
| :--------------------- | :--------------------------------------------------------------------------------------------------------------- |
| `tweet_mode` | Replaced by fields and expansions functionality. |
| `trim_user` | Replaced by fields and expansions. Use `author_id` expansion and `user.fields` for user data. |
| `include_my_retweet` | Provides the ID of the source Post for Retweeted Posts by the authenticating user. |
| `include_entities` | Use fields and expansions to control entities in the payload. |
| `include_ext_alt_text` | Adds `ext_alt_text` field in media entity if alt text is present. |
| `include_card_uri` | Adds `card_uri` when an ads card is attached. |
| `map` | Returns the Post ID and error message for unavailable Posts in X API v2, as opposed to nullified fields in v1.1. |
### CURL Requests
The following cURL requests show standard v1.1 endpoints and their v2 equivalents. Replace `ACCESS_TOKEN` in the header with your app access token. For v2 endpoints, the token must belong to a [developer App](/fundamentals/developer-apps) within a Project.
The response payloads from v1.1 will differ from v2. With v2, you can request different fields with the [fields](/x-api/fundamentals/fields) and [expansions](/x-api/fundamentals/expansions) parameters.
**Standard v1.1 `GET statuses/lookup` and v2 `GET /tweets` endpoints**
```bash theme={null}
curl --request GET \
--url 'https://api.x.com/1.1/statuses/lookup.json?id=1460323737035677698%2C1460323743339741184' \
--header 'Authorization: Bearer $ACCESS_TOKEN'
```
```bash theme={null}
curl --request GET \
--url 'https://api.x.com/2/tweets?ids=1460323737035677698%2C1460323743339741184&tweet.fields=created_at&expansions=author_id&user.fields=created_at' \
--header 'Authorization: Bearer $ACCESS_TOKEN'
```
**Standard v1.1 `GET statuses/show/:id` and v2 `GET /tweets/:id` endpoints**
```
curl --request GET \
--url 'https://api.x.com/1.1/statuses/show.json?id=1460323737035677698' \
--header 'Authorization: Bearer $ACCESS_TOKEN'
```
```
curl --request GET \
--url 'https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at&expansions=author_id&user.fields=created_at' \
--header 'Authorization: Bearer $ACCESS_TOKEN'
```
# v1 to v2
Source: https://docs.x.com/enterprise-api/posts/lookup/migrate/standard-to-twitter-api-v2
If you have been working with the standard v1.1 GET statuses/show and GET statuses/lookup, this. Reference for the Enterprise X API tier covering migrate.
## Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 GET statuses/show and GET statuses/lookup, this guide will help you understand the similarities and differences between the standard and X API v2 Posts lookup endpoints.
You may also be interested in our [visual data format migration tool](/x-api/migrate/data-format-migration) to help you quickly see the differences between the [X API v1.1 data format](/x-api/fundamentals/data-dictionary) and the [X API v2 format](/x-api/fundamentals/data-dictionary).
* **Similarities**
* OAuth 1.0a User Context
* Posts per request limits
* Support for Post edit history and metadata
* **Differences**
* Endpoint URLs
* App and Project requirements
* Response data format
* Request parameters
### Similarities
#### OAuth 1.0a User Context Authentication Method
The standard endpoint supports [OAuth 1.0a User Context](/resources/fundamentals/authentication), while the new X API v2 Post lookup endpoint supports both OAuth 1.0a User Context and [OAuth 2.0 App-Only](/resources/fundamentals/authentication). Therefore, if you were previously using one of the standard v1.1 Post lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
App-Only authentication is likely the easiest way to get started. To learn how to generate an App Access Token, see [this OAuth 2.0 App-only guide](/resources/fundamentals/authentication).
#### Posts per Request Limits
The v1.1 [GET statuses/lookup](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-lookup) endpoint allows you to specify up to 100 Posts per request. This also applies to the GET /tweets endpoint. To specify a full 100 Posts, use the `ids` parameter as a query parameter wi
# Quickstart
Source: https://docs.x.com/enterprise-api/posts/lookup/quickstart
This guide walks you through making your first Post lookup request using the X API v2. Reference for the Enterprise X API tier covering lookup.
This guide walks you through making your first Post lookup request using the X API v2.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token (found in the Developer Console under "Keys and tokens")
***
Every Post has a unique ID. You can find it in the Post's URL:
```
https://x.com/XDevelopers/status/1228393702244134912
└── This is the Post ID
```
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1228393702244134912" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a single Post by ID
response = client.posts.get("1228393702244134912")
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.posts.get("1228393702244134912");
console.log(response.data);
```
The default response includes the Post's `id`, `text`, and `edit_history_tweet_ids`:
```json theme={null}
{
"data": {
"id": "1228393702244134912",
"text": "What did the developer write in their Valentine's card?\n\nwhile(true) {\n I = Love(You);\n}",
"edit_history_tweet_ids": ["1228393702244134912"]
}
}
```
Use query parameters to get more data:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1228393702244134912?\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id&\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a Post with additional fields and expansions
response = client.posts.get(
"1228393702244134912",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id"],
user_fields=["username", "verified"]
)
print(response.data)
print(response.includes) # Contains author user object
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.posts.get("1228393702244134912", {
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id"],
userFields: ["username", "verified"],
});
console.log(response.data);
console.log(response.includes); // Contains author user object
```
**Response:**
```json theme={null}
{
"data": {
"id": "1228393702244134912",
"text": "What did the developer write in their Valentine's card?...",
"created_at": "2020-02-14T19:00:55.000Z",
"author_id": "2244994945",
"public_metrics": {
"retweet_count": 156,
"reply_count": 23,
"like_count": 892,
"quote_count": 12
},
"edit_history_tweet_ids": ["1228393702244134912"]
},
"includes": {
"users": [
{
"id": "2244994945",
"username": "XDevelopers",
"verified": true
}
]
}
}
```
Retrieve up to 100 Posts in a single request:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets?\
ids=1228393702244134912,1227640996038684673,1199786642791452673&\
tweet.fields=created_at,author_id" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get multiple Posts by IDs
response = client.posts.get_posts(
ids=["1228393702244134912", "1227640996038684673", "1199786642791452673"],
tweet_fields=["created_at", "author_id"]
)
for post in response.data:
print(f"{post.id}: {post.text[:50]}...")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.posts.getPosts({
ids: ["1228393702244134912", "1227640996038684673", "1199786642791452673"],
tweetFields: ["created_at", "author_id"],
});
response.data?.forEach((post) => {
console.log(`${post.id}: ${post.text?.slice(0, 50)}...`);
});
```
***
## Next steps
Learn authentication, rate limits, and best practices
Master the fields and expansions system
See all available parameters
Explore more examples
# Integration guide
Source: https://docs.x.com/enterprise-api/posts/manage-tweets/integrate
This page covers tools and key concepts for integrating the manage Posts endpoints into your. Reference for the Enterprise X API tier covering manage tweets.
This page covers tools and key concepts for integrating the manage Posts endpoints into your system.
***
## Helpful tools
Before we dive into some key concepts that will help you integrate this endpoint, we recommend that you become familiar with:
### Postman
Postman is a great tool that you can use to test out an endpoint. Each Postman request includes every path and body parameter to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our ["Using Postman"](/tutorials/postman-getting-started) page.
### Code samples
Interested in getting set up with this endpoint with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [Github page](https://github.com/xdevplatform/Twitter-API-v2-sample-code).
### Third-party libraries
Take advantage of one of our communities' [third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the proper version tag.
## Key concepts
### Authentication
All X API v2 endpoints require you to authenticate your requests with a set of credentials, also known as keys and tokens.
These specific endpoints requires the use of [OAuth 1.0a User Context](/resources/fundamentals/authentication), which means that you must use a set of API keys and user Access Tokens to make a successful request. The Access Tokens must be associated with the user that you are making the request on behalf of. If you would like to generate a set of Access Tokens for another user, they must authorize or authenticate your App using the [3-legged OAuth flow](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow).
Please note that OAuth 1.0a can be difficult to use. If you are not familiar with this authentication method, we recommend that you use a [library](/tools-and-libraries), use a tool like Postman, or use OAuth 2.0 to authenticate your requests.
[OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) allows for greater control over an application's scope, and authorization flows across multiple devices. OAuth 2.0 allows you to pick specific fine-grained scopes which give you specific permissions on behalf of a user.
To enable OAuth 2.0 in your App, you must enable it in your App's authentication settings found in the App settings section of the Developer Console.
### Developer Console, Projects, and developer Apps
To retrieve a set of authentication credentials that will work with the X API v2 endpoints, you must have a \[developer account]/resources/fundamentals/developer-portal), set up a [Project](/resources/fundamentals/developer-apps) within that account, and created a [developer App](/resources/fundamentals/developer-apps) within that Project. You can then find your keys and tokens within your developer App.
### Rate limits
Every day, many thousands of developers make requests to the X API. To help manage the sheer volume of these requests, [rate limits](https://developer.x.com/x-api/fundamentals/rate-limits) are placed on each endpoint that limits the number of requests that you can make on behalf of your app or on behalf of an authenticated user.
These endpoints are rate limited at the user level, meaning that the authenticated user that you are making the request on behalf of can only call the endpoint a certain number of times across any developer App. There is a user rate limit of 200 requests per 15 minutes for the POST method. The DELETE method has a rate limit of 50 requests for 15 minutes. Additionally, there is a limit of [300 requests per 3 hours](https://blog.x.com/developer/en_us/topics/tools/2018/new-developer-requirements-to-protect-our-platform), including Posts created with either manage Posts or manage Retweets.
### Source labels
Your App name and website URL will be shown as the [source label](https://help.x.com/en/using-twitter/how-to-tweet#source-labels) within metadata for any Posts created programmatically by your application. If you change the use case of a X App, be sure to update the use case in these settings in order to ensure you are in compliance with the [Developer Terms](https://developer.x.com/content/developer-twitter/en/developer-terms/agreement-and-policy).
### Profile settings
You can only add a location to Posts if you have geo enabled in your profile settings. If you don't have geo enabled, you can still add a location parameter in your request body, but it won't get attached to your Post. The same is also true for tagging users in images. If the user you're tagging doesn't have photo-tagging enabled, their names won't show up in the list of tagged users even though the Post is successfully created.
### Adding media to a Post
Currently, isn't a way to fully upload media using v2 of the X API currently. However, you attach previously uploaded media to a Post. You can use media IDs that have been already [uploaded using the media upload endpoint](/x-api/media/upload-media) or [X Media Studio](https://media.x.com/en/articles/products/2018/media-studio). These media ids must be your own or that of an authenticated user.
***
## Code examples
### Create a Post
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"text": "Hello world!"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Create a Post
response = client.posts.create(text="Hello world!")
print(f"Created Post: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Create a Post
const response = await client.posts.create({ text: "Hello world!" });
console.log(`Created Post: ${response.data?.id}`);
```
### Create a reply
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"text": "This is a reply!", "reply": {"in_reply_to_tweet_id": "1234567890"}}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Create a reply
response = client.posts.create(
text="This is a reply!",
reply={"in_reply_to_tweet_id": "1234567890"}
)
print(f"Created reply: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Create a reply
const response = await client.posts.create({
text: "This is a reply!",
reply: { inReplyToTweetId: "1234567890" },
});
console.log(`Created reply: ${response.data?.id}`);
```
### Delete a Post
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/tweets/1234567890" \
-H "Authorization: OAuth ..."
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Delete a Post
response = client.posts.delete("1234567890")
print(f"Deleted: {response.data.deleted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Delete a Post
const response = await client.posts.delete("1234567890");
console.log(`Deleted: ${response.data?.deleted}`);
```
**Next steps**
[API reference](/x-api/posts/manage-tweets#manage-tweets-api-reference-index)
# Manage Posts on the Enterprise X API
Source: https://docs.x.com/enterprise-api/posts/manage-tweets/introduction
Create and delete Posts on behalf of authenticated users with the Enterprise X API manage Posts endpoints. Includes request and response details.
The Manage Posts endpoints let you create and delete Posts on behalf of authenticated users. Build applications that post content, create threads, or manage user Posts.
## Overview
Publish a new Post
Delete an existing Post
Reply to another Post
Quote another Post
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :------------------------------------------ | :---------------- |
| POST | [`/2/tweets`](/x-api/posts/create-post) | Create a new Post |
| DELETE | [`/2/tweets/:id`](/x-api/posts/delete-post) | Delete a Post |
***
## Creating Posts
### Basic Post
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text": "Hello from the API!"}'
```
### Reply to a Post
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "This is a reply!",
"reply": {
"in_reply_to_tweet_id": "1234567890"
}
}'
```
### Quote a Post
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Check this out!",
"quote_tweet_id": "1234567890"
}'
```
### Post with media
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Photo of the day",
"media": {
"media_ids": ["1234567890123456789"]
}
}'
```
Upload media first using the [Media Upload endpoint](/x-api/media/quickstart/media-upload-chunked), then reference the `media_id` in your Post.
### Post with poll
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "What is your favorite color?",
"poll": {
"options": ["Red", "Blue", "Green", "Yellow"],
"duration_minutes": 1440
}
}'
```
### Post with paid partnership
Use the `paid_partnership` field when creating a Post to indicate it is a paid partnership (i.e., the author is disclosing that the Post contains paid promotion). When set to `true`, the Post will be labeled as a paid promotion.
```bash theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Excited to partner with Acme on their latest launch!",
"paid_partnership": true
}'
```
To retrieve the value on existing Posts (including your own), request it via the `tweet.fields` parameter:
```bash theme={null}
curl "https://api.x.com/2/tweets/1234567890?tweet.fields=paid_partnership,created_at" \
-H "Authorization: Bearer $TOKEN"
```
***
## Deleting Posts
```bash theme={null}
curl -X DELETE "https://api.x.com/2/tweets/1234567890" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
You can only delete Posts authored by the authenticated user.
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) or [3-legged OAuth](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow)
Create your first Post
Key concepts and best practices
Upload media for Posts
Full endpoint documentation
# Enterprise manage Posts v2 migration
Source: https://docs.x.com/enterprise-api/posts/manage-tweets/migrate/overview
Compare Standard v1.1 statuses endpoints with the X API v2 manage Posts endpoints for creating, deleting, and editing Posts, with parameter mappings.
## Comparing X API’s manage Posts endpoints
The v2 manage Posts endpoints will replace the standard v1.1 [POST statuses/update](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-update) and [POST statuses/destroy/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-destroy-id) endpoints. If you have code, apps, or tools that use the v1.1 version of the manage Posts endpoints and are considering migrating to the newer X API v2 endpoint, then this set of guides is for you.
The following tables compare the standard v1.1 and X API v2 manage Posts endpoints:
### Create a Post
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP methods supported | POST | POST |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/statuses/update.json | /2/tweets |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
300 requests per 3-hour window per user, per app. Shared with the v1.1 POST Retweets endpoint. | 200 requests per 15 min per user
300 requests per 3-hour window per user, per app. Shared with the v2 POST Retweets endpoint. |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) | | ✔ |
### Delete a Post
| Description | Standard v1.1 | X API v2 |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- | :------------------------------------------------------------------------ |
| HTTP methods supported | POST | DELETE |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/statuses/destroy/:id.json | /2/tweets/:id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/x-api/fundamentals/rate-limits) | None | 50 requests per 15 min per user |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) | | ✔ |
### Other migration resources
[Manage Posts: Standard v1.1 to X API v2](/x-api/posts/manage-tweets#standard-v1-1-compared-to-x-api-v2 "Manage Posts: Standard v1.1 to X API v2")
[X API migration hub](/x-api/migrate/overview)
# v1 to v2
Source: https://docs.x.com/enterprise-api/posts/manage-tweets/migrate/standard-to-twitter-api-v2
If you have been working with the standard v1.1 POST statuses/update and POST statuses/destroy/:id. Reference for the Enterprise X API tier covering migrate.
## Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [POST statuses/update](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-update) and [POST statuses/destroy/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-destroy-id) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard and X API v2 manage Posts endpoints.
* **Similarities**
* Authentication
* **Differences**
* Endpoint URLs
* App and Project requirements
* Request parameters
### Similarities
**Authentication**
Both the standard v1.1 and X API v2 manage Posts ([POST statuses/update](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-update) and [POST statuses/destroy/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-destroy-id)) endpoints use [OAuth 1.0a User Context](https://developer.x.com/content/developer-twitter/resources/fundamentals/authentication). Therefore, if you were previously using one of the standard v1.1 endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* [https://api.x.com/1.1/statuses/update.json](https://api.x.com/1.1/statuses/update.json)
(Creates a Post)
* `https://api.x.com/1.1/statuses/destroy/:id.json`
(Deletes a Post)
* X API v2 endpoint:
* [https://api.x.com/2/tweets](https://api.x.com/2/tweets)
(Creates a Post)
* [https://api.x.com/2/tweets/:id](https://api.x.com/2/tweets/:id)
(Deletes a specified Post)
### App and Project requirements
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated to a [Project](/resources/fundamentals/developer-apps) when authenticating your requests.
# Enterprise manage Posts quickstart
Source: https://docs.x.com/enterprise-api/posts/manage-tweets/quickstart
Step-by-step quickstart for creating and deleting Posts with the Enterprise X API, including authentication, request payloads, and example responses.
This guide walks you through creating and deleting Posts using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Tokens (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Create a Post
The POST `/2/tweets` endpoint requires a JSON body with at least `text` or `media`:
```json theme={null}
{
"text": "Hello from the X API!"
}
```
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text": "Hello from the X API!"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Create a Post
response = client.posts.create(text="Hello from the X API!")
print(f"Created Post: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Create a Post
const response = await client.posts.create({ text: "Hello from the X API!" });
console.log(`Created Post: ${response.data?.id}`);
```
A successful response includes the new Post's `id` and `text`:
```json theme={null}
{
"data": {
"id": "1445880548472328192",
"text": "Hello from the X API!"
}
}
```
***
## Advanced examples
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "This is a reply!",
"reply": {
"in_reply_to_tweet_id": "1234567890"
}
}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Create a reply
response = client.posts.create(
text="This is a reply!",
reply={"in_reply_to_tweet_id": "1234567890"}
)
print(f"Created reply: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Create a reply
const response = await client.posts.create({
text: "This is a reply!",
reply: { inReplyToTweetId: "1234567890" },
});
console.log(`Created reply: ${response.data?.id}`);
```
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Check this out!",
"quote_tweet_id": "1234567890"
}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Quote a Post
response = client.posts.create(
text="Check this out!",
quote_tweet_id="1234567890"
)
print(f"Created quote: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Quote a Post
const response = await client.posts.create({
text: "Check this out!",
quoteTweetId: "1234567890",
});
console.log(`Created quote: ${response.data?.id}`);
```
First, upload media using the [Media Upload endpoint](/x-api/media/quickstart/media-upload-chunked), then reference the `media_id`:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Photo of the day!",
"media": {
"media_ids": ["1234567890123456789"]
}
}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Post with media
response = client.posts.create(
text="Photo of the day!",
media={"media_ids": ["1234567890123456789"]}
)
print(f"Created Post with media: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Post with media
const response = await client.posts.create({
text: "Photo of the day!",
media: { mediaIds: ["1234567890123456789"] },
});
console.log(`Created Post with media: ${response.data?.id}`);
```
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "What is your favorite color?",
"poll": {
"options": ["Red", "Blue", "Green", "Yellow"],
"duration_minutes": 1440
}
}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Post with poll
response = client.posts.create(
text="What is your favorite color?",
poll={"options": ["Red", "Blue", "Green", "Yellow"], "duration_minutes": 1440}
)
print(f"Created poll: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Post with poll
const response = await client.posts.create({
text: "What is your favorite color?",
poll: { options: ["Red", "Blue", "Green", "Yellow"], durationMinutes: 1440 },
});
console.log(`Created poll: ${response.data?.id}`);
```
Use the `paid_partnership` field to indicate that this Post is a paid partnership (i.e., the author is disclosing it contains paid promotion). When set to `true`, the Post will be labeled as a paid promotion.
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/tweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Excited to partner with Acme on their latest launch!",
"paid_partnership": true
}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Post with paid partnership
response = client.posts.create(
text="Excited to partner with Acme on their latest launch!",
paid_partnership=True
)
print(f"Created paid partnership post: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Post with paid partnership
const response = await client.posts.create({
text: "Excited to partner with Acme on their latest launch!",
paidPartnership: true,
});
console.log(`Created paid partnership post: ${response.data?.id}`);
```
***
## Delete a Post
You need the ID of the Post you want to delete. This is returned when you create a Post.
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/tweets/1445880548472328192" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Delete a Post
response = client.posts.delete("1445880548472328192")
print(f"Deleted: {response.data.deleted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Delete a Post
const response = await client.posts.delete("1445880548472328192");
console.log(`Deleted: ${response.data?.deleted}`);
```
```json theme={null}
{
"data": {
"deleted": true
}
}
```
You can only delete Posts that you authored.
***
## Next steps
Key concepts and best practices
Upload media for Posts
Full endpoint documentation
Working code examples
# Quote Posts
Source: https://docs.x.com/enterprise-api/posts/quote-tweets/introduction
The Quote Posts endpoint lets you retrieve Posts that quote a specific Post. Reference for the Enterprise X API tier covering quote tweets.
The Quote Posts endpoint lets you retrieve Posts that quote a specific Post. See how users are commenting on and sharing content.
## Overview
Get all Quote Posts for a Post
See how content is being discussed
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------ | :------------------------- |
| GET | [`/2/tweets/:id/quote_tweets`](/x-api/posts/get-quoted-posts) | Get Quote Posts for a Post |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/tweets/1234567890/quote_tweets?\
tweet.fields=created_at,author_id,public_metrics&\
expansions=author_id&\
user.fields=username" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example response
```json theme={null}
{
"data": [
{
"id": "9876543210",
"text": "Great point! This is exactly what we need.",
"author_id": "1111111111",
"created_at": "2024-01-15T10:30:00.000Z"
}
],
"includes": {
"users": [
{
"id": "1111111111",
"username": "example_user"
}
]
},
"meta": {
"result_count": 1
}
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Get Quote Posts for a Post
Full endpoint documentation
# Quickstart
Source: https://docs.x.com/enterprise-api/posts/quote-tweets/quickstart
This guide walks you through retrieving Quote Posts (Posts that quote another Post). Reference for the Enterprise X API tier covering quote tweets.
This guide walks you through retrieving Quote Posts (Posts that quote another Post).
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
Get the ID of the Post you want to find quotes for. You can find it in the Post's URL:
```
https://x.com/XDevelopers/status/1409931481552543749
└── This is the Post ID
```
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1409931481552543749/quote_tweets?\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id&\
user.fields=username,verified&\
max_results=10" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get Quote Posts with pagination
for page in client.posts.get_quote_tweets(
"1409931481552543749",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id"],
user_fields=["username", "verified"],
max_results=10
):
for post in page.data:
print(f"{post.text[:50]}... - Likes: {post.public_metrics.like_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get Quote Posts with pagination
const paginator = client.posts.getQuoteTweets("1409931481552543749", {
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id"],
userFields: ["username", "verified"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}... - Likes: ${post.public_metrics?.like_count}`);
});
}
```
```json theme={null}
{
"data": [
{
"id": "1495979553889697792",
"text": "Great thread on the new API features! https://t.co/...",
"author_id": "29757971",
"created_at": "2022-02-22T04:31:34.000Z",
"public_metrics": {
"retweet_count": 5,
"reply_count": 2,
"like_count": 42,
"quote_count": 1
},
"edit_history_tweet_ids": ["1495979553889697792"]
}
],
"includes": {
"users": [
{
"id": "29757971",
"username": "developer",
"verified": false
}
]
},
"meta": {
"result_count": 1,
"next_token": "avdjwk0udyx6"
}
}
```
The SDKs handle pagination automatically. For cURL, use the `next_token` to get more Quote Posts:
```bash theme={null}
curl "https://api.x.com/2/tweets/1409931481552543749/quote_tweets?\
max_results=10&\
pagination_token=avdjwk0udyx6" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Next steps
Look up Retweets
Look up Posts by ID
Full endpoint documentation
# Integration guide
Source: https://docs.x.com/enterprise-api/posts/retweets/integrate
This page covers tools and key concepts for integrating the Retweet endpoints. Reference for the Enterprise X API tier covering retweets.
This page covers tools and key concepts for integrating the Retweet endpoints.
## Helpful tools
Before we dive into some key concepts that will help you integrate this endpoint, we recommend that you become familiar with:
#### Postman
Postman is a great tool that you can use to test out an endpoint. Each Postman request includes every path and body parameter to help you quickly understand what is available to you. To learn more about our Postman collections, please visit our ["Using Postman"](/tutorials/postman-getting-started) page.
#### Code samples
Interested in getting set up with this endpoint with some code in your preferred coding language? We've got a handful of different code samples available that you can use as a starting point on our [Github page](https://github.com/xdevplatform/Twitter-API-v2-sample-code).
#### Third-party libraries
Take advantage of one of our communities' [third-party libraries](/tools-and-libraries) to help you get started. You can find a library that works with the v2 endpoints by looking for the proper version tag.
### Key concepts
#### Authentication
All X API v2 endpoints require for you to authenticate your requests with a set of credentials, also known as keys and tokens.
You can use either OAuth 1.0a User Context or OAuth 2.0 Bearer Token to authenticate your requests to the Retweets lookup endpoint.
The manage Retweets endpoints require the use of OAuth 1.0a User Context, which means that you must use a set of API keys and user access tokens to make a successful request. The access tokens must be associated with the user that you are making the request on behalf of. If you would like to generate a set of access tokens for another user, they must authorize or authenticate your App using the 3-legged OAuth flow.
Please note that OAuth 1.0a can be tricky to use. If you are not familiar with this authentication method, we recommend that you use a [library](/tools-and-libraries) to properly authenticate your requests.
**Please note**
If you are requesting the following fields, OAuth 1.0a User Context is required:
* tweet.fields.non\_public\_metrics
* tweet.fields.promoted\_metrics
* tweet.fields.organic\_metrics
* media.fields.non\_public\_metrics
* media.fields.promoted\_metrics
* media.fields.organic\_metrics
#### Developer Console, Projects, and developer Apps
To retrieve a set of authentication credentials that will work with the X API v2 endpoints, you must [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info), set up a [Project](/resources/fundamentals/developer-apps) within that account, and created a [developer App](/resources/fundamentals/developer-apps) within that Project. You can then find your keys and tokens within your developer App.
#### Rate limits
Every day, many thousands of developers make requests to the X API. To help manage the sheer volume of these requests, [rate limits](/x-api/fundamentals/rate-limits) are placed on each endpoint that limits the number of requests that you can make on behalf of your app or on behalf of an authenticated user.
The manage Retweets endpoints are limited to 50 requests per 15 min (per user). Additionally, for the POST endpoint, you are limited to 300 requests per 3-hour window (per user, per app).
With the Retweets lookup endpoint, you are limited to 75 requests per 15-min window. Additionally, only the 100 most recent Retweeting users will be returned by this endpoint.
#### Fields and expansions
The X API v2 allows users to select exactly which data they want to return from the API using a set of tools called fields and expansions. The expansion parameter allows you to expand objects referenced in the payload. For example, this endpoint allows you to pull the following [expansions](/x-api/fundamentals/expansions):
* attachments.poll\_ids
* attachments.media\_keys
* author\_id, entities.mentions.username
* geo.place\_id
* in\_reply\_to\_user\_id,
* referenced\_tweets.id,
* referenced\_tweets.id.author\_id
The fields parameter allows you to select exactly which [fields](/x-api/fundamentals/fields) within the different data objects you would like to receive. These endpoints delivers Post objects primarily. By default, the Post object returns the id and text fields. To receive additional fields such as tweet.created\_at or tweet.entities, you will have to specifically request those using a fields parameter. Some important fields that you may want to consider using in your integration are our poll data, metrics, Post annotations, and conversation ID fields.
We've added a guide on how to [use fields and expansions](/x-api/fundamentals/data-dictionary/reference#how-to-use-fields-and-expansions) together to our [X API v2 data dictionary](/x-api/fundamentals/data-dictionary).
***
### Code examples
#### Get users who retweeted a Post
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1234567890/retweeted_by?user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get users who retweeted a Post
response = client.posts.get_retweeted_by(
"1234567890",
user_fields=["username", "verified"]
)
for user in response.data:
print(f"{user.username} - Verified: {user.verified}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get users who retweeted a Post
const response = await client.posts.getRetweetedBy("1234567890", {
userFields: ["username", "verified"],
});
response.data?.forEach((user) => {
console.log(`${user.username} - Verified: ${user.verified}`);
});
```
#### Retweet a Post
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/123/retweets" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1234567890"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Retweet a Post
response = client.posts.retweet(user_id="123", tweet_id="1234567890")
print(response.data)
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Retweet a Post
const response = await client.posts.retweet("123", { tweetId: "1234567890" });
console.log(response.data);
```
# Retweets
Source: https://docs.x.com/enterprise-api/posts/retweets/introduction
The Retweets endpoints let you retweet and undo retweets, see who retweeted a Post, and get. Reference for the Enterprise X API tier covering retweets.
The Retweets endpoints let you retweet and undo retweets, see who retweeted a Post, and get reposts of your own Posts.
## Overview
Retweet a Post on behalf of a user
Remove a retweet
See who retweeted a Post
Get reposts of your own Posts
***
## Endpoints
### Retweets lookup
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------ | :---------------------------------------- |
| GET | [`/2/tweets/:id/retweeted_by`](/x-api/posts/get-reposted-by) | Get users who retweeted a Post |
| GET | [`/2/tweets/:id/quote_tweets`](/x-api/posts/get-quoted-posts) | Get quote Posts of a Post |
| GET | [`/2/users/reposts_of_me`](/x-api/users/get-reposts-of-me) | Get reposts of authenticated user's Posts |
### Manage retweets
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------------------- | :------------- |
| POST | [`/2/users/:id/retweets`](/x-api/users/repost-post) | Retweet a Post |
| DELETE | [`/2/users/:id/retweets/:tweet_id`](/x-api/users/unrepost-post) | Undo a retweet |
***
## Example: Get retweeting users
```bash theme={null}
curl "https://api.x.com/2/tweets/1234567890/retweeted_by?\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example: Retweet a Post
```bash theme={null}
curl -X POST "https://api.x.com/2/users/123456789/retweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1234567890"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Get retweets for a Post
Retweet and undo retweets
Get reposts of your Posts
Full endpoint documentation
# Manage Retweets
Source: https://docs.x.com/enterprise-api/posts/retweets/migrate/manage-retweets-standard-to-twitter-api-v2
If you have been working with the standard v1.1 POST statuses/retweet/:id, and POST. Reference for the Enterprise X API tier covering migrate.
### Manage Retweets: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [POST statuses/retweet/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-retweet-id), and [POST statuses/unretweet/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-unretweet-id) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard and X API v2 Retweets endpoints.
* **Similarities**
* Authentication
* **Differences**
* Endpoint URLs and HTTP methods
* Request limitations
* App and Project requirements
* Request parameters
#### Similarities
**Authentication**
Both the standard v1.1 and X API v2 manage Retweets ([POST statuses/retweet/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-retweet-id), and [POST statuses/unretweet/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-unretweet-id)) endpoints use [OAuth 1.0a User Context](https://developer.x.com/content/developer-twitter/resources/fundamentals/authentication). Therefore, if you were previously using one of the standard v1.1 Retweets lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs and HTTP methods**
* Standard v1.1 endpoints:
* [https://api.x.com/1.1/statuses/retweet/:id.json](https://api.x.com/1.1/statuses/retweet/:id.json)
(Retweets a Post. Returns the original Post with Retweet details embedded)
* [https://api.x.com/1.1/statuses/unretweet/:id.json](https://api.x.com/1.1/statuses/unretweet/:id.json)
(Undo a Retweet. Returns the original Post with Retweet details embedded)
* X API v2 endpoint:
* [https://api.x.com/2/tweets/:id/retweets](https://api.x.com/2/tweets/:id/retweets)
(Retweets a given Post)
* [https://api.x.com/2/users/:id/retweets/:source\\\_tweet\\\_id](https://api.x.com/2/users/:id/retweets/:source\\_tweet\\_id)
(Undo a Retweet of a given Post)
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated to a [Project](/resources/fundamentals/developer-apps) when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps associated with an App.
**Request parameters**
The following standard v1.1 request parameters accepted two request query parameters (user\_id or screen\_name). The X API v2 only accepts the numerical user ID, and it must be passed as part of the endpoint path.
| Standard v1.1 | X API v2 |
| :--------------------- | :------------ |
| **id** | **id** |
| **includes\_entities** | No equivalent |
Please note that the Standard v1.1 parameters are passed as query parameters, whereas the X API v2 parameters are passed as body parameters for the POST endpoint or path parameters for the DELETE endpoint.
Also, an id of the user Retweeting a Post is not required when using the standard v1.1 endpoints since the [Access Tokens](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow) passed with [OAuth 1.0a User Context](/resources/fundamentals/authentication) infer which user is initiating the Retweet/undoing a Retweet.
***
## Code examples
### Retweet a Post (v2)
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/123456789/retweets" \
-H "Authorization: OAuth ..." \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1234567890"}'
```
```python Python theme={null}
# Requires OAuth 1.0a User Context authentication
import requests
from requests_oauthlib import OAuth1
auth = OAuth1(
"API_KEY", "API_SECRET",
"ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"
)
url = "https://api.x.com/2/users/123456789/retweets"
response = requests.post(url, auth=auth, json={"tweet_id": "1234567890"})
print(response.json())
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Retweet a Post
response = client.posts.retweet(user_id="123456789", tweet_id="1234567890")
print(f"Retweeted: {response.data.retweeted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Retweet a Post
const response = await client.posts.retweet("123456789", { tweetId: "1234567890" });
console.log(`Retweeted: ${response.data?.retweeted}`);
```
### Undo a Retweet (v2)
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/123456789/retweets/1234567890" \
-H "Authorization: OAuth ..."
```
```python Python theme={null}
# Requires OAuth 1.0a User Context authentication
import requests
from requests_oauthlib import OAuth1
auth = OAuth1(
"API_KEY", "API_SECRET",
"ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"
)
url = "https://api.x.com/2/users/123456789/retweets/1234567890"
response = requests.delete(url, auth=auth)
print(response.json())
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Undo a Retweet
response = client.posts.unretweet(user_id="123456789", tweet_id="1234567890")
print(f"Retweeted: {response.data.retweeted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Undo a Retweet
const response = await client.posts.unretweet("123456789", "1234567890");
console.log(`Retweeted: ${response.data?.retweeted}`);
```
# Enterprise Reposts endpoints v2 migration
Source: https://docs.x.com/enterprise-api/posts/retweets/migrate/overview
Compare Standard v1.1 retweets endpoints with the X API v2 manage Reposts and Reposts lookup endpoints, including parameters and authentication.
## Comparing X API’s Retweets endpoints
**Retweets lookup**
The v2 Retweets lookup endpoint will replace the standard [v1.1 GET statuses/retweets/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweets-id) and [v1.1 GET statuses/retweets/:ids](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweeters-ids) endpoints.
The following tables compare the standard v1.1 and X API v2 Retweets endpoints:
| Description | Standard v1.1 | X API v2 |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP methods supported | GET | GET |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/retweeters/id.json
OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 75 requests per 15 min | 75 requests per 15 min (per App)
75 requests per 15 min (per user) |
| Data format | Standard v1.1 format | [X API v2 format](/x-api/fundamentals/data-dictionary) (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
### Manage Retweets
The following tables compare the standard v1.1 and X API v2 undo Retweet endpoint:
**Retweet a Post**
| Description | Standard v1.1 | X API v2 |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP methods supported | POST | POST |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/statuses/retweet/:id.json | /2/users/:id/retweets |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | None
300 requests per 3-hour window (per user, per app). This is shared with the POST Tweet endpoint | 50 requests per 15 min (per user)
300 requests per 3-hour window (per user, per app). This is shared with the POST Tweet endpoint for manage Posts. |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
#### Undo a Retweet
The following tables compare the standard v1.1 and X API v2 undo Retweet endpoint:
| Description | Standard v1.1 | X API v2 |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- | :--------------------------------------- |
| HTTP methods supported | POST | DELETE |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/statuses/unretweet/:id.json | /2/users/:id/retweets/:source\_tweet\_id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context |
| Default request [rate limits](/resources/fundamentals/rate-limits) | None | 50 requests per 15 min (per user) |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
**Other migration resources**
[Retweets lookup: Standard v1.1 to X API v2](/x-api/posts/retweets#retweets-lookup-standard-v1-1-compared-to-x-api-v2 "Retweets lookup: Standard v1.1 to X API v2")
[Manage Retweets: Standard v1.1 to X API v2](/x-api/posts/retweets#manage-retweets-standard-v1-1-compared-to-x-api-v2)
[X API migration hub](/x-api/migrate/overview)
# Retweets lookup
Source: https://docs.x.com/enterprise-api/posts/retweets/migrate/retweets-lookup-standard-to-twitter-api-v2
If you have been working with the standard v1.1 v1.1 GET statuses/retweets/:id, v1.1 GET. Reference for the Enterprise X API tier covering migrate.
### Retweets lookup: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [v1.1 GET statuses/retweets/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweets-id), [v1.1 GET statuses/retweets/:ids](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweeters-ids), the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 Retweets lookup endpoints.
* **Similarities**
* Authentication
* Users per request limits
* **Differences**
* Endpoint URLs
* Request limitations
* App and Project requirements
* Response data format
* Request parameters
#### Similarities
**Authentication**
Both the standard v1.1 and X API v2 Retweets lookup endpoints ([v1.1 GET statuses/retweets/:id](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweets-id) and [v1.1 GET statuses/retweeters/:ids](https://developer.x.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweeters-ids)) use [OAuth 1.0a User Context](https://developer.x.com/content/developer-twitter/resources/fundamentals/authentication) or OAuth 2.0 Bearer Token.
**Users per request limits**
For both v1.1 and v2 GET endpoints the max number of users that will be returned by the Retweets lookup endpoint is 100 users. For the v2 Retweets lookup endpoint, there is no pagination token being passed, by default we give out 100 users and that's the max that is returned.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* [https://api.x.com/1.1/statuses/retweets/:id.json](https://api.x.com/1.1/statuses/retweets/:id.json)
(Returns a collection of the 100 most recent
# Manage Retweets
Source: https://docs.x.com/enterprise-api/posts/retweets/quickstart/manage-retweets
This guide walks you through Retweeting and undoing Retweets using the X API. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through Retweeting and undoing Retweets using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Retweet a Post
You need your authenticated user's ID. You can find it using the [user lookup endpoint](/x-api/users/lookup/introduction) or from your Access Token (the numeric part is your user ID).
Find the Post ID in the URL when viewing a Post:
```
https://x.com/XDevelopers/status/1228393702244134912
└── This is the Post ID
```
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/123456789/retweets" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"tweet_id": "1228393702244134912"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Retweet a Post
response = client.posts.retweet(
user_id="123456789",
tweet_id="1228393702244134912"
)
print(f"Retweeted: {response.data.retweeted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Retweet a Post
const response = await client.posts.retweet("123456789", {
tweetId: "1228393702244134912",
});
console.log(`Retweeted: ${response.data?.retweeted}`);
```
```json theme={null}
{
"data": {
"retweeted": true
}
}
```
***
## Undo a Retweet
Remove a Retweet:
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/123456789/retweets/1228393702244134912" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Undo a Retweet
response = client.posts.unretweet(
user_id="123456789",
tweet_id="1228393702244134912"
)
print(f"Retweeted: {response.data.retweeted}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Undo a Retweet
const response = await client.posts.unretweet("123456789", "1228393702244134912");
console.log(`Retweeted: ${response.data?.retweeted}`);
```
**Response:**
```json theme={null}
{
"data": {
"retweeted": false
}
}
```
***
## Next steps
Get users who Retweeted a Post
Get Quote Posts
Full endpoint documentation
# Retweets Lookup
Source: https://docs.x.com/enterprise-api/posts/retweets/quickstart/retweets-lookup
This guide walks you through retrieving users who Retweeted a specific Post. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through retrieving users who Retweeted a specific Post.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token (for public data) or User Access Token (for private metrics)
***
## Get users who Retweeted a Post
Get the ID of the Post you want to look up Retweets for:
```
https://x.com/XDevelopers/status/1354143047324299264
└── This is the Post ID
```
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1354143047324299264/retweeted_by?\
user.fields=created_at,username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get users who Retweeted a Post with pagination
for page in client.posts.get_retweeted_by(
"1354143047324299264",
user_fields=["created_at", "username", "verified"]
):
for user in page.data:
print(f"{user.username} - Joined: {user.created_at}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get users who Retweeted a Post with pagination
const paginator = client.posts.getRetweetedBy("1354143047324299264", {
userFields: ["created_at", "username", "verified"],
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Joined: ${user.created_at}`);
});
}
```
```json theme={null}
{
"data": [
{
"created_at": "2008-12-04T18:51:57.000Z",
"id": "17874544",
"username": "TwitterSupport",
"name": "Twitter Support",
"verified": true
},
{
"created_at": "2007-02-20T14:35:54.000Z",
"id": "783214",
"username": "Twitter",
"name": "Twitter",
"verified": true
}
],
"meta": {
"result_count": 2,
"next_token": "7140dibdnow9c7btw3z2vwioavpvutgzrzm9icis4ndix"
}
}
```
***
## Include additional data
Use expansions to get related data like pinned Posts:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/1354143047324299264/retweeted_by?\
user.fields=created_at&\
expansions=pinned_tweet_id&\
tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get Retweeting users with expansions
for page in client.posts.get_retweeted_by(
"1354143047324299264",
user_fields=["created_at"],
expansions=["pinned_tweet_id"],
tweet_fields=["created_at"]
):
for user in page.data:
print(f"{user.username}")
# Pinned Posts are in page.includes.tweets
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get Retweeting users with expansions
const paginator = client.posts.getRetweetedBy("1354143047324299264", {
userFields: ["created_at"],
expansions: ["pinned_tweet_id"],
tweetFields: ["created_at"],
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(user.username);
});
// Pinned Posts are in page.includes?.tweets
}
```
### Response with expansion
```json theme={null}
{
"data": [
{
"pinned_tweet_id": "1389270063807598594",
"created_at": "2018-11-21T14:24:58.000Z",
"id": "1065249714214457345",
"username": "TwitterSpaces",
"name": "Spaces"
}
],
"includes": {
"tweets": [
{
"created_at": "2021-05-03T17:26:09.000Z",
"id": "1389270063807598594",
"text": "now, everyone with 600 or more followers can host a Space..."
}
]
}
}
```
***
## Next steps
Retweet and undo Retweets
Get Quote Posts
Full endpoint documentation
# Retweets of Me
Source: https://docs.x.com/enterprise-api/posts/retweets/quickstart/retweets-of-me
This guide walks you through retrieving your Posts that have been Retweeted by others. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through retrieving your Posts that have been Retweeted by others.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Why use Retweets of Me?
The Retweets of Me endpoint helps you:
* **Track engagement** — See which of your Posts are being shared
* **Understand resonance** — Learn what content resonates with your audience
* **Inform strategy** — Adjust your content strategy based on sharing patterns
***
## Get your Retweeted Posts
```bash cURL theme={null}
curl "https://api.x.com/2/users/reposts_of_me?\
tweet.fields=created_at,public_metrics&\
max_results=10" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get your Posts that have been Retweeted
for page in client.posts.get_reposts_of_me(
tweet_fields=["created_at", "public_metrics"],
max_results=10
):
for post in page.data:
print(f"{post.text[:50]}... - Retweets: {post.public_metrics.retweet_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get your Posts that have been Retweeted
const paginator = client.posts.getRepostsOfMe({
tweetFields: ["created_at", "public_metrics"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}... - Retweets: ${post.public_metrics?.retweet_count}`);
});
}
```
***
## Response
```json theme={null}
{
"data": [
{
"id": "1848781937210802364",
"text": "ever wanted to discover trends.. before they're trends?...",
"created_at": "2024-01-15T10:30:00.000Z",
"public_metrics": {
"retweet_count": 42,
"reply_count": 5,
"like_count": 156,
"quote_count": 8
},
"edit_history_tweet_ids": ["1848781937210802364"]
},
{
"id": "1847990559081648620",
"text": "posting is just journaling with an audience",
"created_at": "2024-01-14T15:20:00.000Z",
"public_metrics": {
"retweet_count": 28,
"reply_count": 12,
"like_count": 89,
"quote_count": 3
},
"edit_history_tweet_ids": ["1847990559081648620"]
}
],
"meta": {
"result_count": 2,
"next_token": "7140dibdnow9c7btw481s8m561gat797rboud5r80xvzm"
}
}
```
***
## Filter by time range
Get Retweeted Posts from a specific period:
```bash cURL theme={null}
curl "https://api.x.com/2/users/reposts_of_me?\
start_time=2024-01-01T00%3A00%3A00Z&\
end_time=2024-01-31T23%3A59%3A59Z&\
tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get Retweeted Posts from a time range
for page in client.posts.get_reposts_of_me(
start_time="2024-01-01T00:00:00Z",
end_time="2024-01-31T23:59:59Z",
tweet_fields=["created_at", "public_metrics"]
):
for post in page.data:
print(f"{post.created_at}: {post.text[:50]}...")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get Retweeted Posts from a time range
const paginator = client.posts.getRepostsOfMe({
startTime: "2024-01-01T00:00:00Z",
endTime: "2024-01-31T23:59:59Z",
tweetFields: ["created_at", "public_metrics"],
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.created_at}: ${post.text?.slice(0, 50)}...`);
});
}
```
***
## Common parameters
| Parameter | Description | Default |
| :----------------- | :------------------------------- | :----------- |
| `max_results` | Results per page (1-100) | 10 |
| `start_time` | Oldest Post timestamp (ISO 8601) | — |
| `end_time` | Newest Post timestamp (ISO 8601) | — |
| `pagination_token` | Token for next page | — |
| `tweet.fields` | Additional Post fields | `id`, `text` |
***
## Next steps
See who Retweeted a Post
Retweet and undo Retweets
Full endpoint documentation
# Search all Posts
Source: https://docs.x.com/enterprise-api/posts/search-all-posts
get /2/tweets/search/all
Retrieves Posts from the full archive matching a search query.
# Search recent Posts
Source: https://docs.x.com/enterprise-api/posts/search-recent-posts
get /2/tweets/search/recent
Retrieves Posts from the last 7 days matching a search query.
# Build a query
Source: https://docs.x.com/enterprise-api/posts/search/integrate/build-a-query
The search endpoints accept a single query with a GET request and return a set of historical. Reference for the Enterprise X API tier covering integrate.
The search endpoints accept a single query with a GET request and return a set of historical Posts that match the query. Queries are made up of operators that match on a variety of Post attributes.
***
## Query limitations
Your queries will be limited depending on which [access level](/x-api/getting-started/about-x-api) you are using:
| Access level | Recent search | Full-archive search |
| :----------- | :--------------- | :------------------ |
| Self-serve | 512 characters | 1,024 characters |
| Enterprise | 4,096 characters | 4,096 characters |
***
## Operator availability
While most operators are available to any developer, some are reserved for certain access levels:
* **Core operators:** Available when using any [Project](/resources/fundamentals/developer-apps)
* **Advanced operators:** Available when using a Project with certain access levels
See the complete [list of operators](/x-api/posts/search/integrate/operators) for availability details.
***
## Operator types: standalone and conjunction-required
**Standalone operators** can be used alone or together with any other operators (including those that require conjunction).
For example, this query works because `#hashtag` is a standalone operator:
```
#xapiv2
```
**Conjunction-required operators** cannot be used by themselves in a query; they can only be used when at least one standalone operator is included. This is because using these operators alone would match an extremely high volume of Posts.
For example, the following queries are **not supported** since they contain only conjunction-required operators:
```
has:media
```
```
has:links OR is:retweet
```
If we add a standalone operator, such as the phrase `"X data"`, the query works properly:
```
"X data" has:mentions (has:media OR has:links)
```
***
## Boolean operators and grouping
String together multiple operators using these tools:
| Operator | Description | Example |
| :------------------------- | :------------------------------------ | :---------------------------------------------------------------------- |
| **AND** (space) | Posts must match both conditions | `snow day #NoSchool` matches Posts with "snow" AND "day" AND #NoSchool |
| **OR** | Posts must match either condition | `grumpy OR cat OR #meme` matches Posts with "grumpy" OR "cat" OR #meme |
| **NOT** (dash) | Exclude Posts matching this condition | `cat #meme -grumpy` matches Posts with "cat" and #meme but NOT "grumpy" |
| **Grouping** (parentheses) | Group operators together | `(grumpy cat) OR (#meme has:images)` matches either group |
**A note on negations**
* The operator `-is:nullcast` must always be negated
* Negated operators cannot be used alone
* Do not negate grouped operators. Instead of `skiing -(snow OR day OR noschool)`, use `skiing -snow -day -noschool`
***
## Order of operations
When combining AND and OR:
1. Operators connected by AND logic are combined first
2. Then, operators connected with OR logic are applied
**Examples:**
| Query | Evaluated as |
| :----------------------- | :------------------------- |
| `apple OR iphone ipad` | `apple OR (iphone ipad)` |
| `ipad iphone OR android` | `(iphone ipad) OR android` |
To eliminate uncertainty, use parentheses:
```
(apple OR iphone) ipad
```
```
iphone (ipad OR android)
```
***
## Punctuation, diacritics, and case sensitivity
**Diacritics:** Search queries with accents or diacritics match Posts both with and without the accents. For example, `Diacrítica` matches both *Diacrítica* and *Diacritica*.
**Case sensitivity:** All operators are case-insensitive. The query `cat` matches *cat*, *CAT*, and *Cat*.
**Filtered stream behaves differently**
When [building filtered stream rules](/x-api/posts/filtered-stream/integrate/build-a-rule), keywords with accents only match Posts that also include the accent. For example, `Diacrítica` only matches *Diacrítica*, not *Diacritica*.
***
## Quote Tweet matching
When using Search Posts, operators match on the Quote Tweet's content but **not** on the content from the original Post that was quoted.
[Filtered stream](/x-api/posts/filtered-stream/introduction) behaves differently—it matches on both the Quote Tweet and the original Post's content.
***
## Specificity and efficiency
Using broad operators like a single keyword or hashtag is not recommended—it will match a massive volume of Posts and quickly consume your usage limits.
**Tips for building effective queries:**
1. **Start specific, then broaden** — Create targeted queries that return relevant results
2. **Use multiple operators** — Combine operators to narrow results
3. **Watch your character count** — The entire query string counts toward the limit
**Example progression:**
```
# Too broad - 200,000+ Posts per day
happy
# Better - adds language filter and exclusions
(happy OR happiness) lang:en -birthday -is:retweet
# Even better - 59 characters, more specific
(happy OR happiness) place_country:GB -birthday -is:retweet
```
***
## Iteratively building a query
### Step 1: Start with a basic query
```
happy OR happiness
```
### Step 2: Test and narrow based on results
We noticed Posts in many languages. Add a language filter:
```
(happy OR happiness) lang:en
```
We're getting birthday wishes. Exclude them and Retweets:
```
(happy OR happiness) lang:en -birthday -is:retweet
```
### Step 3: Broaden for better coverage
We want to capture more sentiment. Add related keywords:
```
(happy OR happiness OR excited OR elated) lang:en -birthday -is:retweet
```
### Step 4: Adjust for trends
Holiday Posts are appearing. Exclude them:
```
(happy OR happiness OR excited OR elated) lang:en -birthday -is:retweet -holidays
```
***
## Adding a query to your request
Use the `query` parameter and HTTP encode your query:
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?\
query=cat%20has%3Amedia%20-grumpy&\
tweet.fields=created_at&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Query examples
### Tracking a natural disaster
Match Posts from weather agencies about Hurricane Harvey:
**Query:**
```
has:geo (from:NWSNHC OR from:NHC_Atlantic OR from:NWSHouston OR from:NWSSanAntonio OR from:USGS_TexasRain OR from:USGS_TexasFlood OR from:JeffLindner1) -is:retweet
```
**Full request URL:**
```
https://api.x.com/2/tweets/search/recent?query=has%3Ageo%20(from%3ANWSNHC%20OR%20from%3ANHC_Atlantic%20OR%20from%3ANWSHouston%20OR%20from%3ANWSSanAntonio%20OR%20from%3AUSGS_TexasRain%20OR%20from%3AUSGS_TexasFlood%20OR%20from%3AJeffLindner1)%20-is%3Aretweet
```
### Sentiment analysis for #nowplaying
**Positive sentiment:**
```
#nowplaying (happy OR exciting OR excited OR favorite OR fav OR amazing OR lovely OR incredible) (place_country:US OR place_country:MX OR place_country:CA) -horrible -worst -sucks -bad -disappointing
```
**Negative sentiment:**
```
#nowplaying (horrible OR worst OR sucks OR bad OR disappointing) (place_country:US OR place_country:MX OR place_country:CA) -happy -exciting -excited -favorite -fav -amazing -lovely -incredible
```
### Using Post annotations
Find Japanese Posts about pets (not cats) with images using the `context:` operator:
First, use [Post lookup](/x-api/posts/lookup/introduction) with `tweet.fields=context_annotations` to identify domain.entity IDs:
* Cats: `domain` 66, `entity` 852262932607926273
* Pets: `domain` 65, `entity` 852262932607926273
**Query:**
```
context:65.852262932607926273 -context:66.852262932607926273 -is:retweet has:images lang:ja
```
***
## Tools
Build and test your queries interactively
***
## Next steps
Complete list of available operators
Make your first search request
Full integration documentation
# Search Operators
Source: https://docs.x.com/enterprise-api/posts/search/integrate/operators
This page provides a complete list of operators available when building a query for the Search. Reference for the Enterprise X API tier covering integrate.
This page provides a complete list of operators available when [building a query](/x-api/posts/search/integrate/build-a-query) for the Search API endpoints.
## Overview
Operators are used to match on specific Post attributes. There are two types:
* **Standalone operators** — Can be used alone or with any other operators
* **Conjunction-required operators** — Must be used with at least one standalone operator
***
## Keyword and phrase operators
| Operator | Type | Summary | Example |
| :--------------- | :--------- | :------------------------------------------------------- | :---------------------------------- |
| `keyword` | Standalone | Matches a keyword within the Post body (tokenized match) | `pepsi OR cola OR "coca cola"` |
| `emoji` | Standalone | Matches an emoji within the Post body | `(😃 OR 😡) 😬` |
| `"exact phrase"` | Standalone | Matches the exact phrase within the Post body | `("X API" OR #v2) -"recent search"` |
***
## Entity operators
| Operator | Type | Summary | Example |
| :------- | :--------- | :----------------------------------------------- | :--------------------------- |
| `#` | Standalone | Matches Posts containing a hashtag (exact match) | `#thankunext #fanart` |
| `@` | Standalone | Matches Posts mentioning a username | `(@XDevelopers OR @API) -@X` |
| `$` | Standalone | Matches Posts containing a cashtag | `$twtr OR @XDevelopers -$fb` |
***
## User operators
| Operator | Type | Summary | Example |
| :------------- | :--------- | :---------------------------------------- | :----------------------------- |
| `from:` | Standalone | Matches Posts from a specific user | `from:XDevelopers OR from:API` |
| `to:` | Standalone | Matches Posts in reply to a specific user | `to:XDevelopers OR to:API` |
| `retweets_of:` | Standalone | Matches Retweets of a specific user | `retweets_of:twitterdev` |
***
## URL operators
| Operator | Type | Summary | Example |
| :------- | :--------- | :-------------------------------------------------------------- | :------------------------------------ |
| `url:` | Standalone | Tokenized match on URL (matches `url` or `expanded_url` fields) | `url:"https://developer.twitter.com"` |
***
## Context and entity operators
| Operator | Type | Summary | Example |
| :----------------- | :--------- | :--------------------------------------------------------------------- | :------------------------------------ |
| `context:` | Standalone | Matches Posts with a specific domain/entity pair | `context:10.799022225751871488` |
| `entity:` | Standalone | Matches Posts with a specific entity string value (recent search only) | `entity:"Michael Jordan"` |
| `conversation_id:` | Standalone | Matches Posts in a conversation thread | `conversation_id:1334987486343299072` |
***
## List operator
| Operator | Type | Summary | Example |
| :------- | :--------- | :-------------------------------------------- | :--------- |
| `list:` | Standalone | Matches Posts from members of a specific List | `list:123` |
***
## Post reference operators
| Operator | Type | Summary | Example |
| :---------------------- | :--------- | :-------------------------------------- | :----------------------------------------- |
| `in_reply_to_tweet_id:` | Standalone | Matches replies to a specific Post | `in_reply_to_tweet_id:1539382664746020864` |
| `retweets_of_tweet_id:` | Standalone | Matches Retweets of a specific Post | `retweets_of_tweet_id:1539382664746020864` |
| `quotes_of_tweet_id:` | Standalone | Matches Quote Tweets of a specific Post | `quotes_of_tweet_id:1539382664746020864` |
***
## Location operators
| Operator | Type | Summary | Example |
| :--------------- | :--------- | :--------------------------------------- | :---------------------------------------------------------- |
| `place:` | Standalone | Matches Posts tagged with a location | `place:"new york city" OR place:seattle` |
| `place_country:` | Standalone | Matches Posts with a country code | `place_country:US OR place_country:MX` |
| `point_radius:` | Standalone | Matches Posts within a radius of a point | `point_radius:[2.355128 48.861118 16km]` |
| `bounding_box:` | Standalone | Matches Posts within a bounding box | `bounding_box:[-105.301758 39.964069 -105.178505 40.09455]` |
***
## Post type operators
| Operator | Type | Summary | Example |
| :------------- | :------------------- | :------------------------------------------- | :------------------------------ |
| `is:retweet` | Conjunction required | Matches Retweets | `data @XDevelopers -is:retweet` |
| `is:reply` | Conjunction required | Matches replies | `from:XDevelopers is:reply` |
| `is:quote` | Conjunction required | Matches Quote Tweets | `"sentiment analysis" is:quote` |
| `is:verified` | Conjunction required | Matches Posts from verified authors | `#nowplaying is:verified` |
| `-is:nullcast` | Conjunction required | Excludes promotional Posts (must be negated) | `"mobile games" -is:nullcast` |
***
## Content type operators
| Operator | Type | Summary | Example |
| :--------------- | :------------------- | :------------------------------------------- | :----------------------------------- |
| `has:hashtags` | Conjunction required | Matches Posts with hashtags | `from:XDevelopers -has:hashtags` |
| `has:cashtags` | Conjunction required | Matches Posts with cashtags | `#stonks has:cashtags` |
| `has:links` | Conjunction required | Matches Posts with links | `from:XDevelopers has:links` |
| `has:mentions` | Conjunction required | Matches Posts with mentions | `#nowplaying has:mentions` |
| `has:media` | Conjunction required | Matches Posts with media (photo, GIF, video) | `(kittens OR puppies) has:media` |
| `has:images` | Conjunction required | Matches Posts with images | `#meme has:images` |
| `has:video_link` | Conjunction required | Matches Posts with native X videos | `#icebucketchallenge has:video_link` |
| `has:geo` | Conjunction required | Matches Posts with geolocation data | `recommend #paris has:geo` |
***
## Language operator
| Operator | Type | Summary | Example |
| :------- | :------------------- | :---------------------------------------------- | :------------------------- |
| `lang:` | Conjunction required | Matches Posts classified as a specific language | `recommend #paris lang:en` |
***
## Logical operators
| Operator | Summary | Example |
| :---------- | :------------------------------- | :------------------------- |
| `OR` | Logical OR between expressions | `cat OR dog` |
| Space (AND) | Logical AND between expressions | `cat dog` (both required) |
| `()` | Grouping for complex expressions | `(cat OR dog) -is:retweet` |
| `-` | Negation/exclusion | `cat -grumpy` |
***
## Supported languages
The `lang:` operator supports these BCP 47 language codes:
| Language | Code | Language | Code | Language | Code |
| :-------- | :--- | :--------- | :--- | :------------------ | :------ |
| Amharic | `am` | Greek | `el` | Portuguese | `pt` |
| Arabic | `ar` | Gujarati | `gu` | Romanian | `ro` |
| Armenian | `hy` | Hebrew | `iw` | Russian | `ru` |
| Basque | `eu` | Hindi | `hi` | Serbian | `sr` |
| Bengali | `bn` | Hungarian | `hu` | Simplified Chinese | `zh-CN` |
| Bulgarian | `bg` | Indonesian | `in` | Slovak | `sk` |
| Catalan | `ca` | Italian | `it` | Slovenian | `sl` |
| Croatian | `hr` | Japanese | `ja` | Spanish | `es` |
| Czech | `cs` | Kannada | `kn` | Swedish | `sv` |
| Danish | `da` | Korean | `ko` | Tamil | `ta` |
| Dutch | `nl` | Latvian | `lv` | Telugu | `te` |
| English | `en` | Lithuanian | `lt` | Thai | `th` |
| Estonian | `et` | Malayalam | `ml` | Traditional Chinese | `zh-TW` |
| Finnish | `fi` | Marathi | `mr` | Turkish | `tr` |
| French | `fr` | Norwegian | `no` | Ukrainian | `uk` |
| German | `de` | Persian | `fa` | Urdu | `ur` |
| Georgian | `ka` | Polish | `pl` | Vietnamese | `vi` |
***
## Query limitations
| Access level | Recent search | Full-archive search |
| :----------- | :--------------- | :------------------ |
| Self-serve | 512 characters | 1,024 characters |
| Enterprise | 4,096 characters | 4,096 characters |
***
## Next steps
Learn query syntax and best practices
Get started with Search
Build and test queries interactively
# Integration Guide
Source: https://docs.x.com/enterprise-api/posts/search/integrate/overview
This guide covers the key concepts you need to integrate the Search Posts endpoints into your. Reference for the Enterprise X API tier covering integrate.
This guide covers the key concepts you need to integrate the Search Posts endpoints into your application.
***
## Authentication
### Recent search
Recent search supports multiple authentication methods:
| Method | Use case |
| :----------------------------------------------------------------------------------------------------------------------------- | :--------------- |
| [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) | Public Post data |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | Private metrics |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Private metrics |
### Full-archive search
Full-archive search only supports [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) authentication.
Private metrics (`non_public_metrics`, `organic_metrics`, `promoted_metrics`) are not available with full-archive search because it only supports App-Only authentication.
***
## Building queries
Queries use operators to match Posts. Combine operators with boolean logic:
```
(AI OR "machine learning") lang:en -is:retweet has:links
```
### Query length limits
| Access level | Recent search | Full-archive search |
| :----------- | :------------ | :------------------ |
| Self-serve | 512 chars | 1,024 chars |
| Enterprise | 4,096 chars | 4,096 chars |
### Operator types
| Type | Description | Example |
| :----------------------- | :-------------------------------------- | :------------------------ |
| **Standalone** | Can be used alone | `#python`, `from:user` |
| **Conjunction-required** | Must be used with a standalone operator | `has:media`, `is:retweet` |
Learn query syntax in detail
See all available operators
***
## Fields and expansions
By default, the response includes only `id`, `text`, and `edit_history_tweet_ids`. Use parameters to request additional data.
### Example request
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/search/recent?\
query=python&\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id,attachments.media_keys&\
user.fields=username,verified&\
media.fields=url,type" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search recent Posts
for page in client.posts.search_recent(
query="python",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id", "attachments.media_keys"],
user_fields=["username", "verified"],
media_fields=["url", "type"],
max_results=100
):
for post in page.data:
print(f"{post.text} - Likes: {post.public_metrics.like_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search recent Posts
const paginator = client.posts.searchRecent("python", {
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id", "attachments.media_keys"],
userFields: ["username", "verified"],
mediaFields: ["url", "type"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text} - Likes: ${post.public_metrics?.like_count}`);
});
}
```
### Available expansions
| Expansion | Returns |
| :--------------------------- | :------------------------- |
| `author_id` | Author's user object |
| `attachments.media_keys` | Attached media objects |
| `attachments.poll_ids` | Attached poll objects |
| `referenced_tweets.id` | Quoted or replied-to Posts |
| `geo.place_id` | Place objects |
| `entities.mentions.username` | Mentioned user objects |
Learn more about customizing responses
***
## Pagination
Search endpoints return results in pages. Use the `next_token` from the response to fetch additional pages.
### How it works
1. Make your initial request with `max_results`
2. Check the `meta` object for `next_token`
3. Include `next_token` in subsequent requests
4. Repeat until no `next_token` is returned
### Example
```bash cURL theme={null}
# First request
curl "https://api.x.com/2/tweets/search/recent?query=python&max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
# Subsequent request with pagination token
curl "https://api.x.com/2/tweets/search/recent?query=python&max_results=100&next_token=NEXT_TOKEN" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# The SDK handles pagination automatically
all_posts = []
for page in client.posts.search_recent(query="python", max_results=100):
if page.data:
all_posts.extend(page.data)
print(f"Found {len(all_posts)} posts")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
async function getAllResults(query) {
const allPosts = [];
// The SDK handles pagination automatically
const paginator = client.posts.searchRecent(query, { maxResults: 100 });
for await (const page of paginator) {
if (page.data) {
allPosts.push(...page.data);
}
}
return allPosts;
}
// Usage
const posts = await getAllResults("python");
console.log(`Found ${posts.length} posts`);
```
Learn more about pagination
***
## Post edits
Posts can be edited up to 5 times within 30 minutes. The search endpoints always return the most recent version.
### Considerations
* `edit_history_tweet_ids` contains all Post IDs (oldest first)
* Posts fetched after the 30-minute window represent the final version
* For near-real-time use cases, recently-published Posts may still be edited
Learn more about Post edits
***
## Best practices
Use multiple operators to narrow results and reduce noise.
Start broad, then refine based on results.
Implement proper pagination for large result sets.
Store results locally to avoid repeated requests.
***
## Next steps
Master query syntax
All available operators
Handle large result sets
Full endpoint documentation
# Pagination
Source: https://docs.x.com/enterprise-api/posts/search/integrate/paginate
Search queries typically match on more Posts than can be returned in a single API response. Reference for the Enterprise X API tier covering integrate.
### Recent search pagination
#### Introduction
Search queries typically match on more Posts than can be returned in a single API response. When that happens, the data is returned in a series of 'pages'. Pagination refers to methods for requesting all of the pages in order to retrieve the entire data set.
Here are fundamental recent search pagination details:
* The recent search endpoints will respond to a query with at least one page, and provide a next\_token in its JSON response if additional pages are available. To receive matching Posts, this process can be repeated until no token is included in the response.
* The next\_token does not expire. Multiple requests using the same next\_token value will receive the same results, regardless of when the request is made.
* Posts are delivered in reverse-chronological order, in the UTC timezone. This is true within individual pages, as well as across multiple pages:
* The first Post in the first response will be the most recent one matching your query.
* The last Post in the last response will be the oldest one matching your query.
* The max\_results request parameter enables you to configure the number of Posts returned per response. This defaults to 10 Posts and has a maximum of 100.
* Every pagination implementation will involve parsing next\_tokens from the response payload, and including them in the 'next page' search request. See below for more details on how to construct these 'next page' requests.
The recent search endpoint was designed to support two fundamental use patterns:
* **Get historical** - Requesting matching Posts from a time period of interest. These are typically one-time requests in support of historical research. Search requests can be based on start\_time and end\_time request parameters. recent search endpoint respond with Posts delivered in reverse-chronological order, starting with the most recent matching Post.
* **Polling** - Requesting matching Posts that have been posted since the last Post received. These use cases often have a near-real-time focus and are characterized by frequent requests, "listening" for new Posts of interest. The recent search endpoint provide the since\_id request parameter in support of the 'polling' pattern. To help with navigating by Post IDs, the until\_id request parameter is also available.
Next, we'll discuss the historical mode. This is the default mode of the recent search endpoint and illustrates the fundamentals of pagination. Then we'll discuss examples of polling use cases. When polling triggers pagination, there is an additional step to manage search requests.
#### Retrieving historical data
This section outlines how you can retrieve Posts from a period of interest (currently limited to the last seven days) using the start\_time and end\_time request parameters. Historical requests are typically one-time requests in support of research and analysis.
Making requests for a period of data is the default mode of the recent search endpoint. If a search request does not specify a start\_time, end\_time, or since\_id request parameter, the end\_time will default to "now" (actually 30 seconds before the time of query) and the start\_time will default to seven days ago.
The endpoint will respond with the first 'page' of Posts in reverse-chronological order, starting with the most recent Post. The response JSON payload will also include a next\_token if there are additional pages of data. To collect the entire set of matching Posts, regardless of the number of pages, requests are made until no next\_token is provided.
For example, here is an initial request for Posts with the keyword snow from the last week:
[https://api.x.com/2/tweets/search/recent?query=snow](https://api.x.com/2/tweets/search/recent?query=snow)
The response includes the most recent 10 Posts, along with these "meta" attributes in the JSON response:
```
"meta": {
"newest_id": "1204860593741553664",
"oldest_id": "1204860580630278147",
"next_token": "b26v89c19zqg8o3fobd8v73egzbdt3qao235oql",
"result_count": 10
}
```
To retrieve the next 10 Posts, this next\_token is added to the original request. The request would be:
[https://api.x.com/2/tweets/search/recent?query=snow\&next\_token=b26v89c19zqg8o3fobd8v73egzbdt3qao235oql](https://api.x.com/2/tweets/search/recent?query=snow\&next_token=b26v89c19zqg8o3fobd8v73egzbdt3qao235oql)
The process of looking for a next\_token and including it in a subsequent request can be repeated until all (or some number of) Posts are collected, or until a specified number of requests have been made. If data fidelity (collecting all matches of your query) is key to your use case, a simple "repeat until request.next\_token is null" design will suffice.
#### Polling and listening use cases
This section outlines how you can retrieve recent Posts by polling the recent search endpoint with the since\_id request parameter.
With polling use cases, "any new Posts of interest?" queries are made on an on-going, frequent basis. Unlike historical use cases, that base requests on time, polling use cases typically base requests on Post IDs.
Central to the polling use pattern is that every new Post has a [unique ID](/resources/fundamentals/x-ids) that is 'emitted' from the X platform generally in ascending order. If one Post has an ID smaller than another, it means it was posted earlier.
The recent search endpoint support navigating the Post archive by Post ID. Responses from the endpoint include oldest\_id and newest\_id Post IDs. In the polling mode, requests are made with the since\_id set to the largest/newest ID received so far.
For example, say a query for new Posts about snow is made every five minutes, and the last Post we received had a Post ID of 10000. When it is time to poll, the request looks like:
[https://api.x.com/2/tweets/search/recent?query=snow\&since\_id=10000](https://api.x.com/2/tweets/search/recent?query=snow\&since_id=10000)
Next, let's say seven Posts were posted since our last request. Since all of these fit on a single data 'page', there is no next\_token. The response provides the Post ID of the most recent (newest) Post:
```
"meta": {
"newest_id": "12000",
"oldest_id": "10005",
"result_count": 7
}
```
To make the next polling query, this newest\_id value is used to set the next since\_id parameter:
`https://api.x.com/2/tweets/search/recent?query=snow&since_id=12000`
When there is more data available, and next tokens are provided, only th newest\_id value from the first page of results is needed. Each page of data will include newest\_id and oldest\_id values, but the value provided in the first page is the only one needed for the next, regularly scheduled, polling request. So, If you are implementing a polling design, or searching for Posts by ID range, pagination logic is slightly more complicated.
Now say that there are now 18 more matching Posts. The endpoint would respond with this initial response with a full data page and a next\_token for requesting the next page of data from this five minute period. It would also include the newest Post ID need for the next polling interval in five minutes.
```
"meta": {
"newest_id": "13800",
"oldest_id": "12500",
"next_token": "fnsih9chihsnkjbvkjbsc",
"result_count": 10
}
```
To collect all the matching data for this five minute period, pass the next\_token in your next request, along with the same since\_id value as the previous request.
[https://api.x.com/2/tweets/search/recent?query=snow\&since\\\_id=12000\&next\\\_token=fnsih9chihsnkjbvkjbsc](https://api.x.com/2/tweets/search/recent?query=snow\&since\\_id=12000\&next\\_token=fnsih9chihsnkjbvkjbsc)
```
"meta": {
"newest_id": "12300",
"oldest_id": "12010",
"result_count": 8
}
```
This second response provides the remaining eight Posts, and no next\_token. Note that we do not update our newest\_id value (12300), and instead base our next since\_id request on the first response's newest\_id value:
[https://api.x.com/2/tweets/search/recent?query=snow\&since\_id=13800](https://api.x.com/2/tweets/search/recent?query=snow\&since_id=13800)
# Search Posts
Source: https://docs.x.com/enterprise-api/posts/search/introduction
The Search Posts endpoints let you find Posts matching specific criteria using powerful query. Reference for the Enterprise X API tier covering search.
The Search Posts endpoints let you find Posts matching specific criteria using powerful query operators. Search for keywords, hashtags, mentions, URLs, and more.
## Overview
X offers two search endpoints with different time ranges and access requirements:
Search Posts from the **last 7 days**. Available to all developers.
Search the **complete archive** back to 2006. Available to pay-per-use and Enterprise customers.
***
## Use cases
* **Brand monitoring** — Track mentions of your brand or products
* **Trend analysis** — Analyze conversations around topics or events
* **Research** — Gather data for academic or market research
* **Real-time listening** — Build applications that react to new Posts
***
## Endpoints
| Method | Endpoint | Description | Access |
| :----- | :------------------------------------------------------------ | :---------------------------- | :---------------------- |
| GET | [`/2/tweets/search/recent`](/x-api/posts/search-recent-posts) | Search Posts from last 7 days | All developers |
| GET | [`/2/tweets/search/all`](/x-api/posts/search-all-posts) | Search complete Post archive | Pay-per-use, Enterprise |
***
## Query operators
Build queries using operators that match on Post attributes:
```
(AI OR "artificial intelligence") lang:en -is:retweet has:links
```
| Operator | Example | Description |
| :------- | :------------------- | :------------------------------ |
| Keyword | `python` | Match Posts containing the word |
| Phrase | `"machine learning"` | Match exact phrase |
| Hashtag | `#AI` | Match Posts with hashtag |
| Mention | `@XDevelopers` | Match Posts mentioning user |
| Operator | Example | Description |
| :------------- | :--------------- | :------------------------- |
| `from:` | `from:elonmusk` | Posts by a user |
| `to:` | `to:XDevelopers` | Replies to a user |
| `retweets_of:` | `retweets_of:X` | Retweets of a user's Posts |
| Operator | Example | Description |
| :------------- | :--------------- | :---------------------- |
| `has:images` | `cat has:images` | Posts with images |
| `has:videos` | `has:videos` | Posts with videos |
| `has:links` | `has:links` | Posts with links |
| `has:mentions` | `has:mentions` | Posts with mentions |
| `url:` | `url:github.com` | Posts with specific URL |
| Operator | Example | Description |
| :------------ | :------------ | :---------------------- |
| `lang:` | `lang:en` | Posts in a language |
| `-is:retweet` | `-is:retweet` | Exclude retweets |
| `-is:reply` | `-is:reply` | Exclude replies |
| `is:verified` | `is:verified` | Posts by verified users |
See all available operators and their access requirements
***
## Recent Search
Search Posts from the **last 7 days**. Available to all developers.
### Features
* Up to 100 Posts per request
* Pagination for large result sets
* All core query operators
* 512-character query length (4,096 for Enterprise)
Make your first recent search request
Full endpoint documentation
***
## Full-Archive Search
Search the **complete Post archive** dating back to March 2006.
Full-archive search is available to pay-per-use and Enterprise customers.
### Features
* Up to 500 Posts per request
* Access to complete Post history
* All query operators available
* 1,024-character query length (4,096 for Enterprise)
Make your first full-archive search request
Full endpoint documentation
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Learn query syntax and operators
Navigate through large result sets
Key concepts and best practices
Working code examples
# v1 to v2 (Enterprise)
Source: https://docs.x.com/enterprise-api/posts/search/migrate/enterprise-to-twitter-api-v2
Compare pagination, timezone handling, Post edit history, and metadata between the Enterprise Search Posts API and X API v2 to plan your migration.
### Enterprise compared to X API v2
**Similarities**
* Pagination
* Timezone
* Support for Post edit history and metadata.
**Differences**
* Endpoint URLs
* App and Project requirement
* Available time periods
* Response data format
* HTTP methods
* Request time formats
* Request parameters
* Filtering operators
#### Similarities
**Pagination**
While v2 has additional pagination features (new pagination parameters that allow you to navigate using Post IDs with `since_id` and `until_id`), both enterprise and v2 allow you to paginate using time (`fromDate` and `toDate` with enterprise, and `start_time` and `end_time` for v2).
**Timezone**
As noted in the pagination section, you can navigate different pages of data using time for both enterprise and v2. In both cases, you will be using UTC as the timezone when using these parameters.
**Support for Post edit history and metadata**
Both versions provide metadata that describes any edit history. Check out the [search API References](/x-api/posts/recent-search) and the[Post edits fundamentals page](/x-api/fundamentals/edit-posts) for more details.
#### Differences
**Endpoint URLs**
* Enterprise endpoints:
* 30 day - `http://gnip-api.x.com/search/30day/accounts/:account_name/:label.json`
* Full-archive - `http://gnip-api.x.com/search/fullarchive/accounts/:account_name/:label.json`
* X API v2 endpoints
* Recent (7 day) - `https://api.x.com/2/tweets/search/recent`
* Full-archive - `https://api.x.com/2/tweets/search/all`
**App and Project requirement**
The X API v2 endpoints require that you use credentials from a Project when authenticating your requests. All X API v1.1 endpoints can use credentials from Apps or Apps associated with an App.
**Available time periods**
Both
# Overview
Source: https://docs.x.com/enterprise-api/posts/search/migrate/overview
The v2 Search Tweets endpoint will eventually replace the standard v1.1 search/posts endpoint and. Reference for the Enterprise X API tier covering migrate.
## Comparing X API's Search Posts endpoints
The v2 Search Tweets endpoint will eventually replace the [standard v1.1 search/posts](/x-api/posts/search/introduction) endpoint and [enterprise Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api). If you have code, apps, or tools that use an older version of a X search endpoint and are considering migrating to the newer X API v2 endpoints, then this guide is for you.
## Recent search comparison
The following table compares the various types of recent search endpoints:
| **Description** | **Standard v1.1** | **X API v2** |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/search/tweets.json | /2/tweets/search/recent |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context OAuth 2.0 App-Only | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE
OAuth 2.0 App-Only |
| Timestamp format | YYYYMMDD | YYYY-MM-DDTHH:mm:ssZ [ISO 8601 / RFC 3339](https://tools.ietf.org/html/rfc3339#section-5.6) |
| Returns Posts that are no older than | 7 days | 7 days |
| HTTP methods supported | GET | GET |
| Default request rate limits | 180 requests per 15 min with OAuth 1.0a User Context
450 requests per 15 min with OAuth 2.0 App-Only | **Self-serve:**
60 requests per 15 min with OAuth 2.0 App-Only
60 requests per 15 min with OAuth 1.0a User Context
60 requests per 15 min with OAuth 2.0 Authorization Code with PKCE |
| Offers fully unwound URLs | | ✔ |
| Maximum Posts per response (default) | 100 (15) | 100 (10) |
| Post JSON format | Standard v1.1 format | [X API v2 format](/x-api/fundamentals/data-dictionary) (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
| Supports selecting which [fields](/x-api/fundamentals/fields) return in the payload | | ✔ |
| Supports requesting and receiving [annotations](/x-api/fundamentals/post-annotations) | | ✔ |
| Supports requesting specific [metrics](/x-api/fundamentals/metrics) within Post object | | ✔ |
| Supports the [conversation\_id](/x-api/fundamentals/conversation-id) operator and field | | ✔ |
| Provides Post edit history | ✔ | ✔ |
| JSON key name for Post data array | statuses | data |
| JSON key name for pagination | search\_metadata.next\_results | meta.next\_token |
| Supports navigating archive by time range | ✔ | ✔ |
| Time resolution of time-based requests | day | second |
| Timezone | UTC | UTC |
| Request parameters for navigating by time | until | start\_time end\_time |
| Request parameters for navigating by Post ID | since\_id max\_id | since\_id until\_id |
| Request parameter for pagination | Provides URL-encoded query | next\_token |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) | | ✔ |
### Full-archive search comparison
The following table compares the various types of full-archive search endpoints:
| **Description** | **Enterprise** | **X API v2** |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |
| Host domain | [https://gnip-api.x.com](https://gnip-api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /search/fullarchive/accounts/:account\_name/:label | /2/tweets/search/all |
| [Authentication](/resources/fundamentals/authentication) | Basic auth | OAuth 2.0 App-Only |
| Timestamp format | YYYYMMDDHHMM | YYYY-MM-DDTHH:mm:ssZ [ISO 8601 / RFC 3339](https://tools.ietf.org/html/rfc3339#section-5.6) |
| Returns Posts that are no older than | The full archive since March 2006 | The full archive since March 2006 |
| HTTP methods supported | GET POST | GET |
| Default request rate limits | The per minute rate limit will vary by partner as specified in your contract.
20 requests per sec with Basic auth | 300 requests per 15 min with OAuth 2.0 App-Only
1 requests per 1 sec with OAuth 2.0 App-Only |
| Offers fully unwound URLs | ✔ | ✔ |
| Posts per response | Maximum: 500 Default: 100 | Maximum: 500 Default: 10 |
| Post JSON format | [Native Enriched or Activity Streams](/x-api/enterprise-gnip-2.0/fundamentals/data-dictionary) format | [X API v2](/x-api/fundamentals/data-dictionary) format (determined by fields and expansions request parameters) |
| Supports selecting which [fields](/x-api/fundamentals/fields) return in the payload | | ✔ |
| Supports requesting and receiving [annotations](/x-api/fundamentals/post-annotations) | | ✔ |
| Supports requesting specific [metrics](/x-api/fundamentals/metrics) within Post object | | ✔ |
| Supports the [conversation\_id](/x-api/fundamentals/conversation-id) operator and field | | ✔ |
| Provides Post edit history | ✔ | ✔ |
| JSON key name for Post data array | results | data |
| JSON key name for pagination | **next** | meta.next\_token |
| Time resolution of time-based requests | second | second |
| Timezone | UTC | UTC |
| Supports navigating archive by Post ID | | ✔ |
| Request parameters for navigation by time | fromDate toDate | start\_time end\_time |
| Request parameters for navigating by Post ID | | since\_id until\_id |
| Request parameter for pagination | next\_token | next\_token |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) that has Academic Research access | | ✔ |
**Filtering operator comparison**
The four different versions (standard, enterprise, and v2) of search Posts differ in which operators are available, and also have varying levels of operator availability within each version, which are explained below.
Enterprise
* There are no sub-tiers of enterprise operators
X API v2
* **Self-serve:** Available when using any Project
* **Enterprise:** Available when using a Project
You can learn more about each of these sets of operators in their respective guides:
* [Enterprise operators](/x-api/enterprise-gnip-2.0/fundamentals/search-api#available-operators)
* [X API v2 operators](/x-api/posts/search/integrate/build-a-query#operators)
Now that we understand the different operator levels within X API v2, here is the table that maps out operator availability for search Posts (note that if the cell is left blank, the operator is not available):
| Search operator | Standard | Enterprise | v2 |
| :---------------------------------- | :----------------------------------------------- | :--------- | :--------------------------------------------- |
| keyword | Available q:keyword | Available | Available |
| emoji | Available q:😄 | Available | Available |
| "exact phrase" | Available | Available | Available |
| # | Available | Available | Available |
| \$ | Available | Available | Available |
| @ | Available | Available | Available |
| from: | Available | Available | Available |
| to: | Available | Available | Available |
| url: | Available | Available | Available |
| retweets\_of: | | Available | Available |
| context: | | | Available |
| entity: | | | Self-serve - Only available with recent search |
| conversation\_id: | | | Available |
| place: | | Available | Available |
| place\_country: | | Available | Available |
| point\_radius: | geocode parameter | Available | Available |
| bounding\_box: | | Available | Available |
| is:retweet | filter:retweets | Available | Available |
| is:reply | | Available | Available |
| is:quote | | Available | Available |
| is:verified | | Available | Available |
| -is:nullcast | | Available | Available |
| has:hashtags | | Available | Available |
| has:cashtags | | Available | Available |
| has:links | filter:links | Available | Available |
| has:mentions | | Available | Available |
| has:media | filter:media | Available | Available |
| has:images | filter:images, filter:twimg | Available | Available |
| has:videos | filter:videos filter:native\_video | Available | Available |
| has:geo | | Available | Available |
| lang: | lang - can be used as an operator or a parameter | Available | Available |
| has:profile\_geo | | Available | |
| profile\_country | | Available | |
| profile\_locality | | Available | |
| profile\_region | | Available | |
| proximity | | Available | |
| :( | Available | | |
| :) | Available | | |
| ? | Available | | |
| filter:periscope | Available | | |
| list: | Available | | Available |
| filter:replies | Available | | |
| filter:pro\_video | Available | | |
| filter:social | Available | | |
| filter:trusted | Available | | |
| filter:follows | Available | | |
| filter:has\_engagement | Available | | |
| include:antisocial | Available | | |
| include:offensive\_user | Available | | |
| include:antisocial\_offensive\_user | Available | | |
| include:sensitive\_content | Available | | |
| source: | Available | | |
| min\_replies: | Available | | |
| min\_retweets: | Available | | |
| min\_faves: | Available | | |
| card\_name: | Available | | |
| card\_domain: | Available | | |
**Other migration resources**
[X API migration hub](/x-api/migrate/overview)
[Check out some sample code for these endpoints](https://github.com/xdevplatform/Twitter-API-v2-sample-code "Check out some sample code for these endpoints")
[Search Posts: Standard v1.1 to X API v2](/x-api/posts/search/migrate/standard-to-twitter-api-v2)
[Search Posts: Enterprise to X API v2](/x-api/posts/search/migrate/enterprise-to-twitter-api-v2)
# v1 to v2
Source: https://docs.x.com/enterprise-api/posts/search/migrate/standard-to-twitter-api-v2
If you have been working with the v1.1 search/posts, the goal of this guide is to help you. Reference for the Enterprise X API tier covering migrate.
### Standard v1.1 compared to X API v2
If you have been working with the v1.1 [search/posts](/x-api/posts/search/introduction), the goal of this guide is to help you understand the similarities and differences between the standard and X API v2 search Posts endpoint.
* **Similarities**
* OAuth 1.0a User Context and OAuth 2.0 App-Only
* Support for Post edit history and metadata.
* **Differences**
* Endpoint URLs
* App and Project requirements
* Response data format
* Request parameters
* New query operators
* AND / OR operator precedence
#### Similarities
**OAuth 1.0a User Context and OAuth 2.0 App-Only authentication**
The v1.1 search/posts and the X API v2 recent search endpoint support both [OAuth 1.0a User Context](/resources/fundamentals/authentication) and [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0).
Therefore, if you were previously using the standard v1.1 search endpoint you can continue using the same authentication method if you migrate to the X API v2 version.
Depending on your authentication library/package of choice, App-Only authentication is probably the easiest way to get started and can be set with a simple request header. To learn how to generate an App Access Token see this [OAuth 2.0 App-Only guide](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only).
If you would like to take advantage of the ability to pull private or advertising metrics with the X API v2 endpoint, you will need to use OAuth 1.0a User Context, and pass the user access tokens related to the user who posted the Post for which you would like to pull metrics.
**Support for Post edit history and metadata**
Both versions provide metadata that describes any edit history. Check out the [search API References](/x-api/posts/recent-search) and the [Post edits fundamentals page](/x-api/fundamentals/edit-posts) for more details.
# Full-Archive Search Quickstart
Source: https://docs.x.com/enterprise-api/posts/search/quickstart/full-archive-search
This guide walks you through making your first full-archive search request to find Posts from. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through making your first full-archive search request to find Posts from the complete X archive, dating back to March 2006.
Full-archive search requires [Self-serve](/x-api/getting-started/about-x-api) or [Enterprise](/x-api/getting-started/about-x-api) access. [Upgrade your access](https://developer.x.com/en/portal/products) to use this endpoint.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* Your App's Bearer Token (found in the Developer Console under "Keys and tokens")
***
## Step 1: Build a query
Full-archive search supports all query operators. Build queries the same way as recent search:
```
from:XDevelopers lang:en
```
Full-archive search supports queries up to 1,024 characters (4,096 for Enterprise).
***
## Step 2: Set a time range
By default, results return Posts from the last 30 days. Use `start_time` and `end_time` to search specific periods:
| Parameter | Format | Example |
| :----------- | :------- | :--------------------- |
| `start_time` | ISO 8601 | `2020-01-01T00:00:00Z` |
| `end_time` | ISO 8601 | `2020-12-31T23:59:59Z` |
***
## Step 3: Make a request
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/search/all?\
query=from%3AXDevelopers&\
start_time=2020-01-01T00%3A00%3A00Z&\
end_time=2020-12-31T23%3A59%3A59Z&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Full-archive search with pagination
for page in client.posts.search_all(
query="from:XDevelopers",
start_time="2020-01-01T00:00:00Z",
end_time="2020-12-31T23:59:59Z",
max_results=100
):
for post in page.data:
print(post.text)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Full-archive search with pagination
const paginator = client.posts.searchAll({
query: "from:XDevelopers",
startTime: "2020-01-01T00:00:00Z",
endTime: "2020-12-31T23:59:59Z",
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(post.text);
});
}
```
***
## Step 4: Review the response
```json theme={null}
{
"data": [
{
"id": "1271111223220809728",
"text": "Tune in tonight and watch as @jessicagarson takes us through...",
"edit_history_tweet_ids": ["1271111223220809728"]
},
{
"id": "1270799243071062016",
"text": "As we work towards building the new Twitter API...",
"edit_history_tweet_ids": ["1270799243071062016"]
}
],
"meta": {
"newest_id": "1271111223220809728",
"oldest_id": "1270799243071062016",
"result_count": 2
}
}
```
Posts created before the edit feature was introduced (September 2022) won't include `edit_history_tweet_ids`.
***
## Step 5: Add fields and expansions
Request additional data with query parameters:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/search/all?\
query=from%3AXDevelopers&\
start_time=2020-01-01T00%3A00%3A00Z&\
end_time=2020-12-31T23%3A59%3A59Z&\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id&\
user.fields=username,description&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search with fields and expansions
for page in client.posts.search_all(
query="from:XDevelopers",
start_time="2020-01-01T00:00:00Z",
end_time="2020-12-31T23:59:59Z",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id"],
user_fields=["username", "description"],
max_results=100
):
for post in page.data:
print(f"{post.created_at}: {post.text[:50]}...")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search with fields and expansions
const paginator = client.posts.searchAll({
query: "from:XDevelopers",
startTime: "2020-01-01T00:00:00Z",
endTime: "2020-12-31T23:59:59Z",
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id"],
userFields: ["username", "description"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.created_at}: ${post.text?.slice(0, 50)}...`);
});
}
```
***
## Step 6: Paginate through results
The SDKs handle pagination automatically. For cURL, use the `next_token` from the response:
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?\
query=from%3AXDevelopers&\
max_results=500&\
next_token=b26v89c19zqg8o3fo7gesq314yb9l2l4ptqy" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Learn more about navigating large result sets
***
## Key differences from recent search
| Feature | Recent Search | Full-Archive Search |
| :---------------------- | :--------------------- | :---------------------- |
| Time range | Last 7 days | March 2006 to now |
| Access required | All developers | Pay-per-use, Enterprise |
| Max results per request | 100 | 500 |
| Query length | 512 chars | 1,024 chars |
| Rate limit | 450 / 15 min | 300 / 15 min, 1 / sec |
| Authentication | App-Only, User Context | App-Only |
***
## Common parameters
| Parameter | Description | Default |
| :------------- | :------------------------- | :----------- |
| `query` | Search query (required) | — |
| `max_results` | Posts per page (10-500) | 10 |
| `start_time` | Oldest Post timestamp | 30 days ago |
| `end_time` | Newest Post timestamp | Now |
| `next_token` | Pagination token | — |
| `tweet.fields` | Additional Post fields | `id`, `text` |
| `expansions` | Related objects to include | — |
***
## Next steps
Master query syntax and operators
See all available operators
Handle large result sets
Full endpoint documentation
# Recent Search Quickstart
Source: https://docs.x.com/enterprise-api/posts/search/quickstart/recent-search
This guide walks you through making your first recent search request to find Posts from the. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through making your first recent search request to find Posts from the last 7 days.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token (found in the Developer Console under "Keys and tokens")
***
Search queries use operators to match Posts. Start with a simple keyword:
```
python
```
Or combine multiple operators:
```
python lang:en -is:retweet
```
This matches Posts containing "python" in English, excluding retweets.
See the [full operator reference](/x-api/posts/search/integrate/operators) for all available options.
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=python%20lang%3Aen%20-is%3Aretweet" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search recent Posts
for page in client.posts.search_recent(
query="python lang:en -is:retweet"
):
for post in page.data:
print(post.text)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search recent Posts
const paginator = client.posts.searchRecent({
query: "python lang:en -is:retweet",
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(post.text);
});
}
```
The default response includes `id`, `text`, and `edit_history_tweet_ids`:
```json theme={null}
{
"data": [
{
"id": "1234567890123456789",
"text": "Just started learning Python and loving it!",
"edit_history_tweet_ids": ["1234567890123456789"]
},
{
"id": "1234567890123456788",
"text": "Python tip: use list comprehensions for cleaner code",
"edit_history_tweet_ids": ["1234567890123456788"]
}
],
"meta": {
"newest_id": "1234567890123456789",
"oldest_id": "1234567890123456788",
"result_count": 2
}
}
```
Request additional data with query parameters:
```bash cURL theme={null}
curl "https://api.x.com/2/tweets/search/recent?\
query=python%20lang%3Aen%20-is%3Aretweet&\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id&\
user.fields=username,verified&\
max_results=10" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search with fields and expansions
for page in client.posts.search_recent(
query="python lang:en -is:retweet",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id"],
user_fields=["username", "verified"],
max_results=10
):
for post in page.data:
print(f"{post.text[:50]}... - Likes: {post.public_metrics.like_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search with fields and expansions
const paginator = client.posts.searchRecent({
query: "python lang:en -is:retweet",
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id"],
userFields: ["username", "verified"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}... - Likes: ${post.public_metrics?.like_count}`);
});
}
```
**Response:**
```json theme={null}
{
"data": [
{
"id": "1234567890123456789",
"text": "Just started learning Python and loving it!",
"created_at": "2024-01-15T10:30:00.000Z",
"author_id": "9876543210",
"public_metrics": {
"retweet_count": 5,
"reply_count": 2,
"like_count": 42,
"quote_count": 1
},
"edit_history_tweet_ids": ["1234567890123456789"]
}
],
"includes": {
"users": [
{
"id": "9876543210",
"username": "pythondev",
"verified": false
}
]
},
"meta": {
"newest_id": "1234567890123456789",
"oldest_id": "1234567890123456789",
"result_count": 1
}
}
```
The SDKs handle pagination automatically. For cURL, use the `next_token` from the response:
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?\
query=python&\
max_results=100&\
next_token=b26v89c19zqg8o3fo7gesq314yb9l2l4ptqy" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Learn more about navigating large result sets
***
## Example queries
```
from:XDevelopers
```
```
#Python -is:retweet
```
```
"machine learning" has:images lang:en
```
```
@elonmusk -is:retweet -is:reply
```
```
url:github.com lang:en
```
***
## Next steps
Master query syntax and operators
See all available operators
Search the complete Post archive
Full endpoint documentation
# Integration Guide
Source: https://docs.x.com/enterprise-api/posts/timelines/integrate
This guide covers the key concepts you need to integrate the Timelines endpoints into your. Reference for the Enterprise X API tier covering timelines.
This guide covers the key concepts you need to integrate the Timelines endpoints into your application.
***
## Authentication
### Endpoint requirements
| Endpoint | App-Only | User Context |
| :--------------------- | :------- | :----------- |
| User Posts timeline | ✓ | ✓ |
| User mentions timeline | ✓ | ✓ |
| Home timeline | — | ✓ (required) |
### Private metrics
To access private metrics, you must authenticate on behalf of the Post author:
These fields require User Context authentication:
* `tweet.fields.non_public_metrics`
* `tweet.fields.promoted_metrics`
* `tweet.fields.organic_metrics`
* `media.fields.non_public_metrics`
* `media.fields.promoted_metrics`
* `media.fields.organic_metrics`
***
## Fields and expansions
By default, responses include only `id`, `text`, and `edit_history_tweet_ids`. Request additional data:
### Example request
```bash cURL theme={null}
curl "https://api.x.com/2/users/123/tweets?\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id,attachments.media_keys&\
user.fields=username,verified&\
media.fields=url,type" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get user's Posts timeline
for page in client.posts.get_user_posts(
user_id="123",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id", "attachments.media_keys"],
user_fields=["username", "verified"],
media_fields=["url", "type"],
max_results=100
):
for post in page.data:
print(f"{post.text} - {post.public_metrics}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get user's Posts timeline with pagination
const paginator = client.posts.getUserPosts("123", {
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id", "attachments.media_keys"],
userFields: ["username", "verified"],
mediaFields: ["url", "type"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text} - ${JSON.stringify(post.public_metrics)}`);
});
}
```
### Key fields
| Field | Description |
| :-------------------- | :----------------------- |
| `created_at` | Post creation timestamp |
| `public_metrics` | Engagement counts |
| `conversation_id` | Thread identifier |
| `context_annotations` | Topic classifications |
| `entities` | Hashtags, mentions, URLs |
Learn more about customizing responses
***
## Pagination
Timelines return up to 100 Posts per request. Use pagination for larger result sets.
### How it works
1. Make initial request with `max_results`
2. Get `next_token` from the `meta` object
3. Include `pagination_token` in next request
4. Repeat until no `next_token` is returned
### Example
```bash cURL theme={null}
# First request
curl "https://api.x.com/2/users/123/tweets?max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
# Subsequent request with pagination token
curl "https://api.x.com/2/users/123/tweets?max_results=100&pagination_token=NEXT_TOKEN" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# The SDK handles pagination automatically
all_posts = []
for page in client.posts.get_user_posts(user_id="123", max_results=100):
if page.data:
all_posts.extend(page.data)
print(f"Found {len(all_posts)} posts")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
async function getAllTimelinePosts(userId) {
const allPosts = [];
// The SDK handles pagination automatically with async iteration
const paginator = client.posts.getUserPosts(userId, { maxResults: 100 });
for await (const page of paginator) {
if (page.data) {
allPosts.push(...page.data);
}
}
return allPosts;
}
// Usage
const posts = await getAllTimelinePosts("123");
console.log(`Found ${posts.length} posts`);
```
Learn more about pagination
***
## Filtering results
### Time-based filtering
| Parameter | Description |
| :----------- | :------------------------------- |
| `start_time` | Oldest Post timestamp (ISO 8601) |
| `end_time` | Newest Post timestamp (ISO 8601) |
| `since_id` | Return Posts after this ID |
| `until_id` | Return Posts before this ID |
### Exclude parameter
Remove specific Post types from results:
```bash cURL theme={null}
curl "https://api.x.com/2/users/123/tweets?exclude=retweets,replies" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Exclude retweets and replies
for page in client.posts.get_user_posts(
user_id="123",
exclude=["retweets", "replies"]
):
for post in page.data:
print(post.text)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Exclude retweets and replies
const paginator = client.posts.getUserPosts("123", {
exclude: ["retweets", "replies"],
});
for await (const page of paginator) {
page.data?.forEach((post) => console.log(post.text));
}
```
| Value | Effect |
| :--------- | :--------------- |
| `retweets` | Exclude retweets |
| `replies` | Exclude replies |
***
## Volume limits
Each timeline has maximum retrieval limits:
| Endpoint | Maximum Posts |
| :--------------------------- | :---------------- |
| User Posts timeline | 3,200 most recent |
| User Posts (exclude=replies) | 800 most recent |
| User mentions timeline | 800 most recent |
| Home timeline | 3,200 or 7 days |
Requesting Posts beyond these limits returns a successful response with no data.
***
## Post edits
Posts can be edited up to 5 times within 30 minutes. Timeline endpoints always return the most recent version.
### Considerations
* Posts older than 30 minutes represent their final version
* Near-real-time use cases should account for potential edits
* Use Post lookup to verify final state if needed
Learn more about Post edits
***
## Post metrics
### Public metrics
Available for all Posts with App-Only or User Context authentication:
```json theme={null}
{
"public_metrics": {
"retweet_count": 156,
"reply_count": 23,
"like_count": 892,
"quote_count": 12,
"bookmark_count": 34,
"impression_count": 15200
}
}
```
### Private metrics
Requires User Context authentication from the Post author:
* Only available for Posts from the last 30 days
* Only returned for Posts authored by the authenticated user
* Returns error for other users' Posts
***
## Edge cases
When requesting non-public metrics for Posts older than 30 days, you may receive a `next_token` with `result_count: 0`. To avoid this:
* Keep requests within the last 30 days
* Use `max_results` of at least 10
Requesting promoted metrics for Posts that weren't promoted returns an empty response. This is a known issue.
For Retweets with text over 140 characters, the text field is truncated. Use the `referenced_tweets.id` expansion to get the full text.
***
## Next steps
Get a user's home feed
Get mentions for a user
Full endpoint documentation
Handle large result sets
# Timelines
Source: https://docs.x.com/enterprise-api/posts/timelines/introduction
The Timelines endpoints let you retrieve Posts from user timelines, mention feeds, and home. Reference for the Enterprise X API tier covering timelines.
The Timelines endpoints let you retrieve Posts from user timelines, mention feeds, and home feeds. Get a user's posted content, see what Posts mention them, or view their personalized home timeline.
## Overview
Get Posts authored by a user
Get Posts mentioning a user
Get personalized home feed
Posts in time order
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------------------------------- | :-------------------------- |
| GET | [`/2/users/:id/tweets`](/x-api/users/get-posts) | Get Posts by a user |
| GET | [`/2/users/:id/mentions`](/x-api/users/get-mentions) | Get Posts mentioning a user |
| GET | [`/2/users/:id/timelines/reverse_chronological`](/x-api/users/get-timeline) | Get home timeline |
***
## User Posts timeline
Get the most recent Posts authored by a specific user.
### Features
* Up to 3,200 most recent Posts
* Filter out replies and retweets
* Pagination support
* Historical access with time-based filtering
Full endpoint documentation
***
## User mentions timeline
Get Posts that mention a specific user.
### Features
* Up to 800 most recent mentions
* Includes replies and quote Posts
* Pagination support
Get mentions for a user
Full endpoint documentation
***
## Reverse chronological home timeline
Get the authenticated user's home timeline in reverse chronological order.
### Features
* Posts from followed accounts
* Most recent 3,200 Posts (or 7 days)
* Excludes algorithmic ranking
* Requires user authentication
This endpoint requires [OAuth 1.0a User Context](/resources/fundamentals/authentication) or [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2).
Get a user's home timeline
Full endpoint documentation
***
## Filtering options
### Exclude parameter
Filter out specific Post types:
| Value | Effect |
| :--------- | :--------------- |
| `retweets` | Exclude retweets |
| `replies` | Exclude replies |
```bash theme={null}
curl "https://api.x.com/2/users/123/tweets?exclude=retweets,replies" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
### Time-based filtering
| Parameter | Description |
| :----------- | :------------------------------- |
| `start_time` | Oldest Post timestamp (ISO 8601) |
| `end_time` | Newest Post timestamp (ISO 8601) |
| `since_id` | Return Posts after this ID |
| `until_id` | Return Posts before this ID |
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Get a user's home feed
Get mentions for a user
Key concepts and best practices
Working code examples
# Enterprise timelines endpoints v2 migration
Source: https://docs.x.com/enterprise-api/posts/timelines/migrate/overview
Compare Standard v1.1 user_timeline and mentions_timeline endpoints with the X API v2 reverse chronological and user mention timelines for migration.
## Comparing X API's timelines endpoints
The v2 reverse chronological timeline, user Posts timeline, and user mention timeline endpoints replace the [v1.1 statuses/home\_timeline,](https://developer.x.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-home_timeline) [v1.1 statuses/user\_timeline](https://developer.x.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-user_timeline.html), and [v1.1 statuses/mentions\_timeline](https://developer.x.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-mentions_timeline.html) endpoints respectively. If you have code, apps, or tools that use an older version of this endpoint and are considering migrating to the newer X API v2 endpoint, then this guide is for you. For a more in-depth migration guide see [Standard v1.1 migration to X API v2](/x-api/posts/timelines/migrate/standard-to-twitter-api-v2).
This page contains three comparison tables:
* Reverse chronological home timeline
* User Post timeline
* User mention timeline
### Reverse chronological home timeline
The following tables compare the standard v1.1 and X API v2 home timeline endpoints:
| | | |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Documentation | [API Reference](https://developer.x.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-home_timeline) | [API Reference](https://developer.x.com/x-api/posts/timelines#user-mention-timeline-3) |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint paths | `/1.1/statuses/home_timeline.json` | `/2/users/:id/timelines/reverse_chronological` |
| Required parameters | `user_id` or `screen_name` | User ID set as path parameter :id |
| Authentication | OAuth 1.0a User Context | OAuth 1.0a User Context
[OAuth 2.0 Authorization Code Flow with PKCE](/fundamentals/authentication/oauth-2-0/authorization-code) |
| Request rate limits | 15 requests per 15-minute with OAuth 1.0a User Context
Request cap: 100,000 within a 24 hour period. | 180 requests per 15-minute window |
| Default Posts per response | 15 | 100 |
| Maximum Posts per response | 800 | This endpoint returns every Post created on a timeline over the last 7 days as well as the most recent 800 regardless of creation date. |
| Provides Post edit history | ✔ | ✔ |
| Historical Posts available | The most recent 800 Posts, including Retweets | The most recent 3,200 Posts, including Retweets |
| Timeline navigation options | since\_id (exclusive) used for update polling
`until_id` |
| Supports requesting and receiving [annotations](/x-api/fundamentals/post-annotations) | N/A | If annotations are included in tweet.fields, results will be annotated with inferred annotation data based on the Post text, such as 'Music Genre' and 'Folk Music' or 'Musician' and 'Dolly Parton' |
| Supports requesting and receiving specific Post [metrics](/x-api/fundamentals/metrics) | N/A | If annotations are included in `tweet.fields`, results will be annotated with public\_metrics per Post including `retweet_count`, `reply_count`, `quote_count`, `like_count`, `impression_count`, and `bookmark_count`, `non_public_metrics` including `impression_count`, `user_profile_clicks`, `url_link_clicks`, and `engagements`.
Additional media metrics such as view\_count and video playback metrics.
Additional organic\_metrics and promoted\_metrics available with User Context for promoted Posts. |
| Supports requesting and receiving [conversation\_id](/x-api/fundamentals/conversation-id) | N/A | Returns a conversation\_id field where the value represents the first published Post in a reply thread to help you track conversations. |
| Post JSON format | [Standard v1.1 data format](https://developer.x.com/en/docs/twitter-api/v1/data-dictionary/overview.html) | [X API v2](/x-api/fundamentals/data-dictionary) format (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
| Results order | Reverse chronological | Reverse chronological |
| Results pagination | N/A must use navigation by Post ID | Results can be reviewed moving forward or backward using a pagination\_token |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) | | ✔ |
### User Post timeline
The following tables compare the standard v1.1 and X API v2 user Post timeline endpoints:
| | | |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Documentation | [API Reference](https://developer.x.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-user_timeline.html) | [API Reference](/x-api/users/get-posts) |
| HTTP methods supported | GET | GET |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint paths | /1.1/statuses/user\_timeline.json | /2/users/:id/tweets |
| Required parameters | user\_id or screen\_name | User ID set as path parameter :id |
| Authentication | OAuth 1.0a User Context
OAuth 2.0 App-Only | OAuth 1.0a User Context
OAuth 2.0 App-Only
OAuth 2.0 Authorization Code with PKCE |
| Request rate limits | 900 requests per 15 min with OAuth 1.0a User Context
1500 requests per 15 min with OAuth 2.0 App-Only
Request cap: 100,000 within a 24 hour period. | 900 requests per 15-minute window with OAuth 1.0a User Context
1500 requests per 15-minute window with OAuth 2.0 App-Only |
| Default Posts per response | 15 | 10 |
| Maximum Posts per response | 200 | 100 |
| Historical Posts available | The most recent 3,200 Posts, including Retweets | The most recent 3,200 Posts, including Retweets |
| Timeline navigation options | since\_id (exclusive) used for update polling
max\_id (inclusive) | start\_time
end\_time
since\_id (exclusive) used for update polling
until\_id (exclusive) |
| Optional parameters for results refinement | count exclude\_replies include\_rts trim\_user tweet\_mode since\_id max\_id | max\_results exclude(retweets,replies) tweet.fields user.fields place.fields media.fields poll.fields expansions start\_time end\_time since\_id until\_id |
| Supports requesting and receiving [annotations](/x-api/fundamentals/post-annotations) | N/A | Returns Post results with inferred annotation data based on the Post text, such as 'Music Genre' and 'Folk Music' or 'Musician' and 'Dolly Parton' |
| Supports requesting and receiving specific Post [metrics](/x-api/fundamentals/metrics) | N/A | Returns Post results with available public\_metrics per Post including retweet\_count, reply\_count, quote\_count and like\_count.
Available with OAuth1.0a User Context: Additional non\_public\_metrics , including impression\_count, user\_profile\_clicks, url\_link\_clicks.
Additional media metrics such as view\_count and video playback metrics.
Additional organic\_metrics and promoted\_metrics available with OAuth 1.0a User Context for promoted Posts. |
| Supports requesting and receiving [conversation\_id](/x-api/fundamentals/conversation-id) | N/A | Returns a conversation\_id field where the value represents the first published Post in a reply thread to help you track conversations. |
| Post JSON format | [Standard v1.1 data format](/x-api/fundamentals/data-dictionary) | [X API v2](/x-api/fundamentals/data-dictionary) format (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
| Results order | Reverse chronological | Reverse chronological |
| Results pagination | N/A must use navigation by Post ID | Results can be reviewed moving forward or backward using a pagination\_token |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [Project](/resources/fundamentals/developer-apps) | | ✔ |
| Provides Post edit history | ✔ | ✔ |
### User mention timeline
The following tables compare the standard v1.1 and X API v2 user mention timeline endpoints
| | | |
| :------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| Documentation | [API Reference](https://developer.x.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-mentions_timeline.html) | [API Reference](/x-api/users/get-mentions) |
| HTTP methods supported | GET | GET |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint paths | /1.1/statuses/mentions\_timeline.json | /2/users/:id/mentions |
| Required parameters | no required parameters | User ID set as path parameter :id |
| Authentication | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 App-Only
OAuth 2.0 Authorization Code with PKCE |
| Default request rate limits | 75 requests per 15 min with OAuth 1.0a User Context
100,000 request cap within a 24 hour period. | 180 requests per 15-minute window with OAuth 1.0a User Context
450 requests per 15-minute window with OAuth 2.0 App-Only |
| Default Posts per response | 15 | 10 |
| Maximum Posts per response | 200 | 100 |
| Historical Posts available | The most recent 800 Posts | The most recent 800 Posts |
| Timeline navigation options | since\_id (exclusive) used for update polling
max\_id (inclusive) | start\_time
end\_time
since\_id (exclusive) used for update polling
until\_id (exclusive) |
| Optional parameters for results refinement | count trim\_user include\_entities tweet\_mode since\_id max\_id | max\_results tweet.fields user.fields place.fields media.fields poll.fields expansions start\_time end\_time since\_id until\_id |
| Supports requesting and receiving [annotations](/x-api/fundamentals/post-annotations) | N/A | Returns Posts results with inferred annotation data based on the Post text, such as 'Music Genre' and 'Folk Music' or 'Musician' and 'Dolly Parton' |
| Supports requesting and receiving specific Post [metrics](/x-api/fundamentals/metrics) | N/A | Returns Post results with available public\_metrics per Post including retweet\_count, reply\_count, quote\_count and like\_count.
Available with OAuth 1.0a User Context: Additional non\_public\_metrics , including impression\_count, user\_profile\_clicks, url\_link\_clicks.
Additional media metrics such as view\_count and video playback metrics.
Additional organic\_metrics and promoted\_metrics available with OAuth 1.0a User Context for promoted Posts |
| | | |
# v1 to v2
Source: https://docs.x.com/enterprise-api/posts/timelines/migrate/standard-to-twitter-api-v2
If you have been working with the v1.1 timelines endpoints (statuses/user\timeline and. Reference for the Enterprise X API tier covering migrate.
## Standard v1.1 timelines to X API v2 timelines
If you have been working with the v1.1 timelines endpoints (statuses/user\_timeline and statuses/mentions\_timeline), the goal of this guide is to help you understand the similarities and differences between the standard and X API v2 timelines endpoints so that you can migrate your current integration to the new version.
* **Similarities:**
* Authentication:
* OAuth 1.0a User Context (reverse chronological home timeline, user Post timeline and user mentions timeline)
* OAuth 2.0 App-Only (user Post timeline)
* Historical Access limit: User timeline (user Post timeline) provides access to most recent 3200 Posts; mentions timeline (user mention timeline) provides access to most recent 800 mentions.
* Support for Post edit history and metadata
* Rate limits (user Post timeline)
* Refresh polling: Ability to retrieve new results since the since\_id
* Traversing timelines by Post IDs
* Results specifications:
* Results order: Results returned in reverse chronological order
* Ability to exclude replies (user Post timeline only)
* Ability to exclude Retweets (user Post timeline only)
* **Differences**
* New Authentication capability:
* OAuth 2.0 App-Only (user mention timeline)
* OAuth 2.0 Authorization Code Flow with PKCE (reverse chronological home timeline, user Post timeline and user mentions timeline)
* Access requirements: X API v2 App and Project requirements
* Rate limits (user mention timeline and reverse chronological home timeline)
* Additional pagination method
* Different max\_results (count) per response
* Response data format
* Request parameters
* Custom
# Home Timeline Quickstart
Source: https://docs.x.com/enterprise-api/posts/timelines/quickstart/reverse-chron-quickstart
This guide walks you through making your first request to the reverse chronological home. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through making your first request to the reverse chronological home timeline endpoint.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Tokens (this endpoint requires user authentication)
***
## Step 1: Get the user ID
You need the user ID for the account whose home timeline you want to retrieve. Find it using the username lookup endpoint:
```bash cURL theme={null}
curl "https://api.x.com/2/users/by/username/XDevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
response = client.users.get_by_username("XDevelopers")
print(f"User ID: {response.data.id}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
const response = await client.users.getByUsername("XDevelopers");
console.log(`User ID: ${response.data?.id}`);
```
The response includes the user ID:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "XDevelopers"
}
}
```
***
## Step 2: Request the home timeline
Make a GET request with the user ID and User Access Token:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/timelines/reverse_chronological" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get home timeline with pagination
for page in client.posts.get_home_timeline("2244994945"):
for post in page.data:
print(post.text)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get home timeline with pagination
const paginator = client.posts.getHomeTimeline("2244994945");
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(post.text);
});
}
```
***
## Step 3: Review the response
```json theme={null}
{
"data": [
{
"id": "1524796546306478083",
"text": "Today marks the launch of Devs in the Details...",
"edit_history_tweet_ids": ["1524796546306478083"]
},
{
"id": "1524468552404668416",
"text": "Join us tomorrow for a discussion about bots...",
"edit_history_tweet_ids": ["1524468552404668416"]
}
],
"meta": {
"result_count": 2,
"newest_id": "1524796546306478083",
"oldest_id": "1524468552404668416",
"next_token": "7140dibdnow9c7btw421dyz6jism75z99gyxd8egarsc4"
}
}
```
***
## Step 4: Add fields and expansions
Request additional data with query parameters:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/timelines/reverse_chronological?\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id&\
user.fields=username,verified&\
max_results=10" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get home timeline with fields and expansions
for page in client.posts.get_home_timeline(
"2244994945",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id"],
user_fields=["username", "verified"],
max_results=10
):
for post in page.data:
print(f"{post.text[:50]}... - Likes: {post.public_metrics.like_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get home timeline with fields and expansions
const paginator = client.posts.getHomeTimeline("2244994945", {
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id"],
userFields: ["username", "verified"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.text?.slice(0, 50)}... - Likes: ${post.public_metrics?.like_count}`);
});
}
```
***
## Step 5: Paginate through results
The SDKs handle pagination automatically. For cURL, use the `next_token` from the response to get more results:
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/timelines/reverse_chronological?\
max_results=10&\
pagination_token=7140dibdnow9c7btw421dyz6jism75z99gyxd8egarsc4" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
***
## Common parameters
| Parameter | Description | Default |
| :------------ | :------------------------------------- | :------ |
| `max_results` | Results per page (1-100) | 10 |
| `start_time` | Oldest Post timestamp (ISO 8601) | — |
| `end_time` | Newest Post timestamp (ISO 8601) | — |
| `since_id` | Return Posts after this ID | — |
| `until_id` | Return Posts before this ID | — |
| `exclude` | Exclude `retweets`, `replies`, or both | — |
***
## Next steps
Get Posts mentioning a user
Key concepts and best practices
Full endpoint documentation
Navigate large result sets
# User Mentions Timeline
Source: https://docs.x.com/enterprise-api/posts/timelines/quickstart/user-mention-quickstart
This guide walks you through retrieving Posts that mention a specific user. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through retrieving Posts that mention a specific user.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token (for public data) or User Access Token (for private metrics)
***
## Get user mentions
Find the user ID using the [user lookup endpoint](/x-api/users/lookup/introduction). For example, @XDevelopers has user ID `2244994945`.
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/mentions?\
tweet.fields=created_at,public_metrics,author_id&\
expansions=author_id&\
user.fields=username,verified&\
max_results=10" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get mentions timeline with pagination
for page in client.posts.get_user_mentions(
"2244994945",
tweet_fields=["created_at", "public_metrics", "author_id"],
expansions=["author_id"],
user_fields=["username", "verified"],
max_results=10
):
for post in page.data:
print(f"@{post.author_id}: {post.text[:50]}...")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get mentions timeline with pagination
const paginator = client.posts.getUserMentions("2244994945", {
tweetFields: ["created_at", "public_metrics", "author_id"],
expansions: ["author_id"],
userFields: ["username", "verified"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`@${post.author_id}: ${post.text?.slice(0, 50)}...`);
});
}
```
```json theme={null}
{
"data": [
{
"id": "1301573587187331074",
"text": "Hey @XDevelopers, love the new API!",
"author_id": "1234567890",
"created_at": "2024-01-15T10:30:00.000Z",
"public_metrics": {
"retweet_count": 5,
"reply_count": 2,
"like_count": 42,
"quote_count": 1
}
}
],
"includes": {
"users": [
{
"id": "1234567890",
"username": "developer",
"name": "Dev Person",
"verified": false
}
]
},
"meta": {
"newest_id": "1301573587187331074",
"oldest_id": "1301573587187331074",
"result_count": 1,
"next_token": "t3buvdr5pujq9g7bggsnf3ep2ha28"
}
}
```
***
## Filter mentions
### Exclude replies
Get only original Posts that mention the user:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/mentions?\
exclude=replies&\
max_results=10" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get mentions excluding replies
for page in client.posts.get_user_mentions(
"2244994945",
exclude=["replies"],
max_results=10
):
for post in page.data:
print(post.text)
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get mentions excluding replies
const paginator = client.posts.getUserMentions("2244994945", {
exclude: ["replies"],
maxResults: 10,
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(post.text);
});
}
```
### Get mentions in a time range
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/mentions?\
start_time=2024-01-01T00%3A00%3A00Z&\
end_time=2024-01-31T23%3A59%3A59Z" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get mentions in a time range
for page in client.posts.get_user_mentions(
"2244994945",
start_time="2024-01-01T00:00:00Z",
end_time="2024-01-31T23:59:59Z"
):
for post in page.data:
print(f"{post.created_at}: {post.text[:50]}...")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get mentions in a time range
const paginator = client.posts.getUserMentions("2244994945", {
startTime: "2024-01-01T00:00:00Z",
endTime: "2024-01-31T23:59:59Z",
});
for await (const page of paginator) {
page.data?.forEach((post) => {
console.log(`${post.created_at}: ${post.text?.slice(0, 50)}...`);
});
}
```
***
## Common parameters
| Parameter | Description | Default |
| :----------------- | :------------------------------------- | :------ |
| `max_results` | Results per page (1-100) | 10 |
| `start_time` | Oldest Post timestamp (ISO 8601) | — |
| `end_time` | Newest Post timestamp (ISO 8601) | — |
| `since_id` | Return Posts after this ID | — |
| `until_id` | Return Posts before this ID | — |
| `exclude` | Exclude `retweets`, `replies`, or both | — |
| `pagination_token` | Token for next page | — |
***
## Next steps
Get user's home timeline
Key concepts and best practices
Full endpoint documentation
Navigate large result sets
# Volume streams (1% sampled and Decahose) on Enterprise
Source: https://docs.x.com/enterprise-api/posts/volume-streams/introduction
Stream sampled Posts in real time with the Enterprise 1% sampled stream and 10% Decahose volume stream endpoints to track trends, sentiment, and events.
* 1% sampled stream.
* 10% sampled stream. Commonly referred to as the "Decahose."
These are referred to as "volume streams" because they both deliver large volumes of data. Even the 1% stream can emit many dozens of Posts every second. With these streams, you can identify and track trends, monitor general sentiment, monitor global events, and much more.
These streaming endpoints deliver [Post objects](/x-api/fundamentals/data-dictionary/reference#tweet) through a persistent HTTP GET connection and use [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) authentication. With Essential access, you can have one connection at a time. With all levels of access, connection requests can be made up to 50 times per 15-minute window.
These volume stream endpoints support edited Posts. These endpoints will deliver edited Posts, along with its edit history, including an array of Post IDs. For Posts with no edit history, this array will hold a single ID. For Posts that have been edited, this array contains multiple IDs, arranged in ascending order reflecting the order of edits, with the most recent version in the last position of the array. To learn more about how Post edits work, see the [Post edits fundamentals](/x-api/fundamentals/edit-posts) page.
*To use these APIs, you must first set up an account with our enterprise sales team.*
**Account setup**
To access these endpoints, you will need:
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info).
* To authenticate using the keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started guide](/x-api/getting-started/getting-access).
***
## Streaming fundamentals
Best practices for streaming clients
Reconnect gracefully
Handle high throughput
Build resilient applications
# Handling disconnections
Source: https://docs.x.com/enterprise-api/powerstream/handling-disconnections
Handle disconnections, reconnects, and backfill on the Enterprise Powerstream endpoint with guidance on retries, error codes, and stream stability.
This page covers Powerstream-specific disconnection handling. For comprehensive guidance on handling disconnections across all streaming endpoints, see the [Handling disconnections fundamentals guide](/x-api/fundamentals/handling-disconnections).
## Powerstream disconnection handling
The core concepts for handling disconnections apply to all streaming endpoints. See the fundamentals guide for:
* Why connections disconnect
* Common disconnection errors
* Detecting disconnections
* Reconnection strategies and backoff
* Best practices
## Recovering lost data
If you experience a disconnect, see [Recovery and redundancy](/x-api/fundamentals/recovery-and-redundancy) for strategies to recover missed data, including:
* **Backfill** — Use the `backfillMinutes` parameter for disconnections of 5 minutes or less
* **Recovery** — Use `startTime` and `endTime` parameters for longer disconnections (up to 24 hours)
### Powerstream backfill example
```bash theme={null}
curl 'https://api.x.com/2/powerstream?backfillMinutes=5' \
-H "Authorization: Bearer $ACCESS_TOKEN"
```
### Powerstream recovery example
```bash theme={null}
curl 'https://api.x.com/2/powerstream?startTime=2022-07-12T15:10:00Z&endTime=2022-07-12T15:20:00Z' \
-H "Authorization: Bearer $ACCESS_TOKEN"
```
***
## Next steps
Complete disconnection handling guide
Recover missed data
Build robust streaming clients
# Powerstream low-latency streaming API on Enterprise
Source: https://docs.x.com/enterprise-api/powerstream/introduction
Powerstream is the Enterprise API's lowest-latency streaming endpoint for public X data, using PowerTrack-style rules to filter Posts by keywords and metadata.
Powerstream is our **lowest-latency streaming API** for accessing public X data in real-time. Unlike other streaming endpoints that prioritize data hydration and delivery (with \~6-7 seconds P99 latency), Powerstream is optimized for speed and delivers data with minimal delay.
Similar to the legacy GNIP Powertrack API, it uses rules to filter Posts based on keywords, operators, and metadata. Once a persistent HTTP connection is made to the Powerstream endpoint, you can start receiving matching Posts in real-time.
Currently, Powerstream supports up to 1,000 rules and each rule can be 2048 characters.
## Key features
* **Real-time data delivery**: Lowest latency option for streaming Posts as they're published.
* **Precise filtering**: Filter for exactly the data you are looking for using Boolean queries with operators.
* **Delivery**: JSON response over HTTP/1.1 chunked transfer encoding.
* **Local datacenter support**: Fetch Posts only from the local datacenter to further reduce latency by avoiding replication lag.
The Powerstream API is a premium offering available under select Enterprise plans.
If you're interested in accessing Powerstream or learning more about our Enterprise offerings, please reach out to our Sales team by submitting the [Enterprise Request Form](/forms/enterprise-api-interest).
We'll be happy to discuss how Powerstream can support your needs.
## Quick start
This section showcases how to quickly get started with the PowerStream endpoints using Python with the `requests` library. Install it via `pip install requests`. All examples use OAuth 2.0 Bearer Token authentication. Replace `YOUR_BEARER_TOKEN` with your actual token (store it securely, e.g., via `os.getenv('BEARER_TOKEN')`).
We'll cover each en
# Powerstream Operators
Source: https://docs.x.com/enterprise-api/powerstream/operators
This page provides a complete list of operators available when building rules for Powerstream. Reference for the Enterprise X API tier covering powerstream.
This page provides a complete list of operators available when building rules for [Powerstream](/x-api/powerstream/introduction).
## Overview
Powerstream uses Boolean queries with operators to filter Posts based on keywords and metadata. Rules can be up to 2,048 characters and you can have up to 1,000 rules.
***
## User operators
| Operator | Summary | Example |
| :------------- | :---------------------------------------- | :---------------------------------- |
| `from:` | Matches posts from a specific user | `from:xdevelopers` or `from:123456` |
| `to:` | Matches posts directed to a specific user | `to:jvaleski` |
| `retweets_of:` | Matches reposts of a specific user | `retweets_of:xdevelopers` |
***
## Content operators
| Operator | Summary | Example |
| :-------------- | :----------------------------------------------- | :--------------------------------------- |
| `contains:` | Matches posts containing specific text/keywords | `contains:hello` or `contains:-2345.432` |
| `url_contains:` | Matches posts with URLs containing specific text | `url_contains:"com/willplayforfood"` |
| `lang:` | Matches posts in specific languages | `lang:en` |
***
## Entity operators
| Operator | Summary | Example |
| :------- | :-------------------------------------------- | :-------------------------------------- |
| `has:` | Matches posts containing specific entities | `has:images`, `has:geo`, `has:mentions` |
| `is:` | Matches posts of specific types or properties | `is:retweet`, `is:reply` |
### Available `has:` options
* `has:mentions` — Posts that mention another user
* `has:geo` — Posts with geolocation data
* `has:links` — Posts containing links
* `has:media` — Posts containing media
* `has:lang` — Posts with detected language
* `has:symbols` — Posts containing cashtags
* `has:images` — Posts containing images
* `has:videos` — Posts containing videos
### Available `is:` options
* `is:retweet` — Retweets
* `is:reply` — Replies to other posts
***
## Location operators
| Operator | Summary | Example |
| :-------------- | :--------------------------------------------- | :----------------------------------------------------------------------------------------- |
| `place:` | Matches posts from specific places/locations | `place:"Belmont Central"` or `place:02763fa2a7611cf3` |
| `bounding_box:` | Matches posts within a geographic bounding box | `bounding_box:[-112.424083 42.355283 -112.409111 42.792311]` |
| `point_radius:` | Matches posts within a radius of a point | `point_radius:[-111.464973 46.371179 25mi]` or `point_radius:[-111.464973 46.371179 15km]` |
***
## User profile operators
| Operator | Summary | Example |
| :---------- | :------------------------------------------------- | :--------------------- |
| `bio:` | Matches posts from users with specific bio content | `bio:"data scientist"` |
| `bio_name:` | Matches posts from users with specific name in bio | `bio_name:PhD` |
***
## Post reference operators
| Operator | Summary | Example |
| :----------------------- | :-------------------------------- | :------------------------------------------ |
| `retweets_of_status_id:` | Matches reposts of specific posts | `retweets_of_status_id:1234567890123456789` |
| `in_reply_to_status_id:` | Matches replies to specific posts | `in_reply_to_status_id:1234567890123456789` |
***
## Special syntax operators
| Operator | Summary | Example |
| :--------- | :-------------------- | :--------------- |
| `@` | Mention operator | `@username` |
| `"phrase"` | Matches exact phrases | `"exact phrase"` |
***
## Logical operators
| Operator | Summary | Example |
| :-------- | :------------------------------- | :---------------------------------------- |
| `OR` | Logical OR between expressions | `x OR facebook` |
| Space/AND | Logical AND between expressions | `x facebook` (both terms must be present) |
| `()` | Grouping for complex expressions | `(x OR facebook) iphone` |
| `-` | Negation/exclusion | `x -facebook` (x but not facebook) |
***
## Building rules
### Basic examples
```
# Match posts from a specific user
from:xdevelopers
# Match posts containing keywords
contains:API contains:developer
# Match posts with images in English
has:images lang:en
```
### Combining operators
```
# Posts from @xdevelopers OR @api that aren't retweets
(from:xdevelopers OR from:api) -is:retweet
# Posts mentioning AI with images, excluding retweets
contains:AI has:images -is:retweet lang:en
# Posts within 25 miles of a location
point_radius:[-73.935242 40.730610 25mi] lang:en
```
***
## Next steps
Get started with Powerstream
Handle streaming disconnections
Recover missed data
# Recovery and redundancy
Source: https://docs.x.com/enterprise-api/powerstream/recovery-and-redundancy
This page covers Powerstream-specific recovery and redundancy features. Reference for the Enterprise X API tier covering powerstream.
This page covers Powerstream-specific recovery and redundancy features. For comprehensive guidance on recovery and redundancy across all streaming endpoints, see the [Recovery and redundancy fundamentals guide](/x-api/fundamentals/recovery-and-redundancy).
## Powerstream recovery features
The core concepts for recovery and redundancy apply to all streaming endpoints. See the fundamentals guide for:
* Redundant connections
* Backfill vs. Recovery decision tree
* Best practices
## Backfill
For disconnections of **5 minutes or less**, use the `backfillMinutes` parameter:
```bash theme={null}
curl 'https://api.x.com/2/powerstream?backfillMinutes=5' \
-H "Authorization: Bearer $ACCESS_TOKEN"
```
Older Posts are delivered first. Posts are **not** deduplicated — your system should be tolerant of duplicates.
## Recovery
For disconnections **longer than 5 minutes** (up to 24 hours), use the `startTime` and `endTime` parameters:
| Parameter | Type | Description |
| :---------- | :------------ | :------------------------------- |
| `startTime` | ISO 8601 date | Start time to recover from (UTC) |
| `endTime` | ISO 8601 date | End time to recover to (UTC) |
```bash theme={null}
curl 'https://api.x.com/2/powerstream?startTime=2022-07-12T15:10:00Z&endTime=2022-07-12T15:20:00Z' \
-H "Authorization: Bearer $ACCESS_TOKEN"
```
Once connected, Recovery will re-stream the specified time period, then disconnect.
***
## Next steps
Complete recovery guide
Handle streaming disconnections
Build robust streaming clients
# Get space by ID
Source: https://docs.x.com/enterprise-api/spaces/get-space-by-id
get /2/spaces/{id}
Retrieves details of a specific space by its ID.
# Get Space Posts
Source: https://docs.x.com/enterprise-api/spaces/get-space-posts
get /2/spaces/{id}/tweets
Retrieves a list of Posts shared in a specific Space by its ID.
# Get Space ticket buyers
Source: https://docs.x.com/enterprise-api/spaces/get-space-ticket-buyers
get /2/spaces/{id}/buyers
Retrieves a list of Users who purchased tickets to a specific Space by its ID.
# Get Spaces by creator IDs
Source: https://docs.x.com/enterprise-api/spaces/get-spaces-by-creator-ids
get /2/spaces/by/creator_ids
Retrieves details of Spaces created by specified User IDs.
# Get Spaces by IDs
Source: https://docs.x.com/enterprise-api/spaces/get-spaces-by-ids
get /2/spaces
Retrieves details of multiple Spaces by their IDs.
# Spaces endpoints on the Enterprise API
Source: https://docs.x.com/enterprise-api/spaces/introduction
Explore the X API Spaces endpoints to look up live or scheduled audio Spaces, search by keyword, and understand host, speaker, and listener roles.
The following page describes the Spaces endpoints included in the X API. To learn more about Spaces in general, please visit [help.x.com](https://help.x.com/en/using-twitter/spaces).
Spaces allow expression and interaction via live audio conversation. The Spaces endpoints provide the tools to create new functionality around Spaces. You can use these endpoints to lookup live or scheduled Spaces, or to build discovery experiences to give your users ways to find Spaces they may be interested in.
We encourage you to use your creativity to extend Spaces beyond the way we built it. With these endpoints you can build experiences to suggest Spaces to listeners based on keywords present in the title, or by surfacing accounts who host live or upcoming Spaces and are followed by a user; you can also help Hosts better understand how their Spaces are performing and get more insights on their audience.
### Important resources
The following resources will help you get started and integrate with the Spaces endpoints:
* [Getting access to X API v2](/x-api/getting-started/getting-access)
* [Spaces data dictionary](/x-api/fundamentals/data-dictionary/reference#space)
* [Make your first request to a Spaces endpoint](/x-api/spaces/lookup/introduction)
#### What's currently available
| | |
| :---------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Spaces lookup** | [Lookup by a single Spaces ID](/x-api/spaces/space-lookup-by-space-id)
[Lookup using multiple Spaces IDs](/x-api/spaces/space-lookup-up-space-ids)
[Lookup by their creator ID](/x-api/spaces/space-lookup-by-their-creators)
[Lookup list of user who purchased a ticket](/x-api/spaces/retrieve-the-list-of-users-who-purchased-a-ticket-to-the-given-space) |
| **Search Spaces** | [Search for spaces using a keyword](/x-api/spaces/search-for-spaces) |
#### Understanding the lifecycle of Spaces
Unlike other resources of the X Developer Platform, Spaces have a set lifecycle. Spaces can be scheduled up to 14 days in advance of their intended start date, and become unavailable after they end. A host can also cancel a previously scheduled Space anytime before it starts.
Spaces are accessible while they are live; once ended, they will no longer be available for retrieval using the Spaces endpoints, and an error message will be returned to indicate this condition.
When your app handles Spaces data, you are responsible for returning the most up-to-date information, and that you remove data that is no longer available from the platform. The [Spaces lookup endpoint](/x-api/spaces/lookup/introduction) can help you ensure you respect the expectations and intent of your users.
### Roles in Spaces
These endpoints reflect the way Spaces work on the X app. In Spaces, X users can have defined roles depending on how they interact with and interact in a Space.
### Creator (or primary host)
The primary Host is the user who created a Space, and the owner of the Space itself. Currently, Spaces can only have one Host, so the primary Host will be the only Host. In the [Spaces data dictionary](/x-api/fundamentals/data-dictionary/reference#space), the primary Host information will be in the creator\_id field, which can be expanded into a [user object](/x-api/fundamentals/data-dictionary/reference#user).
### Hosts
The primary Hosts can make one or more users co-hosts. In the Spaces data dictionary, these Hosts will appear as host\_ids, which can be expanded into a list of user objects. Host designation can change throughout the duration of a Space, and the metadata returned by these endpoints will reflect the status at the time of the request.
Your app will know the primary host by checking the creator\_id value, and who are the co-hosts by checking the host\_ids values.
### Speaker
Speakers are users who have permission to talk in the Space. Zero or more Speakers can be present at any time, and there may be up to 10 Speakers (including the Hosts) in a Space. In the Space data dictionary, speakers will be returned in the speaker\_ids list, which you can expand into a list of user objects.
### Listener
A Listener can listen to a Space, react anytime using the predefined reactions, and ask to become a speaker (when the Hosts allows this in the Space settings). Listener information will only be returned as an aggregate count of participants (including Hosts) in the participant\_count field.
# Spaces Lookup
Source: https://docs.x.com/enterprise-api/spaces/lookup/introduction
The Spaces lookup endpoints let you retrieve information about live or scheduled Spaces. Reference for the Enterprise X API tier covering lookup.
The Spaces lookup endpoints let you retrieve information about live or scheduled Spaces. Look up Spaces by their ID or find Spaces created by specific users.
## Overview
Get details for a specific Space
Look up multiple Spaces at once
Find Spaces by their hosts
Get users who purchased tickets
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------------------------- | :----------------------------- |
| GET | [`/2/spaces/:id`](/x-api/spaces/get-space-by-id) | Get Space by ID |
| GET | [`/2/spaces`](/x-api/spaces/get-spaces-by-ids) | Get Spaces by IDs |
| GET | [`/2/spaces/by/creator_ids`](/x-api/spaces/get-spaces-by-creator-ids) | Get Spaces by creator user IDs |
| GET | [`/2/spaces/:id/buyers`](/x-api/spaces/get-space-ticket-buyers) | Get ticket buyers for a Space |
| GET | [`/2/spaces/:id/tweets`](/x-api/spaces/get-space-posts) | Get Posts shared in a Space |
***
## Response fields
By default, the response includes `id` and `state`. Request additional fields:
| Field | Description |
| :------------------ | :------------------------ |
| `title` | Space title |
| `host_ids` | Host user IDs |
| `speaker_ids` | Speaker user IDs |
| `participant_count` | Number of participants |
| `scheduled_start` | Scheduled start time |
| `started_at` | Actual start time |
| `ended_at` | End time |
| `is_ticketed` | Whether Space has tickets |
### Space states
| State | Description |
| :---------- | :------------------- |
| `live` | Currently active |
| `scheduled` | Scheduled for future |
| `ended` | Has ended |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/spaces/1DXxyRYNejbKM?\
space.fields=title,host_ids,participant_count,scheduled_start,state" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Make your first Spaces lookup request
Find Spaces by keyword
Full endpoint documentation
Working code examples
# Quickstart
Source: https://docs.x.com/enterprise-api/spaces/lookup/quickstart
This guide walks you through retrieving Space information using the Spaces lookup endpoints. Reference for the Enterprise X API tier covering lookup.
This guide walks you through retrieving Space information using the Spaces lookup endpoints.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
## Get a Space by ID
Retrieve details for a specific Space:
```bash cURL theme={null}
curl "https://api.x.com/2/spaces/1DXxyRYNejbKM?\
space.fields=title,host_ids,participant_count,scheduled_start,state,created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a Space by ID
response = client.spaces.get(
"1DXxyRYNejbKM",
space_fields=["title", "host_ids", "participant_count", "scheduled_start", "state", "created_at"]
)
print(f"Space: {response.data.title}")
print(f"State: {response.data.state}")
print(f"Participants: {response.data.participant_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get a Space by ID
const response = await client.spaces.get("1DXxyRYNejbKM", {
spaceFields: ["title", "host_ids", "participant_count", "scheduled_start", "state", "created_at"],
});
console.log(`Space: ${response.data?.title}`);
console.log(`State: ${response.data?.state}`);
console.log(`Participants: ${response.data?.participant_count}`);
```
### Response
```json theme={null}
{
"data": {
"id": "1DXxyRYNejbKM",
"state": "live",
"title": "Discussing AI and the Future",
"host_ids": ["2244994945"],
"participant_count": 245,
"created_at": "2024-01-15T09:00:00.000Z"
}
}
```
***
## Get multiple Spaces
Look up multiple Spaces at once:
```bash cURL theme={null}
curl "https://api.x.com/2/spaces?\
ids=1DXxyRYNejbKM,1YqJDqWYNQDGW&\
space.fields=title,state,participant_count" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get multiple Spaces
response = client.spaces.get_spaces(
ids=["1DXxyRYNejbKM", "1YqJDqWYNQDGW"],
space_fields=["title", "state", "participant_count"]
)
for space in response.data:
print(f"{space.title} - {space.state}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get multiple Spaces
const response = await client.spaces.getSpaces({
ids: ["1DXxyRYNejbKM", "1YqJDqWYNQDGW"],
spaceFields: ["title", "state", "participant_count"],
});
response.data?.forEach((space) => {
console.log(`${space.title} - ${space.state}`);
});
```
***
## Get Spaces by creator
Find Spaces hosted by specific users:
```bash cURL theme={null}
curl "https://api.x.com/2/spaces/by/creator_ids?\
user_ids=2244994945,783214&\
space.fields=title,state,scheduled_start" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get Spaces by creator
response = client.spaces.get_by_creator_ids(
user_ids=["2244994945", "783214"],
space_fields=["title", "state", "scheduled_start"]
)
for space in response.data:
print(f"{space.title} - {space.state}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get Spaces by creator
const response = await client.spaces.getByCreatorIds({
userIds: ["2244994945", "783214"],
spaceFields: ["title", "state", "scheduled_start"],
});
response.data?.forEach((space) => {
console.log(`${space.title} - ${space.state}`);
});
```
***
## Include host information
Expand host user data:
```bash cURL theme={null}
curl "https://api.x.com/2/spaces/1DXxyRYNejbKM?\
space.fields=title,host_ids,state&\
expansions=host_ids&\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get Space with host info
response = client.spaces.get(
"1DXxyRYNejbKM",
space_fields=["title", "host_ids", "state"],
expansions=["host_ids"],
user_fields=["username", "verified"]
)
print(f"Space: {response.data.title}")
# Host info is in response.includes.users
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get Space with host info
const response = await client.spaces.get("1DXxyRYNejbKM", {
spaceFields: ["title", "host_ids", "state"],
expansions: ["host_ids"],
userFields: ["username", "verified"],
});
console.log(`Space: ${response.data?.title}`);
// Host info is in response.includes?.users
```
### Response with expansion
```json theme={null}
{
"data": {
"id": "1DXxyRYNejbKM",
"state": "live",
"title": "Discussing AI and the Future",
"host_ids": ["2244994945"]
},
"includes": {
"users": [
{
"id": "2244994945",
"username": "XDevelopers",
"verified": true
}
]
}
}
```
***
## Space states
| State | Description |
| :---------- | :------------------- |
| `live` | Currently active |
| `scheduled` | Scheduled for future |
| `ended` | Has ended |
***
## Available fields
| Field | Description |
| :------------------ | :------------------------ |
| `title` | Space title |
| `host_ids` | Host user IDs |
| `speaker_ids` | Speaker user IDs |
| `participant_count` | Current participants |
| `scheduled_start` | Scheduled start time |
| `started_at` | Actual start time |
| `ended_at` | End time |
| `is_ticketed` | Whether Space has tickets |
| `state` | Current state |
***
## Next steps
Find Spaces by keyword
Full endpoint documentation
# Search Spaces
Source: https://docs.x.com/enterprise-api/spaces/search-spaces
get /2/spaces/search
Retrieves a list of Spaces matching the specified search query.
# Spaces Search
Source: https://docs.x.com/enterprise-api/spaces/search/introduction
The Spaces Search endpoint lets you search for live or scheduled Spaces by keyword. Reference for the Enterprise X API tier covering search.
The Spaces Search endpoint lets you search for live or scheduled Spaces by keyword. Find Spaces about topics of interest.
## Overview
Search Spaces by title
Find live and upcoming Spaces
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :------------------------------------------------ | :---------------- |
| GET | [`/2/spaces/search`](/x-api/spaces/search-spaces) | Search for Spaces |
***
## Parameters
| Parameter | Description |
| :------------- | :------------------------------ |
| `query` | Search query (required) |
| `state` | Filter by `live` or `scheduled` |
| `space.fields` | Additional Space fields |
| `expansions` | Related objects to include |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/spaces/search?\
query=AI&\
state=live&\
space.fields=title,host_ids,participant_count" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example response
```json theme={null}
{
"data": [
{
"id": "1DXxyRYNejbKM",
"state": "live",
"title": "Discussing AI and the Future",
"host_ids": ["1234567890"],
"participant_count": 245
}
],
"meta": {
"result_count": 1
}
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Search for your first Space
Look up Spaces by ID
Full endpoint documentation
# Quickstart
Source: https://docs.x.com/enterprise-api/spaces/search/quickstart
Quickstart guide for searching X Spaces by keyword with the Enterprise tier Spaces search endpoint, covering authentication and example requests.
This guide walks you through searching for Spaces by keyword.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
## Search for Spaces
Search for Spaces matching a keyword:
```bash cURL theme={null}
curl "https://api.x.com/2/spaces/search?\
query=AI&\
space.fields=title,host_ids,participant_count,state&\
state=live" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search for Spaces
response = client.spaces.search(
query="AI",
space_fields=["title", "host_ids", "participant_count", "state"],
state="live"
)
for space in response.data:
print(f"{space.title} - {space.participant_count} participants")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search for Spaces
const response = await client.spaces.search({
query: "AI",
spaceFields: ["title", "host_ids", "participant_count", "state"],
state: "live",
});
response.data?.forEach((space) => {
console.log(`${space.title} - ${space.participant_count} participants`);
});
```
### Response
```json theme={null}
{
"data": [
{
"id": "1DXxyRYNejbKM",
"state": "live",
"title": "Discussing AI and the Future",
"host_ids": ["2244994945"],
"participant_count": 245
},
{
"id": "1YqJDqWYNQDGW",
"state": "live",
"title": "AI in Healthcare",
"host_ids": ["783214"],
"participant_count": 89
}
],
"meta": {
"result_count": 2
}
}
```
***
## Filter by state
Search only live or scheduled Spaces:
### Live Spaces only
```bash cURL theme={null}
curl "https://api.x.com/2/spaces/search?query=tech&state=live" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search live Spaces only
response = client.spaces.search(query="tech", state="live")
for space in response.data:
print(f"LIVE: {space.title}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search live Spaces only
const response = await client.spaces.search({
query: "tech",
state: "live",
});
response.data?.forEach((space) => {
console.log(`LIVE: ${space.title}`);
});
```
### Scheduled Spaces only
```bash cURL theme={null}
curl "https://api.x.com/2/spaces/search?query=tech&state=scheduled" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search scheduled Spaces only
response = client.spaces.search(query="tech", state="scheduled")
for space in response.data:
print(f"SCHEDULED: {space.title}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search scheduled Spaces only
const response = await client.spaces.search({
query: "tech",
state: "scheduled",
});
response.data?.forEach((space) => {
console.log(`SCHEDULED: ${space.title}`);
});
```
***
## Include host information
Expand host user data:
```bash cURL theme={null}
curl "https://api.x.com/2/spaces/search?\
query=AI&\
space.fields=title,host_ids,state&\
expansions=host_ids&\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search with host info
response = client.spaces.search(
query="AI",
space_fields=["title", "host_ids", "state"],
expansions=["host_ids"],
user_fields=["username", "verified"]
)
for space in response.data:
print(f"{space.title}")
# Host info is in response.includes.users
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Search with host info
const response = await client.spaces.search({
query: "AI",
spaceFields: ["title", "host_ids", "state"],
expansions: ["host_ids"],
userFields: ["username", "verified"],
});
response.data?.forEach((space) => {
console.log(space.title);
});
// Host info is in response.includes?.users
```
***
## Common parameters
| Parameter | Description |
| :------------- | :------------------------------------ |
| `query` | Search query (required) |
| `state` | Filter: `live`, `scheduled`, or `all` |
| `max_results` | Results to return (1-100) |
| `space.fields` | Space fields to include |
| `expansions` | Related objects to include |
| `user.fields` | User fields to include |
***
## Next steps
Look up Spaces by ID
Full endpoint documentation
# Get stream rule counts
Source: https://docs.x.com/enterprise-api/stream/get-stream-rule-counts
get /2/tweets/search/stream/rules/counts
Retrieves the count of rules in the active rule set for the filtered stream.
# Get stream rules
Source: https://docs.x.com/enterprise-api/stream/get-stream-rules
get /2/tweets/search/stream/rules
Retrieves the active rule set or a subset of rules for the filtered stream.
# Likes Streams
Source: https://docs.x.com/enterprise-api/stream/likes-streams-introduction
The Likes Streams endpoints deliver real-time like events through persistent HTTP GET connections. Reference for the Enterprise X API tier covering stream.
The Likes Streams endpoints deliver real-time like events through persistent HTTP GET connections. These streams provide access to like activity across X, enabling you to track engagement patterns, monitor content performance, and analyze liking behavior at scale.
Two streams are available:
* **All Likes stream** — Delivers all public like events in real time (firehose).
* **Sampled Likes stream** — Delivers a 10% sample of public like events.
These streaming endpoints use [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) authentication.
*To use these APIs, you must first set up an account with our enterprise sales team.*
**Account setup**
To access these endpoints, you will need:
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info).
* To authenticate using the keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started guide](/x-api/getting-started/getting-access).
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------------- | :---------------------------------- |
| GET | [`/2/likes/firehose/stream`](/x-api/stream/stream-all-likes) | Stream all like events in real time |
| GET | [`/2/likes/sample10/stream`](/x-api/stream/stream-sampled-likes) | Stream a 10% sample of like events |
***
## Streaming fundamentals
Best practices for streaming clients
Reconnect gracefully
Handle high throughput
Build resilient applications
# Stream 10% sampled Posts
Source: https://docs.x.com/enterprise-api/stream/stream-10-sampled-posts
get /2/tweets/sample10/stream
Streams a 10% sample of public Posts in real-time.
# Stream all Likes
Source: https://docs.x.com/enterprise-api/stream/stream-all-likes
get /2/likes/firehose/stream
Streams all public Likes in real-time.
# Stream all Posts
Source: https://docs.x.com/enterprise-api/stream/stream-all-posts
get /2/tweets/firehose/stream
Streams all public Posts in real-time.
# Stream English Posts
Source: https://docs.x.com/enterprise-api/stream/stream-english-posts
get /2/tweets/firehose/stream/lang/en
Streams all public English-language Posts in real-time.
# Stream filtered Posts
Source: https://docs.x.com/enterprise-api/stream/stream-filtered-posts
get /2/tweets/search/stream
Streams Posts in real-time matching the active rule set.
# Stream Japanese Posts
Source: https://docs.x.com/enterprise-api/stream/stream-japanese-posts
get /2/tweets/firehose/stream/lang/ja
Streams all public Japanese-language Posts in real-time.
# Stream Korean Posts
Source: https://docs.x.com/enterprise-api/stream/stream-korean-posts
get /2/tweets/firehose/stream/lang/ko
Streams all public Korean-language Posts in real-time.
# Stream Likes compliance data
Source: https://docs.x.com/enterprise-api/stream/stream-likes-compliance-data
get /2/likes/compliance/stream
Streams all compliance data related to Likes for Users.
# Stream Portuguese Posts
Source: https://docs.x.com/enterprise-api/stream/stream-portuguese-posts
get /2/tweets/firehose/stream/lang/pt
Streams all public Portuguese-language Posts in real-time.
# Stream Post labels
Source: https://docs.x.com/enterprise-api/stream/stream-post-labels
get /2/tweets/label/stream
Streams all labeling events applied to Posts.
# Stream Posts compliance data
Source: https://docs.x.com/enterprise-api/stream/stream-posts-compliance-data
get /2/tweets/compliance/stream
Streams all compliance data related to Posts.
# Stream sampled Likes
Source: https://docs.x.com/enterprise-api/stream/stream-sampled-likes
get /2/likes/sample10/stream
Streams a 10% sample of public Likes in real-time.
# Stream sampled Posts
Source: https://docs.x.com/enterprise-api/stream/stream-sampled-posts
get /2/tweets/sample/stream
Streams a 1% sample of public Posts in real-time.
# Stream Users compliance data
Source: https://docs.x.com/enterprise-api/stream/stream-users-compliance-data
get /2/users/compliance/stream
Streams all compliance data related to Users.
# Update stream rules
Source: https://docs.x.com/enterprise-api/stream/update-stream-rules
post /2/tweets/search/stream/rules
Adds or deletes rules from the active rule set for the filtered stream.
# Tools and libraries
Source: https://docs.x.com/enterprise-api/tools-and-libraries
# Get AI trend by ID
Source: https://docs.x.com/enterprise-api/trends/get-ai-trends-by-id
get /2/ai_trends/{id}
Retrieve a single AI-curated trend by its identifier, including metadata about the trend and the Posts driving it, via the Enterprise X API.
# Get personalized Trends
Source: https://docs.x.com/enterprise-api/trends/get-personalized-trends
get /2/users/personalized_trends
Retrieves personalized trending topics for the authenticated user.
# Get Trends by WOEID
Source: https://docs.x.com/enterprise-api/trends/get-trends-by-woeid
get /2/trends/by/woeid/{woeid}
Retrieves trending topics for a specific location identified by its WOEID.
# Personalized Trends
Source: https://docs.x.com/enterprise-api/trends/personalized-trends/introduction
The Personalized Trends endpoint returns trending topics tailored to the authenticated. Reference for the Enterprise X API tier covering personalized trends.
The Personalized Trends endpoint returns trending topics tailored to the authenticated user, based on their location and interests.
## Overview
Trends tailored to the user
Based on user's location
Current trending topics
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :----------------------------- | :---------------------- |
| GET | `/2/users/personalized_trends` | Get personalized trends |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/users/personalized_trends" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
## Example response
```json theme={null}
{
"data": [
{
"trend_name": "#AI",
"tweet_count": 125000
},
{
"trend_name": "Machine Learning",
"tweet_count": 85000
}
]
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
* Premium User Subscription
Get trends for a specific location
Full endpoint documentation
# Trends by WOEID
Source: https://docs.x.com/enterprise-api/trends/trends-by-woeid/introduction
The Trends by WOEID endpoint returns trending topics for a specific geographic location. Reference for the Enterprise X API tier covering trends by woeid.
The Trends by WOEID endpoint returns trending topics for a specific geographic location, identified by a Yahoo! Where On Earth ID (WOEID).
## Overview
Trends for any supported location
Countries, cities, and regions
Current trending topics
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :------------------------------------------------------------ | :--------------------- |
| GET | [`/2/trends/by/woeid/:id`](/x-api/trends/get-trends-by-woeid) | Get trends for a WOEID |
***
## Common WOEIDs
| Location | WOEID |
| :------------- | :------- |
| Worldwide | 1 |
| United States | 23424977 |
| United Kingdom | 23424975 |
| Japan | 23424856 |
| New York | 2459115 |
| Los Angeles | 2442047 |
| London | 44418 |
| Tokyo | 1118370 |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/trends/by/woeid/1" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example response
```json theme={null}
{
"data": [
{
"trend_name": "#AI",
"tweet_count": 250000
},
{
"trend_name": "Breaking News",
"tweet_count": 180000
}
]
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [Bearer Token](/resources/fundamentals/authentication)
Get trends for the authenticated user
Full endpoint documentation
# Get usage
Source: https://docs.x.com/enterprise-api/usage/get-usage
get /2/usage/tweets
Retrieves usage statistics for Posts over a specified number of days.
# Usage
Source: https://docs.x.com/enterprise-api/usage/introduction
The Usage endpoint lets you monitor your API usage, including the number of Posts consumed. Reference for the Enterprise X API tier covering usage.
The Usage endpoint lets you monitor your API usage, including the number of Posts consumed. Track your usage programmatically to manage costs and stay within limits.
Pay-per-usage plans are subject to a monthly cap of 2 million Post reads. If you need higher volume, consider an [Enterprise plan](/forms/enterprise-api-interest).
## Overview
Track Posts consumed
View usage by day
Monitor usage across your App
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :------------------------------------------ | :------------------ |
| GET | [`/2/usage/tweets`](/x-api/usage/get-usage) | Get Post usage data |
***
## Response data
The response includes daily Post consumption counts:
```json theme={null}
{
"data": {
"daily_project_usage": [
{
"date": "2024-01-15",
"usage": [
{
"app_id": "12345678",
"tweets_consumed": 15420
}
]
}
],
"project_id": "1234567890",
"project_cap": 10000000
}
}
```
### Fields
| Field | Description |
| :-------------------- | :------------------------ |
| `daily_project_usage` | Array of daily usage data |
| `date` | Date in YYYY-MM-DD format |
| `app_id` | Your App's ID |
| `tweets_consumed` | Posts consumed that day |
| `project_cap` | Your monthly Post limit |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/usage/tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Use cases
* **Cost monitoring** — Track consumption against your budget
* **Alerting** — Set up alerts when approaching limits
* **Optimization** — Identify high-consumption endpoints
* **Reporting** — Generate usage reports
Resources are deduplicated within a 24-hour UTC window, so requesting the same resource multiple times in a day only counts as one charge. [Learn more about pricing →](/x-api/getting-started/pricing)
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [Bearer Token](/resources/fundamentals/authentication)
Full endpoint documentation
View usage in the dashboard
# Block DMs
Source: https://docs.x.com/enterprise-api/users/block-dms
post /2/users/{id}/dm/block
Blocks direct messages to or from a specific User by their ID for the authenticated user.
# Integration Guide
Source: https://docs.x.com/enterprise-api/users/blocks/integrate
This guide covers the key concepts you need to integrate the blocks endpoints into your. Reference for the Enterprise X API tier covering blocks.
This guide covers the key concepts you need to integrate the blocks endpoints into your application.
The block and unblock users endpoints are only available under the Enterprise plan. You can fill out the Enterprise interest form [here](/forms/enterprise-api-interest).
***
## Authentication
Blocks endpoints require user authentication:
| Method | Description |
| :----------------------------------------------------------------------------------------------------------------------------- | :------------------------------- |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | Recommended for new applications |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Legacy support |
App-Only authentication is not supported. You must authenticate on behalf of a user.
### Required scopes (OAuth 2.0)
| Scope | Required for |
| :------------ | :------------------------------- |
| `block.read` | Retrieving blocked accounts |
| `block.write` | Blocking and unblocking accounts |
| `users.read` | Required with block scopes |
***
## Endpoints overview
| Method | Endpoint | Description | Availability |
| :----- | :-------------------------------------------------- | :--------------------------- | :------------------------------------------------------------- |
| GET | `/2/users/:id/blocking` | Get list of blocked accounts |
Pay-per-useEnterprise
|
| POST | `/2/users/:id/blocking` | Block an account | Enterprise |
| DELETE | `/2/users/:source_user_id/blocking/:target_user_id` | Unblock an account | Enterprise |
***
## Fields and expansions
### Default response
```json theme={null}
{
"data": [
{
"id": "1234567890",
"name": "Example User",
"username": "example"
}
]
}
```
### Available fields
| Field | Description |
| :------------------ | :------------------------ |
| `created_at` | Account creation date |
| `description` | User bio |
| `profile_image_url` | Avatar URL |
| `public_metrics` | Follower/following counts |
| `verified` | Verification status |
| Expansion | Description |
| :---------------- | :----------------- |
| `pinned_tweet_id` | User's pinned Post |
***
## What happens when you block
* See your Posts (unless logged out)
* Follow you
* Send you DMs
* Add you to Lists
* Tag you in photos
* See their Posts
* Follow them
* Send them DMs
When you block someone who follows you, they are automatically unfollowed.
***
## Pagination
For users with large block lists, results are paginated:
```bash cURL theme={null}
# First request
curl "https://api.x.com/2/users/123/blocking?max_results=100" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
# Subsequent request with pagination token
curl "https://api.x.com/2/users/123/blocking?max_results=100&pagination_token=NEXT_TOKEN" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
# Use OAuth 2.0 user access token
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# The SDK handles pagination automatically
all_blocked = []
for page in client.users.get_blocking(user_id="123", max_results=100):
if page.data:
all_blocked.extend(page.data)
print(f"Blocked {len(all_blocked)} users")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
async function getAllBlockedUsers(userId) {
const allBlocked = [];
// The SDK handles pagination automatically
const paginator = client.users.getBlocking(userId, { maxResults: 100 });
for await (const page of paginator) {
if (page.data) {
allBlocked.push(...page.data);
}
}
return allBlocked;
}
// Usage
const blocked = await getAllBlockedUsers("123");
console.log(`Blocked ${blocked.length} users`);
```
***
## Error handling
| Status | Error | Solution |
| :----- | :---------------- | :----------------------------------------------------------------------------------------------- |
| 400 | Invalid request | Check user ID format |
| 401 | Unauthorized | Verify access token |
| 403 | Forbidden | Check scopes and permissions. Block/unblock require [Enterprise](/forms/enterprise-api-interest) |
| 404 | Not Found | User doesn't exist |
| 429 | Too Many Requests | Wait and retry |
***
## Next steps
Make your first blocks request
Mute users instead of blocking
Full endpoint documentation
Working code examples
# Blocks
Source: https://docs.x.com/enterprise-api/users/blocks/introduction
The Blocks endpoints let you retrieve the list of users blocked by the authenticated user, as well. Reference for the Enterprise X API tier covering blocks.
The Blocks endpoints let you retrieve the list of users blocked by the authenticated user, as well as block and unblock users.
The block and unblock users endpoints are only available under the Enterprise plan. You can fill out the Enterprise interest form [here](/forms/enterprise-api-interest).
## Overview
Get your blocked user list
Block a user
Unblock a user
***
## Endpoints
| Method | Endpoint | Description | Availability |
| :----- | :--------------------------------------------------- | :---------------- | :------------------------------------------------------------- |
| GET | [`/2/users/:id/blocking`](/x-api/users/get-blocking) | Get blocked users |
Pay-per-useEnterprise
|
| POST | `/2/users/:id/blocking` | Block a user | Enterprise |
| DELETE | `/2/users/:source_user_id/blocking/:target_user_id` | Unblock a user | Enterprise |
***
## Example: Get blocked users
```bash theme={null}
curl "https://api.x.com/2/users/123456789/blocking?\
user.fields=username,description" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
## Example: Block a user (Enterprise only)
```bash theme={null}
curl -X POST "https://api.x.com/2/users/123456789/blocking" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target_user_id": "9876543210"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
Get started with blocks
Key concepts and best practices
Full endpoint documentation
# Migration guide
Source: https://docs.x.com/enterprise-api/users/blocks/migrate
The block and unblock users endpoints are only available under the Enterprise plan. Reference for the Enterprise X API tier covering blocks.
The block and unblock users endpoints are only available under the Enterprise plan. You can fill out the Enterprise interest form [here](/forms/enterprise-api-interest).
### Blocks lookup: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [GET blocks/ids](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/get-blocks-ids) and [GET blocks/list](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 blocks lookup endpoints.
* **Similarities**
* Authentication
* **Differences**
* Endpoint URLs
* Users per request limits
* App and Project requirements
* Response data formats
* Request parameters
#### Similarities
**Authentication**
Both the standard v1.1 and X API v2 blocks lookup endpoints use [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2). Therefore, if you were previously using one of the standard v1.1 blocks lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* GET [https://api.x.com/1.1/blocks/ids.json](https://api.x.com/1.1/blocks/ids.json)
(list of user IDs who are blocked by the specified user)
* GET [https://api.x.com/1.1/blocks/lists.json](https://api.x.com/1.1/blocks/lists.json)
(list of users who are blocked by the specified user)
* X API v2 endpoint:
* GET [https://api.x.com/2/users/:id/blocking](https://api.x.com/2/users/:id/blocking)
(list of users who are blocked by the specified user ID)
# Quickstart
Source: https://docs.x.com/enterprise-api/users/blocks/quickstart
This guide walks you through retrieving your block list, as well as blocking and unblocking users. Reference for the Enterprise X API tier covering blocks.
This guide walks you through retrieving your block list, as well as blocking and unblocking users.
The block and unblock users endpoints are only available under the Enterprise plan. You can fill out the Enterprise interest form [here](/forms/enterprise-api-interest).
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Get blocked users
You need your authenticated user's ID to retrieve your block list. You can get it from the `/2/users/me` endpoint or use the ID from your tokens.
```bash cURL theme={null}
curl "https://api.x.com/2/users/123456789/blocking?\
user.fields=username,verified,created_at&\
max_results=100" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get blocked users with pagination
for page in client.users.get_blocking(
"123456789",
user_fields=["username", "verified", "created_at"],
max_results=100
):
for user in page.data:
print(f"{user.username} - Created: {user.created_at}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get blocked users with pagination
const paginator = client.users.getBlocking("123456789", {
userFields: ["username", "verified", "created_at"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Created: ${user.created_at}`);
});
}
```
```json theme={null}
{
"data": [
{
"id": "17874544",
"name": "Example User",
"username": "example_user",
"verified": false,
"created_at": "2008-12-04T18:51:57.000Z"
}
],
"meta": {
"result_count": 1,
"next_token": "abc123"
}
}
```
***
## Block a user (Enterprise only)
Get the user ID of the account you want to block.
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/123456789/blocking" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target_user_id": "9876543210"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Block a user
response = client.users.block(
source_user_id="123456789",
target_user_id="9876543210"
)
print(f"Blocking: {response.data.blocking}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Block a user
const response = await client.users.block("123456789", {
targetUserId: "9876543210",
});
console.log(`Blocking: ${response.data?.blocking}`);
```
```json theme={null}
{
"data": {
"blocking": true
}
}
```
***
## Unblock a user (Enterprise only)
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/123456789/blocking/9876543210" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Unblock a user
response = client.users.unblock(
source_user_id="123456789",
target_user_id="9876543210"
)
print(f"Blocking: {response.data.blocking}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Unblock a user
const response = await client.users.unblock("123456789", "9876543210");
console.log(`Blocking: ${response.data?.blocking}`);
```
```json theme={null}
{
"data": {
"blocking": false
}
}
```
***
## Next steps
Mute users instead of blocking
Manage follows
Key concepts and best practices
Full endpoint documentation
# Create Bookmark
Source: https://docs.x.com/enterprise-api/users/create-bookmark
post /2/users/{id}/bookmarks
Adds a post to the authenticated user’s bookmarks.
# Delete Bookmark
Source: https://docs.x.com/enterprise-api/users/delete-bookmark
delete /2/users/{id}/bookmarks/{tweet_id}
Removes a Post from the authenticated user’s Bookmarks by its ID.
# Follow List
Source: https://docs.x.com/enterprise-api/users/follow-list
post /2/users/{id}/followed_lists
Causes the authenticated user to follow a specific List by its ID.
# Follow User
Source: https://docs.x.com/enterprise-api/users/follow-user
post /2/users/{id}/following
Causes the authenticated user to follow a specific user by their ID.
# Follows
Source: https://docs.x.com/enterprise-api/users/follows/introduction
The Follows endpoints let you follow and unfollow users, and retrieve follower and following lists. Reference for the Enterprise X API tier covering follows.
The Follows endpoints let you follow and unfollow users, and retrieve follower and following lists for any user.
## Overview
Follow a user on behalf of the authenticated user
Unfollow a user
Get a user's followers
Get who a user follows
***
## Endpoints
### Follows lookup
| Method | Endpoint | Description |
| :----- | :----------------------------------------------------- | :--------------------- |
| GET | [`/2/users/:id/followers`](/x-api/users/get-followers) | Get a user's followers |
| GET | [`/2/users/:id/following`](/x-api/users/get-following) | Get who a user follows |
### Manage follows
| Method | Endpoint | Description |
| :----- | :--------------------------------------------------------------------------------- | :-------------- |
| POST | [`/2/users/:id/following`](/x-api/users/follow-user) | Follow a user |
| DELETE | [`/2/users/:source_user_id/following/:target_user_id`](/x-api/users/unfollow-user) | Unfollow a user |
***
## Example: Get followers
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/followers?\
user.fields=username,verified,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example: Follow a user
```bash theme={null}
curl -X POST "https://api.x.com/2/users/123456789/following" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target_user_id": "2244994945"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Get started with follows
Full endpoint documentation
Working code examples
# Enterprise follows endpoints v2 migration
Source: https://docs.x.com/enterprise-api/users/follows/migrate/overview
Compare Standard v1.1 friendships and followers endpoints with X API v2 follow lookup and manage follows endpoints to migrate your integration.
## Comparing X API’s follows endpoints
### Follows lookup
The v2 follows lookup endpoints will replace the standard v1.1 [followers/ids](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids), v1.1 [followers/list](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/get-followers-list), v1.1 [friends/ids](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids), and v1.1 [friends/list](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/get-friends-list) endpoints.
The following tables compare the various types of follows lookup endpoints:
| | | |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint path | /1.1/friends/ids.json
/1.1/friends/list.json
/1.1/followers/ids.json
/1.1/followers/list.json | /2/users/:id/following
/2/users/:id/followers |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context
App only | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE
App only |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 15 requests per 15 min (per user)
15 requests per 15 min (per app) | 15 requests per 15 min (per user)
15 requests per 15 min (per app) |
| Maximum users per response | GET friends/id & GET followers/id return a maximum of 5000 users IDs per page.
GET friends/list & GET followers/list return a maximum of 200 user objects per page. | 1000 user objects per page |
| Pagination | Token returns in a next\_cursor field, which can then be passed as the value to the cursor parameter to return the next page of results. | Token returns in a next\_token field, which can then be passed as the value to the token parameter to return the next page of results.
The v2 payload also delivers a previous\_token field, which can also be passed with the pagination\_token parameter to return the previous page of results. |
| JSON format | Standard v1.1 format | [X API v2 format](/x-api/fundamentals/data-dictionary) (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
| Supports selecting which [fields](/x-api/fundamentals/data-dictionary) return in the payload | | ✔ |
| Supports the Post [annotations](/x-api/fundamentals/post-annotations) fields | | ✔ |
| Supports requesting new [metrics](/x-api/fundamentals/metrics) fields | | ✔ |
| Supports the [conversation\_id](/x-api/fundamentals/conversation-id) field | | ✔ |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [project](/resources/fundamentals/developer-apps) | | ✔ |
#### Manage follows
The v2 manage follows endpoints will replace the standard v1.1 [POST friendships/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create) and [POST friendships/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy) endpoints.
The following tables compare the standard v1.1 and X API v2 create follow endpoints:
#### Follow a user
| Description | Standard v1.1 | X API v2 |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- | :------------------------------------------------------------------------ |
| HTTP methods supported | POST | POST |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/friendships/create.json | /2/users/:id/following |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 50 requests per 15 min | 50 requests per 15 min |
| Maximum daily operations per users | 400 | 400 |
| Maximum daily operations per app | 1000 | 1000 |
| Requires use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
#### Unfollow a user
The following tables compare the standard v1.1 and X API v2 delete follow endpoints:
| Description | Standard v1.1 | X API v2 |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- | :------------------------------------------------------------------------ |
| HTTP methods supported | POST | DELETE |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/friendships/destroy.json | /2/users/:source\_user\_id/following/:target\_user\_id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 15 requests per 15 min (per user) | 50 requests per 15 min (per user) |
| Maximum daily operations per app | None | 500 |
| Requires use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
**Other migration resources**
[Follows lookup: Standard v1.1 to X API v2](/x-api/users/follows/migrate/standard-to-twitter-api-v2)
[Manage follows: Standard v1.1 to X API v2](/x-api/users/follows#manage-follows-standard-v1-1-compared-to-x-api-v2)
[X API migration hub](/x-api/migrate/overview)
# v1 to v2
Source: https://docs.x.com/enterprise-api/users/follows/migrate/standard-to-twitter-api-v2
If you have been working with the standard v1.1 POST friendships/create and POST. Reference for the Enterprise X API tier covering migrate.
#### Manage follows: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [POST friendships/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create) and [POST friendships/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard and X API v2 manage follows endpoints.
* **Similarities**
* OAuth 1.0a User Context
* **Differences**
* Endpoint URLs
* App and Project requirements
* HTTP methods
* Request parameters
#### Similarities
**OAuth 1.0a User Context authentication method**
Both the endpoint versions support [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2). Therefore, if you were previously using one of the standard v1.1 manage follows endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* POST [https://api.x.com/1.1/friendships/create.json](https://api.x.com/1.1/friendships/create.json)
(follow a user)
* POST [https://api.x.com/1.1/friendships/destroy.json](https://api.x.com/1.1/friendships/destroy.json)
(unfollow a user)
* X API v2 endpoint:
* POST [https://api.x.com/2/users/:id/following](https://api.x.com/2/users/:id/following)
(follow a user)
* DELETE [https://api.x.com/2/users/:source\\\_user\\\_id/following/:target\\\_user\\\_id](https://api.x.com/2/users/:source\\_user\\_id/following/:target\\_user\\_id)
(unfollow a user)
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated to a [Project](/resources/fundamentals/developer-apps) when authenticating your requests.
# Quickstart
Source: https://docs.x.com/enterprise-api/users/follows/quickstart
This guide walks you through retrieving followers and following lists, and managing follows. Reference for the Enterprise X API tier covering follows.
This guide walks you through retrieving followers and following lists, and managing follows.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token (for lookups)
* User Access Token (for managing follows)
***
## Get a user's followers
Retrieve the list of users following a specific user:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/followers?\
user.fields=username,verified,public_metrics&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get a user's followers with pagination
for page in client.users.get_followers(
"2244994945",
user_fields=["username", "verified", "public_metrics"],
max_results=100
):
for user in page.data:
print(f"{user.username} - Followers: {user.public_metrics.followers_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get a user's followers with pagination
const paginator = client.users.getFollowers("2244994945", {
userFields: ["username", "verified", "public_metrics"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Followers: ${user.public_metrics?.followers_count}`);
});
}
```
### Response
```json theme={null}
{
"data": [
{
"id": "1234567890",
"name": "Developer",
"username": "dev_user",
"verified": false,
"public_metrics": {
"followers_count": 500,
"following_count": 200,
"tweet_count": 1500
}
}
],
"meta": {
"result_count": 1,
"next_token": "abc123"
}
}
```
***
## Get who a user follows
Retrieve the list of users that a specific user follows:
```bash cURL theme={null}
curl "https://api.x.com/2/users/2244994945/following?\
user.fields=username,verified&\
max_results=100" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get users that a user follows
for page in client.users.get_following(
"2244994945",
user_fields=["username", "verified"],
max_results=100
):
for user in page.data:
print(f"{user.username} - Verified: {user.verified}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get users that a user follows
const paginator = client.users.getFollowing("2244994945", {
userFields: ["username", "verified"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Verified: ${user.verified}`);
});
}
```
***
## Follow a user
Follow a user on behalf of the authenticated user:
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/123456789/following" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target_user_id": "2244994945"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Follow a user
response = client.users.follow(
source_user_id="123456789",
target_user_id="2244994945"
)
print(f"Following: {response.data.following}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Follow a user
const response = await client.users.follow("123456789", {
targetUserId: "2244994945",
});
console.log(`Following: ${response.data?.following}`);
```
### Response
```json theme={null}
{
"data": {
"following": true,
"pending_follow": false
}
}
```
If the target account is protected, `pending_follow` will be `true` until the follow request is approved.
***
## Unfollow a user
Unfollow a user on behalf of the authenticated user:
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/123456789/following/2244994945" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Unfollow a user
response = client.users.unfollow(
source_user_id="123456789",
target_user_id="2244994945"
)
print(f"Following: {response.data.following}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Unfollow a user
const response = await client.users.unfollow("123456789", "2244994945");
console.log(`Following: ${response.data?.following}`);
```
### Response
```json theme={null}
{
"data": {
"following": false
}
}
```
***
## Common parameters
| Parameter | Description |
| :----------------- | :------------------------------------- |
| `max_results` | Results per page (1-1000, default 100) |
| `pagination_token` | Token for next page |
| `user.fields` | Additional user fields |
| `expansions` | Related objects to include |
***
## Next steps
Look up user profiles
Block and unblock users
Mute and unmute users
Full endpoint documentation
# Get affiliates
Source: https://docs.x.com/enterprise-api/users/get-affiliates
get /2/users/{id}/affiliates
Retrieves a list of Users who are affiliated with a specific organization User by their ID.
# Get blocking
Source: https://docs.x.com/enterprise-api/users/get-blocking
get /2/users/{id}/blocking
Retrieves a list of Users blocked by the specified User ID.
# Get Bookmark folders
Source: https://docs.x.com/enterprise-api/users/get-bookmark-folders
get /2/users/{id}/bookmarks/folders
Retrieves a list of Bookmark folders created by the authenticated user.
# Get Bookmarks
Source: https://docs.x.com/enterprise-api/users/get-bookmarks
get /2/users/{id}/bookmarks
Retrieves a list of Posts bookmarked by the authenticated user.
# Get Bookmarks by folder ID
Source: https://docs.x.com/enterprise-api/users/get-bookmarks-by-folder-id
get /2/users/{id}/bookmarks/folders/{folder_id}
Retrieves Posts in a specific Bookmark folder by its ID for the authenticated user.
# Get followed Lists
Source: https://docs.x.com/enterprise-api/users/get-followed-lists
get /2/users/{id}/followed_lists
Retrieves a list of Lists followed by a specific User by their ID.
# Get followers
Source: https://docs.x.com/enterprise-api/users/get-followers
get /2/users/{id}/followers
Retrieves a list of Users who follow a specific User by their ID.
# Get following
Source: https://docs.x.com/enterprise-api/users/get-following
get /2/users/{id}/following
Retrieves a list of Users followed by a specific User by their ID.
# Get liked Posts
Source: https://docs.x.com/enterprise-api/users/get-liked-posts
get /2/users/{id}/liked_tweets
Retrieves a list of Posts liked by a specific User by their ID.
# Get List memberships
Source: https://docs.x.com/enterprise-api/users/get-list-memberships
get /2/users/{id}/list_memberships
Retrieves a list of Lists that a specific User is a member of by their ID.
# Get mentions
Source: https://docs.x.com/enterprise-api/users/get-mentions
get /2/users/{id}/mentions
Retrieves a list of Posts that mention a specific User by their ID.
# Get muting
Source: https://docs.x.com/enterprise-api/users/get-muting
get /2/users/{id}/muting
Retrieves a list of Users muted by the authenticated user.
# Get my User
Source: https://docs.x.com/enterprise-api/users/get-my-user
get /2/users/me
Retrieves details of the authenticated user.
# Get owned Lists
Source: https://docs.x.com/enterprise-api/users/get-owned-lists
get /2/users/{id}/owned_lists
Retrieves a list of Lists owned by a specific User by their ID.
# Get pinned Lists
Source: https://docs.x.com/enterprise-api/users/get-pinned-lists
get /2/users/{id}/pinned_lists
Retrieves a list of Lists pinned by the authenticated user.
# Get Posts
Source: https://docs.x.com/enterprise-api/users/get-posts
get /2/users/{id}/tweets
Retrieves a list of posts authored by a specific User by their ID.
# Get public keys for multiple users
Source: https://docs.x.com/enterprise-api/users/get-public-keys-for-multiple-users
get /2/users/public_keys
Returns the public keys and Juicebox configuration for the specified users.
# Get Reposts of me
Source: https://docs.x.com/enterprise-api/users/get-reposts-of-me
get /2/users/reposts_of_me
Retrieves a list of Posts that repost content from the authenticated user.
# Get Timeline
Source: https://docs.x.com/enterprise-api/users/get-timeline
get /2/users/{id}/timelines/reverse_chronological
Retrieves a reverse chronological list of Posts in the authenticated User’s Timeline.
# Get User by ID
Source: https://docs.x.com/enterprise-api/users/get-user-by-id
get /2/users/{id}
Retrieves details of a specific User by their ID.
# Get User by username
Source: https://docs.x.com/enterprise-api/users/get-user-by-username
get /2/users/by/username/{username}
Retrieves details of a specific User by their username.
# Get user public keys
Source: https://docs.x.com/enterprise-api/users/get-user-public-keys
get /2/users/{id}/public_keys
Returns the public keys and Juicebox configuration for the specified user.
# Get Users by IDs
Source: https://docs.x.com/enterprise-api/users/get-users-by-ids
get /2/users
Retrieves details of multiple Users by their IDs.
# Get Users by usernames
Source: https://docs.x.com/enterprise-api/users/get-users-by-usernames
get /2/users/by
Retrieves details of multiple Users by their usernames.
# Like Post
Source: https://docs.x.com/enterprise-api/users/like-post
post /2/users/{id}/likes
Causes the authenticated user to Like a specific Post by its ID.
# Integration Guide
Source: https://docs.x.com/enterprise-api/users/lookup/integrate
This guide covers the key concepts you need to integrate the User lookup endpoints into your. Reference for the Enterprise X API tier covering lookup.
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:
| Method | Best for | Can access private metrics? |
| :----------------------------------------------------------------------------------------------------------------------------- | :---------------------------- | :------------------------------- |
| [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0) | Server-to-server, public data | No |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | User-facing apps | Yes (for authorized user's data) |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Legacy integrations | Yes (for authorized user's data) |
### App-Only authentication
For public user data, use a Bearer Token:
```bash cURL theme={null}
curl "https://api.x.com/2/users/by/username/XDevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
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)
```
```javascript JavaScript SDK theme={null}
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`):
```bash cURL theme={null}
curl "https://api.x.com/2/users/me" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
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)
```
```javascript JavaScript SDK theme={null}
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
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "XDevelopers"
}
}
```
### Available fields
| Field | Description |
| :------------------ | :--------------------------- |
| `created_at` | Account creation timestamp |
| `description` | User bio |
| `entities` | Parsed URLs in bio |
| `location` | User-defined location |
| `pinned_tweet_id` | Pinned Post ID |
| `profile_image_url` | Avatar URL |
| `protected` | Whether account is protected |
| `public_metrics` | Follower/following counts |
| `url` | Website URL |
| `verified` | Verification status |
| `withheld` | Withholding information |
| Field | Description |
| :--------------- | :----------------------- |
| `created_at` | Post creation timestamp |
| `text` | Post content |
| `public_metrics` | Engagement counts |
| `entities` | Hashtags, mentions, URLs |
### Example with fields
```bash cURL theme={null}
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"
```
```python Python SDK theme={null}
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
```
```javascript JavaScript SDK theme={null}
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
```json theme={null}
{
"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"
}
]
}
}
```
Learn more about customizing responses
***
## Batch lookups
Look up multiple users in a single request:
```bash cURL (by IDs) theme={null}
curl "https://api.x.com/2/users?ids=2244994945,783214,6253282&\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash cURL (by usernames) theme={null}
curl "https://api.x.com/2/users/by?usernames=XDevelopers,X,XAPI&\
user.fields=username,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```python Python SDK theme={null}
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}")
```
```javascript JavaScript SDK theme={null}
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
| Status | Error | Solution |
| :----- | :---------------- | :---------------------------------- |
| 400 | Invalid request | Check parameter formatting |
| 401 | Unauthorized | Verify authentication credentials |
| 403 | Forbidden | Check App permissions |
| 404 | Not Found | User doesn't exist or was suspended |
| 429 | Too Many Requests | Wait 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
```json theme={null}
{
"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
Use multi-user endpoints to fetch up to 100 users at once, reducing API calls.
Specify only the fields you need to minimize response size.
Cache user profiles locally to reduce repeated requests.
Check for partial errors in batch responses.
***
## Next steps
Complete endpoint documentation
All available objects and fields
Working code examples
Handle errors gracefully
# User Lookup
Source: https://docs.x.com/enterprise-api/users/lookup/introduction
The User lookup endpoints let you retrieve profile information for one or more users. Reference for the Enterprise X API tier covering lookup.
The User lookup endpoints let you retrieve profile information for one or more users. Look up users by their ID, username, or get details for the currently authenticated user.
## Overview
Look up users by their unique user ID
Look up users by their @handle
Retrieve up to 100 users per request
Get details for the current user
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------------------------- | :--------------------------------- |
| GET | [`/2/users/:id`](/x-api/users/get-user-by-id) | Get user by ID |
| GET | [`/2/users`](/x-api/users/get-users-by-ids) | Get users by IDs (up to 100) |
| GET | [`/2/users/by/username/:username`](/x-api/users/get-user-by-username) | Get user by username |
| GET | [`/2/users/by`](/x-api/users/get-users-by-usernames) | Get users by usernames (up to 100) |
| GET | [`/2/users/me`](/x-api/users/get-my-user) | Get authenticated user |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/users/by/username/XDevelopers?\
user.fields=created_at,description,public_metrics,verified" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example response
```json 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
}
}
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Look up users by ID or username
Get the current user's profile
Key concepts and best practices
Full endpoint documentation
# Enterprise user lookup v2 migration
Source: https://docs.x.com/enterprise-api/users/lookup/migrate/overview
Compare Standard v1.1 users/show and users/lookup endpoints with the X API v2 user lookup endpoints, including fields, expansions, and authentication.
## Comparing X API’s users lookup endpoints
The v2 user lookup endpoints will replace the standard v1.1 [GET users/lookup](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup.html) and [GET users/show](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/follow-search-get-users/api-reference/get-users-show.html) endpoints. If you have code, apps, or tools that use one of these versions of the user lookup endpoints, and are considering migrating to the newer X API v2 endpoint, then this set of guides is for you.
The following tables compare the various types of users lookup endpoints:
| | | |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | **Standard v1.1** | **X API v2** |
| HTTP methods supported | `GET` | `GET` |
| Host domain | `https://api.x.com` | `https://api.x.com` |
| Endpoint path | `/1.1/users/show.json` `/1.1/users/lookup.json` | `/2/users`
`/2/users/:id`
`/2/users/by`
`/2/users/by/:username` |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
App only
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 900 requests per 15 min (per user)
/show - 900 requests per 15 min (per app) /lookup - 300 requests per 15 min (per app) | 900 requests per 15 min (per user)
300 requests per 15 min (per app) |
| Maximum Users per response | /show - 1
/lookup - 100 | 100 |
| JSON response object format | Standard v1.1 format | [X API v2 format](/x-api/fundamentals/data-dictionary) (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
| Supports selecting which [fields](/x-api/fundamentals/data-dictionary) return in the payload | | ✔ |
| Supports the [annotations](/x-api/fundamentals/post-annotations) fields (on pinned Post) | | ✔ |
| Supports requesting new [metrics](/x-api/fundamentals/metrics) fields (on pinned Post) | | ✔ |
| Supports the [conversation\_id](/x-api/fundamentals/conversation-id) field (on pinned Post) | | ✔ |
| Requires the use of credentials from a [developer App](/resources/fundamentals/developer-apps) associated with a [project](/resources/fundamentals/developer-apps) | | ✔ |
**Other migration resources**
[User lookup: Standard v1.1 to X API v2](/x-api/users/lookup/migrate/standard-to-twitter-api-v2)
[X API migration hub](/x-api/migrate/overview)
[Check out some sample code for these endpoints](https://github.com/xdevplatform/Twitter-API-v2-sample-code "Check out some sample code for these endpoints")
# v1 to v2
Source: https://docs.x.com/enterprise-api/users/lookup/migrate/standard-to-twitter-api-v2
If you have been working with the standard v1.1 GET users/show and GET users/lookup, the goal of. Reference for the Enterprise X API tier covering migrate.
### Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 GET users/show and GET users/lookup, the goal of this guide is to help you understand the similarities and differences between the standard and X API v2 users lookup endpoints.
* **Similarities**
* OAuth 1.0a User Context
* Users per request limits
* **Differences**
* Endpoint URLs
* App and Project requirements
* Response data format
* Request parameters
#### Similarities
**OAuth 1.0a User Context authentication method**
The standard endpoint supports [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2), while the new X API v2 users lookup endpoints support both OAuth 1.0a User Context and [App only](/resources/fundamentals/authentication#oauth-2-0). Therefore, if you were previously using one of the standard v1.1 users lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
Depending on your authentication library/package of choice, App only authentication is probably the easiest way to get started and can be set with a simple request header. To learn how to generate an App only Access Token, see [this App only guide](/resources/fundamentals/authentication#bearer-token-also-known-as-app-only).
**Users per request limits**
The standard v1.1 GET users/lookup endpoint allows you to specify 100 users per request. This also goes for the GET /users and GET /users/by endpoints. To specify a full 100 users, you will need to pass the ids (GET /users) parameter or the username (GET /users/by) parameter as a query parameter, and include the list of user IDs/usernames in a comma-separated list.
#### Differences
**Endpoint URLs**
# Authenticated User Quickstart
Source: https://docs.x.com/enterprise-api/users/lookup/quickstart/authenticated-lookup
This guide walks you through retrieving the currently authenticated user's profile using the. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through retrieving the currently authenticated user's profile using the `/me` endpoint.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Get the authenticated user
Make a request to the `/me` endpoint with a User Access Token:
```bash cURL theme={null}
curl "https://api.x.com/2/users/me?\
user.fields=created_at,description,verified,public_metrics,profile_image_url" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get the authenticated user
response = client.users.get_me(
user_fields=["created_at", "description", "verified", "public_metrics", "profile_image_url"]
)
print(f"Username: {response.data.username}")
print(f"ID: {response.data.id}")
print(f"Followers: {response.data.public_metrics.followers_count}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get the authenticated user
const response = await client.users.getMe({
userFields: ["created_at", "description", "verified", "public_metrics", "profile_image_url"],
});
console.log(`Username: ${response.data?.username}`);
console.log(`ID: ${response.data?.id}`);
console.log(`Followers: ${response.data?.public_metrics?.followers_count}`);
```
***
## Response
```json 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,
"profile_image_url": "https://pbs.twimg.com/profile_images/...",
"public_metrics": {
"followers_count": 583423,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
***
## Use case
The `/me` endpoint is essential when:
* **Verifying authentication** — Confirm the user is properly authenticated
* **Getting the user ID** — Retrieve the authenticated user's ID for other API calls
* **Personalizing experiences** — Display the user's profile in your app
* **On behalf of requests** — Know who you're making requests for
***
## Include pinned Post
Request the user's pinned Post:
```bash cURL theme={null}
curl "https://api.x.com/2/users/me?\
user.fields=pinned_tweet_id&\
expansions=pinned_tweet_id&\
tweet.fields=created_at,text" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get authenticated user with pinned Post
response = client.users.get_me(
user_fields=["pinned_tweet_id"],
expansions=["pinned_tweet_id"],
tweet_fields=["created_at", "text"]
)
print(f"Username: {response.data.username}")
# Pinned Post is in response.includes.tweets
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get authenticated user with pinned Post
const response = await client.users.getMe({
userFields: ["pinned_tweet_id"],
expansions: ["pinned_tweet_id"],
tweetFields: ["created_at", "text"],
});
console.log(`Username: ${response.data?.username}`);
// Pinned Post is in response.includes?.tweets
```
### Response with expansion
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "XDevelopers",
"pinned_tweet_id": "1234567890"
},
"includes": {
"tweets": [
{
"id": "1234567890",
"text": "Welcome to my profile!",
"created_at": "2024-01-01T00:00:00.000Z"
}
]
}
}
```
***
## Available fields
| Field | Description |
| :------------------ | :------------------------ |
| `created_at` | Account creation date |
| `description` | User bio |
| `profile_image_url` | Avatar URL |
| `verified` | Verification status |
| `public_metrics` | Follower/following counts |
| `location` | User-defined location |
| `url` | User's website |
| `protected` | Protected account status |
| `pinned_tweet_id` | Pinned Post ID |
***
## Authentication requirement
The `/me` endpoint requires User Context authentication. App-Only (Bearer Token) authentication is not supported.
Use either:
* [OAuth 1.0a User Context](/resources/fundamentals/authentication)
* [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
***
## Next steps
Look up other users
Key concepts and best practices
Full endpoint documentation
# User Lookup Quickstart
Source: https://docs.x.com/enterprise-api/users/lookup/quickstart/user-lookup
This guide walks you through looking up users by their ID or username. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through looking up users by their ID or username.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* Your App's Bearer Token
***
## Look up by ID
### Single user
```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 Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get user by 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 JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get user by 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}`);
```
### Response
```json 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
}
}
}
```
### Multiple users
Look up to 100 users at once:
```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 Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get multiple users by 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 JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get multiple users by 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}`);
});
```
***
## Look up by username
### Single user
```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 Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get user by 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" });
// Get user by 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}`);
```
### Multiple users
```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 Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Get multiple users by 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 JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });
// Get multiple users by 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}`);
});
```
***
## Available fields
| Field | Description |
| :------------------ | :------------------------ |
| `created_at` | Account creation date |
| `description` | User bio |
| `profile_image_url` | Avatar URL |
| `verified` | Verification status |
| `public_metrics` | Follower/following counts |
| `location` | User-defined location |
| `url` | User's website |
| `protected` | Protected account status |
| `pinned_tweet_id` | Pinned Post ID |
***
## Handle errors
### User not found
```json theme={null}
{
"errors": [
{
"resource_type": "user",
"title": "Not Found Error",
"detail": "Could not find user with username: [nonexistent_user]."
}
]
}
```
### Protected user
Protected users' data is still returned, but you won't be able to access their Posts unless you follow them.
***
## Next steps
Get the current user
Key concepts and best practices
Full endpoint documentation
# Mute User
Source: https://docs.x.com/enterprise-api/users/mute-user
post /2/users/{id}/muting
Causes the authenticated user to mute a specific User by their ID.
# Integration Guide
Source: https://docs.x.com/enterprise-api/users/mutes/integrate
This guide covers the key concepts you need to integrate the mutes endpoints into your application. Reference for the Enterprise X API tier covering mutes.
This guide covers the key concepts you need to integrate the mutes endpoints into your application.
***
## Authentication
Mutes endpoints require user authentication to access private mute lists:
| Method | Description |
| :----------------------------------------------------------------------------------------------------------------------------- | :------------------------------- |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | Recommended for new applications |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication) | Legacy support |
App-Only authentication is not supported. You must authenticate on behalf of a user.
### Required scopes (OAuth 2.0)
| Scope | Required for |
| :----------- | :--------------------------- |
| `mute.read` | Retrieving muted accounts |
| `mute.write` | Muting and unmuting accounts |
| `users.read` | Required with mute scopes |
***
## Endpoints overview
| Method | Endpoint | Description |
| :----- | :------------------------------------------------ | :------------------------- |
| GET | `/2/users/:id/muting` | Get list of muted accounts |
| POST | `/2/users/:id/muting` | Mute an account |
| DELETE | `/2/users/:source_user_id/muting/:target_user_id` | Unmute an account |
***
## Fields and expansions
### Default response
```json theme={null}
{
"data": [
{
"id": "1234567890",
"name": "Example User",
"username": "example"
}
]
}
```
### Available fields
| Field | Description |
| :------------------ | :------------------------ |
| `created_at` | Account creation date |
| `description` | User bio |
| `profile_image_url` | Avatar URL |
| `public_metrics` | Follower/following counts |
| `verified` | Verification status |
| Expansion | Description |
| :---------------- | :----------------- |
| `pinned_tweet_id` | User's pinned Post |
### Example with fields
```bash cURL theme={null}
curl "https://api.x.com/2/users/123456789/muting?\
user.fields=username,verified,created_at&\
max_results=100" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get muted users with additional fields
for page in client.users.get_muting(
user_id="123456789",
user_fields=["username", "verified", "created_at"],
max_results=100
):
for user in page.data:
print(f"{user.username} - Verified: {user.verified}")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
const paginator = client.users.getMuting("123456789", {
userFields: ["username", "verified", "created_at"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Verified: ${user.verified}`);
});
}
```
***
## Pagination
For users with large mute lists, results are paginated:
```bash cURL theme={null}
# First request
curl "https://api.x.com/2/users/123/muting?max_results=100" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
# Subsequent request with pagination token
curl "https://api.x.com/2/users/123/muting?max_results=100&pagination_token=NEXT_TOKEN" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# The SDK handles pagination automatically
all_muted = []
for page in client.users.get_muting(user_id="123", max_results=100):
if page.data:
all_muted.extend(page.data)
print(f"Muted {len(all_muted)} users")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
async function getAllMutedUsers(userId) {
const allMuted = [];
// The SDK handles pagination automatically
const paginator = client.users.getMuting(userId, { maxResults: 100 });
for await (const page of paginator) {
if (page.data) {
allMuted.push(...page.data);
}
}
return allMuted;
}
// Usage
const muted = await getAllMutedUsers("123");
console.log(`Muted ${muted.length} users`);
```
Learn more about pagination
***
## Behavior differences
### Muting vs Blocking
| Feature | Mute | Block |
| :------------------ | :--------------- | :----------- |
| See their Posts | No (hidden) | No |
| They see your Posts | Yes | No |
| They follow you | Yes (can follow) | No (removed) |
| They can DM you | Yes | No |
| Notification sent | No | No |
Muting is private — the muted user is not notified and cannot tell they've been muted.
***
## Error handling
| Status | Error | Solution |
| :----- | :---------------- | :--------------------------- |
| 400 | Invalid request | Check user ID format |
| 401 | Unauthorized | Verify access token |
| 403 | Forbidden | Check scopes and permissions |
| 404 | Not Found | User doesn't exist |
| 429 | Too Many Requests | Wait and retry |
***
## Next steps
Make your first mutes request
Block users instead of muting
Full endpoint documentation
Working code examples
# Mutes
Source: https://docs.x.com/enterprise-api/users/mutes/introduction
Use the Enterprise Mutes endpoints to mute and unmute accounts on behalf of the authenticated user and retrieve the full list of users they have muted on X.
The Mutes endpoints let you mute and unmute users, and retrieve the list of users muted by the authenticated user.
## Overview
Mute a user
Unmute a user
Get your muted user list
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :---------------------------------------------------------------------------- | :-------------- |
| GET | [`/2/users/:id/muting`](/x-api/users/get-muting) | Get muted users |
| POST | [`/2/users/:id/muting`](/x-api/users/mute-user) | Mute a user |
| DELETE | [`/2/users/:source_user_id/muting/:target_user_id`](/x-api/users/unmute-user) | Unmute a user |
***
## Example: Get muted users
```bash theme={null}
curl "https://api.x.com/2/users/123456789/muting?\
user.fields=username,description" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
## Example: Mute a user
```bash theme={null}
curl -X POST "https://api.x.com/2/users/123456789/muting" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target_user_id": "9876543210"}'
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* User Access Tokens via [OAuth 2.0 PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2)
Get your muted users
Mute and unmute users
Key concepts and best practices
Full endpoint documentation
# Manage mutes
Source: https://docs.x.com/enterprise-api/users/mutes/migrate/manage-mutes-standard-to-twitter-api-v2
If you have been working with the standard v1.1 POST mutes/users/create and POST. Reference for the Enterprise X API tier covering migrate.
### Manage mutes: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [POST mutes/users/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-create) and [POST mutes/users/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-destroy) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 manage mutes endpoints.
* **Similarities**
* OAuth 1.0a User Context
* **Differences**
* Endpoint URLs
* App and Project requirements
* HTTP methods
* Request parameters
#### Similarities
**OAuth 1.0a User Context authentication method**
Both the endpoint versions support [OAuth 1.0a User Context](https://developer.x.com/content/developer-twitter/resources/fundamentals/authentication). Therefore, if you were previously using one of the standard v1.1 manage mutes endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* POST [https://api.x.com/1.1/mutes/users/create.json](https://api.x.com/1.1/mutes/users/create.json)
(mute a user)
* POST [https://api.x.com/1.1/mutes/users/destroy.json](https://api.x.com/1.1/mutes/users/destroy.json)
(unmute a user)
* X API v2 endpoint:
* POST [https://api.x.com/2/users/:id/muting](https://api.x.com/2/users/:id/muting)
(mute a user)
* DELETE [https://api.x.com/2/users/:source\\\_user\\\_id/muting/:target\\\_user\\\_id](https://api.x.com/2/users/:source\\_user\\_id/muting/:target\\_user\\_id)
(unmute a user)
**App and Project requirements**
The X API v2 endpoints require that you use credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a \[Project
# Mutes lookup
Source: https://docs.x.com/enterprise-api/users/mutes/migrate/mutes-lookup-standard-to-twitter-api-v2
If you have been working with the standard v1.1 GET mutes/users/ids and GET mutes/users/list. Reference for the Enterprise X API tier covering migrate.
### Mutes lookup: Standard v1.1 compared to X API v2
If you have been working with the standard v1.1 [GET mutes/users/ids](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-ids) and [GET mutes/users/list](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-list) endpoints, the goal of this guide is to help you understand the similarities and differences between the standard v1.1 and X API v2 mutes lookup endpoints.
* **Similarities**
* Authentication
* **Differences**
* Endpoint URLs
* Users per request limits
* App and Project requirements
* Response data formats
* Request parameters
#### Similarities
**Authentication**
Both the standard v1.1 and X API v2 mutes lookup endpoints use [OAuth 1.0a User Context](/resources/fundamentals/authentication#oauth-1-0a-2). Therefore, if you were previously using one of the standard v1.1 mutes lookup endpoints, you can continue using the same authentication method if you migrate to the X API v2 version.
#### Differences
**Endpoint URLs**
* Standard v1.1 endpoints:
* GET [https://api.x.com/1.1/mutes/users/ids.json](https://api.x.com/1.1/mutes/users/ids.json)
(list of user IDs who the specified user muted)
* GET [https://api.x.com/1.1/mutes/users/lists.json](https://api.x.com/1.1/mutes/users/lists.json)
(list of users who are muted by the specified user)
* X API v2 endpoint:
* GET [https://api.x.com/2/users/:id/muting](https://api.x.com/2/users/:id/muting)
(list of users who are muted by the specified user ID)
**Users per request limits**
The standard v1.1 endpoints allow you to return up to 5000 users per request. The new v2 endpoints allow you to return up to 1000 users per request. To return a full 1000 users, you w
# Enterprise mutes endpoints v2 migration
Source: https://docs.x.com/enterprise-api/users/mutes/migrate/overview
Compare Standard v1.1 mutes endpoints with the X API v2 mutes lookup and manage mutes endpoints, including parameter, auth, and rate limit changes.
## Comparing X API’s mutes endpoints
#### Mutes lookup
The v2 mutes lookup endpoint will replace the standard [v1.1 GET mutes/users/ids](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-ids) and [GET mutes/users/list](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-list) endpoints.
The following tables compare the standard v1.1 and X API v2 mute endpoints:
| Description | Standard v1.1 | X API v2 |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP methods supported | **GET** | **GET** |
| Host domain | **[https://api.x.com](https://api.x.com)** | **[https://api.x.com](https://api.x.com)** |
| Endpoint path | **/1.1/mutes/users/ids.json**
/1.1/mutes/users/list.json | **/2/users/:id/muting** |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 15 requests per 15 min (per user) | 15 requests per 15 min (per user) |
| Data formats | Standard v1.1 format | [X API v2 format](/x-api/fundamentals/data-dictionary) (determined by fields and expansions request parameters, not backward-compatible with v1.1 formats)
To learn more about how to migrate from the Standard v1.1 format to the X API v2 format, please visit our [data formats migration guide](/x-api/migrate/data-format-migration). |
| Requires use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
#### Manage mutes
The v2 manage mutes endpoints will replace the standard v1.1 [POST mutes/users/create](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-create) and [POST mutes/users/destroy](https://developer.x.com/en/docs/twitter-api/v1/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-destroy) endpoints.
The following tables compare the standard v1.1 and X API v2 mute endpoints:
**Mute a user**
| Description | Standard v1.1 | X API v2 |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- | :------------------------------------------------------------------------ |
| HTTP methods supported | POST | POST |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/mutes/users/create.json | /2/users/:id/muting |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 50 requests per 15 min | 50 requests per 15 min |
| Requires use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
**Unmute a user**
The following tables compare the standard v1.1 and X API v2 unmute endpoints:
| Description | Standard v1.1 | X API v2 |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- | :------------------------------------------------------------------------ |
| HTTP methods supported | POST | DELETE |
| Host domain | [https://api.x.com](https://api.x.com) | [https://api.x.com](https://api.x.com) |
| Endpoint path | /1.1/mutes/users/destroy.json | /2/users/:source\_user\_id/muting/:target\_user\_id |
| [Authentication](/resources/fundamentals/authentication) | OAuth 1.0a User Context | OAuth 1.0a User Context
OAuth 2.0 Authorization Code with PKCE |
| Default request [rate limits](/resources/fundamentals/rate-limits) | 50 requests per 15 min | 50 requests per 15 min |
| Requires use of credentials from a [developer App](/resources/fundamentals/developer-apps) that is associated with a [Project](/resources/fundamentals/developer-apps) | | ✔️ |
**Other migration resources**
[Manage mutes: Standard v1.1 to X API v2](/x-api/users/mutes#manage-mutes-standard-v1-1-compared-to-x-api-v2)
[X API migration hub](/x-api/migrate/overview)
# Manage Mutes
Source: https://docs.x.com/enterprise-api/users/mutes/quickstart/manage-mutes-quickstart
This guide walks you through muting and unmuting users using the X API. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through muting and unmuting users using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Mute a user
You need your authenticated user's ID. You can find it using the [user lookup endpoint](/x-api/users/lookup/introduction) or from your Access Token (the numeric part is your user ID).
Find the user ID of the account you want to mute using the [user lookup endpoint](/x-api/users/lookup/introduction).
```bash cURL theme={null}
curl -X POST "https://api.x.com/2/users/123456789/muting" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"target_user_id": "9876543210"}'
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Mute a user
response = client.users.mute(
source_user_id="123456789",
target_user_id="9876543210"
)
print(f"Muting: {response.data.muting}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Mute a user
const response = await client.users.mute("123456789", {
targetUserId: "9876543210",
});
console.log(`Muting: ${response.data?.muting}`);
```
```json theme={null}
{
"data": {
"muting": true
}
}
```
***
## Unmute a user
Remove a mute from a user:
```bash cURL theme={null}
curl -X DELETE "https://api.x.com/2/users/123456789/muting/9876543210" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
# Unmute a user
response = client.users.unmute(
source_user_id="123456789",
target_user_id="9876543210"
)
print(f"Muting: {response.data.muting}")
```
```javascript JavaScript SDK theme={null}
import { Client, OAuth1 } from "@xdevplatform/xdk";
const oauth1 = new OAuth1({
apiKey: "YOUR_API_KEY",
apiSecret: "YOUR_API_SECRET",
accessToken: "YOUR_ACCESS_TOKEN",
accessTokenSecret: "YOUR_ACCESS_TOKEN_SECRET",
});
const client = new Client({ oauth1 });
// Unmute a user
const response = await client.users.unmute("123456789", "9876543210");
console.log(`Muting: ${response.data?.muting}`);
```
**Response:**
```json theme={null}
{
"data": {
"muting": false
}
}
```
***
## Mute vs Block
| Feature | Mute | Block |
| :------------------ | :--- | :---- |
| See their Posts | No | No |
| They see your Posts | Yes | No |
| They can follow you | Yes | No |
| They can DM you | Yes | No |
| They know | No | Yes |
***
## Next steps
Get your muted users
Block users instead
Full endpoint documentation
# Mutes Lookup
Source: https://docs.x.com/enterprise-api/users/mutes/quickstart/mutes-lookup
This guide walks you through retrieving your muted users list using the X API. Reference for the Enterprise X API tier covering quickstart.
This guide walks you through retrieving your muted users list using the X API.
**Prerequisites**
Before you begin, you'll need:
* A [developer account](https://developer.x.com/en/portal/petition/essential/basic-info) with an approved App
* User Access Token (OAuth 1.0a or OAuth 2.0 PKCE)
***
## Get your muted users
You need your authenticated user's ID. You can find it using the [user lookup endpoint](/x-api/users/lookup/introduction) or from your Access Token (the numeric part is your user ID).
```bash cURL theme={null}
curl "https://api.x.com/2/users/123456789/muting?\
user.fields=created_at,username,verified&\
max_results=100" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get muted users with pagination
for page in client.users.get_muting(
"123456789",
user_fields=["created_at", "username", "verified"],
max_results=100
):
for user in page.data:
print(f"{user.username} - Muted")
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get muted users with pagination
const paginator = client.users.getMuting("123456789", {
userFields: ["created_at", "username", "verified"],
maxResults: 100,
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(`${user.username} - Muted`);
});
}
```
```json theme={null}
{
"data": [
{
"id": "2244994945",
"name": "X Developers",
"username": "XDevelopers",
"created_at": "2013-12-14T04:35:55.000Z",
"verified": true
}
],
"meta": {
"result_count": 1,
"next_token": "1710819323648428707"
}
}
```
***
## Include additional data
Use expansions to get related data like pinned Posts:
```bash cURL theme={null}
curl "https://api.x.com/2/users/123456789/muting?\
user.fields=created_at&\
expansions=pinned_tweet_id&\
tweet.fields=created_at" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
```python Python SDK theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")
# Get muted users with expansions
for page in client.users.get_muting(
"123456789",
user_fields=["created_at"],
expansions=["pinned_tweet_id"],
tweet_fields=["created_at"]
):
for user in page.data:
print(f"{user.username}")
# Pinned Posts are in page.includes.tweets
```
```javascript JavaScript SDK theme={null}
import { Client } from "@xdevplatform/xdk";
const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });
// Get muted users with expansions
const paginator = client.users.getMuting("123456789", {
userFields: ["created_at"],
expansions: ["pinned_tweet_id"],
tweetFields: ["created_at"],
});
for await (const page of paginator) {
page.data?.forEach((user) => {
console.log(user.username);
});
// Pinned Posts are in page.includes?.tweets
}
```
### Response with expansion
```json theme={null}
{
"data": [
{
"username": "XDevelopers",
"created_at": "2013-12-14T04:35:55.000Z",
"id": "2244994945",
"name": "X Developers",
"pinned_tweet_id": "1430984356139470849"
}
],
"includes": {
"tweets": [
{
"created_at": "2021-08-26T20:03:51.000Z",
"id": "1430984356139470849",
"text": "Help us build a better X Developer Platform!..."
}
]
},
"meta": {
"result_count": 1
}
}
```
***
## Paginate through results
The SDKs handle pagination automatically. For cURL, use the `next_token` from the response:
```bash theme={null}
curl "https://api.x.com/2/users/123456789/muting?\
max_results=100&\
pagination_token=1710819323648428707" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN"
```
***
## Next steps
Mute and unmute users
Full endpoint documentation
# Pin List
Source: https://docs.x.com/enterprise-api/users/pin-list
post /2/users/{id}/pinned_lists
Causes the authenticated user to pin a specific List by its ID.
# Repost Post
Source: https://docs.x.com/enterprise-api/users/repost-post
post /2/users/{id}/retweets
Causes the authenticated user to repost a specific Post by its ID.
# Search Users
Source: https://docs.x.com/enterprise-api/users/search-users
get /2/users/search
Retrieves a list of Users matching a search query.
# User Search
Source: https://docs.x.com/enterprise-api/users/search/introduction
Search X users by keyword with the Enterprise tier User search endpoint to find accounts by name, handle, bio terms, and other public profile fields.
The User Search endpoint lets you search for users by keyword. Find users by name, username, or content in their bio.
## Overview
Search by name, username, or bio
Find relevant accounts
***
## Endpoint
| Method | Endpoint | Description |
| :----- | :--------------------------------------------- | :--------------- |
| GET | [`/2/users/search`](/x-api/users/search-users) | Search for users |
***
## Example request
```bash theme={null}
curl "https://api.x.com/2/users/search?\
query=python%20developer&\
user.fields=description,verified,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
## Example response
```json theme={null}
{
"data": [
{
"id": "1234567890",
"name": "Python Developer",
"username": "pythondev",
"description": "Building cool things with Python",
"verified": false,
"public_metrics": {
"followers_count": 5000,
"following_count": 200,
"tweet_count": 1500
}
}
],
"meta": {
"result_count": 1
}
}
```
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* Your App's [keys and tokens](/resources/fundamentals/authentication)
Look up users by ID or username
Full endpoint documentation
# Unblock DMs
Source: https://docs.x.com/enterprise-api/users/unblock-dms
post /2/users/{id}/dm/unblock
Unblocks direct messages to or from a specific User by their ID for the authenticated user.
# Unfollow List
Source: https://docs.x.com/enterprise-api/users/unfollow-list
delete /2/users/{id}/followed_lists/{list_id}
Causes the authenticated user to unfollow a specific List by its ID.
# Unfollow User
Source: https://docs.x.com/enterprise-api/users/unfollow-user
delete /2/users/{source_user_id}/following/{target_user_id}
Causes the authenticated user to unfollow a specific user by their ID.
# Unlike Post
Source: https://docs.x.com/enterprise-api/users/unlike-post
delete /2/users/{id}/likes/{tweet_id}
Causes the authenticated user to Unlike a specific Post by its ID.
# Unmute User
Source: https://docs.x.com/enterprise-api/users/unmute-user
delete /2/users/{source_user_id}/muting/{target_user_id}
Causes the authenticated user to unmute a specific user by their ID.
# Unpin List
Source: https://docs.x.com/enterprise-api/users/unpin-list
delete /2/users/{id}/pinned_lists/{list_id}
Causes the authenticated user to unpin a specific List by its ID.
# Unrepost Post
Source: https://docs.x.com/enterprise-api/users/unrepost-post
delete /2/users/{id}/retweets/{source_tweet_id}
Causes the authenticated user to unrepost a specific Post by its ID.
# Create replay job for webhook
Source: https://docs.x.com/enterprise-api/webhooks/create-replay-job-for-webhook
post /2/webhooks/replay
Creates a replay job to retrieve events from up to the past 24 hours for all events delivered or attempted to be delivered to the webhook.
# Create stream link
Source: https://docs.x.com/enterprise-api/webhooks/create-stream-link
post /2/tweets/search/webhooks/{webhook_id}
Creates a link to deliver FilteredStream events to the given webhook.
# Create webhook
Source: https://docs.x.com/enterprise-api/webhooks/create-webhook
post /2/webhooks
Creates a new webhook configuration.
# Delete stream link
Source: https://docs.x.com/enterprise-api/webhooks/delete-stream-link
delete /2/tweets/search/webhooks/{webhook_id}
Deletes a link from FilteredStream events to the given webhook.
# Delete webhook
Source: https://docs.x.com/enterprise-api/webhooks/delete-webhook
delete /2/webhooks/{webhook_id}
Deletes an existing webhook configuration.
# Get stream links
Source: https://docs.x.com/enterprise-api/webhooks/get-stream-links
get /2/tweets/search/webhooks
Get a list of webhook links associated with a filtered stream ruleset.
# Get webhook
Source: https://docs.x.com/enterprise-api/webhooks/get-webhook
get /2/webhooks
Get a list of webhook configs associated with a client app.
# V2 Webhooks API
Source: https://docs.x.com/enterprise-api/webhooks/introduction
The V2 Webhooks API enables developers to receive real-time event notifications from X accounts. Reference for the Enterprise X API tier covering webhooks.
The V2 Webhooks API enables developers to receive real-time event notifications from X accounts via webhook-based JSON messages. These APIs allow you to register and manage webhooks, develop consumer applications to process events, and ensure secure communication through challenge-response checks (CRC) and signature headers.
## Overview
Receive events instantly as they occur
Data sent directly to your server — no polling
CRC validation and signature verification
Retry and recovery support
***
## Products that support webhooks
These are the products that currently support delivering events via webhook:
| Product | Description |
| :----------------------------------------------------------------- | :------------------------------------------------------ |
| [X Activity API (XAA)](/x-api/activity/introduction) | Receive real-time events for activity happening on X |
| [Account Activity API (AAA)](/x-api/account-activity/introduction) | Receive real-time events tied to specific user accounts |
| [Filtered Stream Webhooks](/x-api/webhooks/stream/introduction) | Receive filtered stream Posts via webhook delivery |
***
## How webhooks work
```mermaid actions={false} theme={null}
flowchart LR
A["X Event Occurs"] --> B["X Server"] --> C["Your Webhook URL"]
```
1. **Event occurs** — A user posts, sends a DM, gets followed, etc.
2. **X sends a POST request** — JSON event payload sent to your registered webhook URL
3. **You process the event** — Your server handles the event data
4. **Respond with 200 OK** — Return a 200 status to acknowledge receipt
***
## Webhook requirements
| Requirement | Description |
| :------------------------ | :--------------------------------------------------------------------------------------------------------------- |
| **HTTPS** | Webhook URL must use HTTPS |
| **Publicly accessible** | URL must be reachable from the internet |
| **No port specification** | The URL cannot include a port (e.g., `https://mydomain.com:5000/webhook` will not work) |
| **Fast response** | Respond within 10 seconds |
| **200 OK** | Return 200 status to acknowledge receipt |
| **CRC support** | Must respond to Challenge-Response Check GET requests ([learn more](/x-api/webhooks/quickstart#2-the-crc-check)) |
***
## Endpoints
| Method | Endpoint | Description |
| :----- | :-------------------------------------------------------------------- | :---------------------------------------- |
| POST | [`/2/webhooks`](/x-api/webhooks/create-webhook) | Register a new webhook |
| GET | [`/2/webhooks`](/x-api/webhooks/get-webhook) | List registered webhooks |
| DELETE | [`/2/webhooks/:webhook_id`](/x-api/webhooks/delete-webhook) | Delete a webhook |
| POST | [`/2/webhooks/replay`](/x-api/webhooks/create-replay-job-for-webhook) | Create a replay job for webhook |
| PUT | [`/2/webhooks/:webhook_id`](/x-api/webhooks/validate-webhook) | Trigger CRC check and re-enable a webhook |
All endpoints require **OAuth2 App Only Bearer Token** authentication.
***
## Security
X's webhook-based APIs provide two methods for confirming the security of your webhook server:
1. **Challenge-Response Check (CRC)** — X sends periodic GET requests to your webhook URL. You respond with an HMAC-SHA256 hash to prove you control the endpoint. CRC checks happen on initial registration, hourly, and on manual re-validation.
2. **Signature verification** — Each POST request from X includes an `x-twitter-webhooks-signature` header. You can verify this signature to confirm X is the source of incoming events.
Step-by-step CRC setup, code examples, and signature verification
***
## Webhook validation
A CRC check is sent to your webhook in the following cases:
* Immediately upon creation
* On an explicit PUT request (`PUT /2/webhooks/{id}`)
* Periodically every 30 minutes, but only if the webhook has not been successfully validated in the past 24 hours
A webhook is marked as **invalid** when:
* It returns an invalid response to a CRC check
* Returns a 2XX status code but the `response_token` is incorrect
* Returns a 3XX status code
* Results in an SSL exception
* It experiences persistent transient errors such that it has not successfully validated for more than 28 hours (includes a 4-hour grace period for transient issues)
* The following responses are treated as transient errors:
* 4XX status code
* 5XX status code
* Request timeout
* Channel closed
You can check the valid/invalid status of a webhook using the `GET /2/webhooks` endpoint or via the toolbox in the Developer Console.
***
## Getting started
**Prerequisites**
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info)
* A [Project and App](/resources/fundamentals/developer-apps) in the Developer Console
* A publicly accessible HTTPS endpoint
* Your app's **consumer secret** (API secret key) for CRC validation
Set up your webhook end-to-end
Receive filtered Posts via webhook
Receive account events via webhook
Working code examples
# Quickstart
Source: https://docs.x.com/enterprise-api/webhooks/quickstart
This guide walks you through setting up a webhook consumer app, implementing the. Reference for the Enterprise X API tier covering webhooks.
This guide walks you through setting up a webhook consumer app, implementing the Challenge-Response Check (CRC), securing incoming events, and registering your webhook with X.
## 1. Develop a webhook consumer app
To register a webhook with your X app, you need to develop, deploy, and host a web app that receives X webhook events and responds to CRC security requests.
### URL requirements
Create a web app with a publicly accessible HTTPS URL that will act as the webhook endpoint to receive events:
* The URI **path** is up to you. These examples are all valid:
* `https://mydomain.com/service/listen`
* `https://mydomain.com/webhook/twitter`
* The URL **cannot** include a port specification (e.g., `https://mydomain.com:5000/webhook` will **not** work)
### What your app needs to handle
Your webhook endpoint must handle two types of HTTP requests:
| Request type | Purpose |
| :----------- | :----------------------------------------------------------------------- |
| **GET** | [CRC validation](#2-the-crc-check) — X verifies you control the endpoint |
| **POST** | Event delivery — X sends JSON event payloads |
***
## 2. The CRC check
The Challenge-Response Check (CRC) is how X validates that the callback URL you provided is valid and that **you control it**. Your web app must correctly respond to CRC requests to register and maintain your webhook.
### When CRC is triggered
| Trigger | Description |
| :----------------------- | :------------------------------------------------ |
| **Initial registration** | When you call `POST /2/webhooks` |
| **Hourly validation** | X automatically validates your webhook every hour |
| **Manual re-validation** | When you call `PUT /2/webhooks/:webhook_id` |
If your webhook fails a CRC check, it will be marked as `invalid` and will **stop receiving events** until it passes again.
### How the CRC works
When X sends a CRC, it makes a **GET request** to your webhook URL with a `crc_token` query parameter:
```
GET https://your-webhook-url.com/webhook?crc_token=challenge_string
```
Your application must respond with a JSON body containing a `response_token`:
```json theme={null}
{
"response_token": "sha256="
}
```
### How to build the CRC response
1. Use the `crc_token` value from the query parameter as the **message**
2. Use your app's **consumer secret** (API secret key) as the **key**
3. Create an **HMAC SHA-256** hash
4. **Base64 encode** the result
5. Prepend `sha256=` to the encoded string
**Important:** Your web app must use your app's **consumer secret** (API secret key) for the CRC encryption — not your bearer token or access token.
### Example: Python
```python theme={null}
import hmac
import hashlib
import base64
def handle_crc(crc_token, consumer_secret):
"""
Respond to a Twitter CRC check.
Args:
crc_token: The crc_token query parameter from the GET request
consumer_secret: Your app's consumer secret (API secret key)
Returns:
dict with the response_token
"""
sha256_hash = hmac.new(
consumer_secret.encode('utf-8'),
crc_token.encode('utf-8'),
hashlib.sha256
).digest()
return {
"response_token": "sha256=" + base64.b64encode(sha256_hash).decode('utf-8')
}
```
### Example: Node.js
```javascript theme={null}
const crypto = require('crypto');
function handleCrc(crcToken, consumerSecret) {
const hmac = crypto
.createHmac('sha256', consumerSecret)
.update(crcToken)
.digest('base64');
return {
response_token: `sha256=${hmac}`
};
}
```
### Example: Flask (full endpoint)
This example shows a complete webhook endpoint that handles both CRC validation (GET) and event delivery (POST):
```python theme={null}
from flask import Flask, request, jsonify
import hmac
import hashlib
import base64
app = Flask(__name__)
CONSUMER_SECRET = "your_consumer_secret_here"
@app.route("/webhook", methods=["GET", "POST"])
def webhook():
if request.method == "GET":
# Handle CRC check
crc_token = request.args.get("crc_token")
if crc_token:
sha256_hash = hmac.new(
CONSUMER_SECRET.encode("utf-8"),
crc_token.encode("utf-8"),
hashlib.sha256,
).digest()
response_token = "sha256=" + base64.b64encode(sha256_hash).decode("utf-8")
return jsonify({"response_token": response_token}), 200
return "Missing crc_token", 400
elif request.method == "POST":
# Handle incoming webhook events
event = request.get_json()
print("Received event:", event)
return "", 200
```
***
## 3. Securing webhooks
X's webhook-based APIs provide two methods for confirming the security of your webhook server:
### Challenge-Response Check (CRC)
The CRC enables X to confirm ownership of the web app receiving webhook events. See [Step 2](#2-the-crc-check) above for full implementation details.
### Signature verification
Each POST request from X includes an `x-twitter-webhooks-signature` header that enables you to confirm that X is the source of the incoming webhook.
To verify the signature:
1. Get the `x-twitter-webhooks-signature` header value from the incoming request
2. Create an HMAC SHA-256 hash using your **consumer secret** as the key and the **raw request body** as the message
3. Base64 encode the hash and prepend `sha256=`
4. Compare your computed value to the header value — they should match
```python theme={null}
import hmac
import hashlib
import base64
def verify_signature(payload, signature_header, consumer_secret):
"""
Verify that a webhook POST request actually came from X.
Args:
payload: The raw request body (bytes)
signature_header: The x-twitter-webhooks-signature header value
consumer_secret: Your app's consumer secret
Returns:
True if the signature is valid
"""
expected = "sha256=" + base64.b64encode(
hmac.new(
consumer_secret.encode("utf-8"),
payload,
hashlib.sha256
).digest()
).decode("utf-8")
return hmac.compare_digest(expected, signature_header)
```
***
## 4. Register your webhook
Once your app can handle CRC checks, register your webhook URL by making a `POST /2/webhooks` request. When you make this request, X will immediately send a CRC request to your web app to verify ownership.
All webhook management endpoints require **OAuth2 App Only Bearer Token** authentication.
### Create a webhook
**`POST /2/webhooks`** — [API Reference](/x-api/webhooks/create-webhook)
```bash theme={null}
curl --request POST \
--url 'https://api.x.com/2/webhooks' \
--header 'Authorization: Bearer $BEARER_TOKEN' \
--header 'Content-Type: application/json' \
--data '{
"url": "https://yourdomain.com/webhooks/twitter"
}'
```
**Success response (200 OK):**
A successful response indicates the webhook was created and the initial CRC check passed.
```json theme={null}
{
"data": {
"id": "1234567890",
"url": "https://yourdomain.com/webhooks/twitter",
"valid": true,
"created_at": "2025-01-15T12:00:00.000Z"
}
}
```
When a webhook is successfully registered, the response includes a **webhook ID**. This ID is needed when making requests to products that support webhooks (e.g., linking to Filtered Stream, or creating subscriptions for Account Activity).
**Common failure reasons:**
| Reason | Description |
| :--------------------- | :--------------------------------------------------------------------------------------------- |
| `CrcValidationFailed` | Your callback URL did not respond correctly to the CRC check (e.g., timed out, wrong response) |
| `UrlValidationFailed` | The callback URL does not meet requirements (e.g., not `https`, invalid format) |
| `DuplicateUrlFailed` | A webhook is already registered by your application for this URL |
| `WebhookLimitExceeded` | Your application has reached the maximum number of allowed webhooks |
### View webhooks
**`GET /2/webhooks`** — [API Reference](/x-api/webhooks/get-webhook)
Retrieve all webhook configurations associated with your application.
```bash theme={null}
curl --request GET \
--url 'https://api.x.com/2/webhooks' \
--header 'Authorization: Bearer $BEARER_TOKEN'
```
**Response (with one webhook):**
```json theme={null}
{
"data": [
{
"created_at": "2025-01-15T12:00:00.000Z",
"id": "1234567890",
"url": "https://yourdomain.com/webhooks/twitter",
"valid": true
}
],
"meta": {
"result_count": 1
}
}
```
**Response (with no webhooks):**
```json theme={null}
{
"data": [],
"meta": {
"result_count": 0
}
}
```
### Delete a webhook
**`DELETE /2/webhooks/:webhook_id`** — [API Reference](/x-api/webhooks/delete-webhook)
Delete a webhook using its `webhook_id` (obtained from the create or list response).
```bash theme={null}
curl --request DELETE \
--url 'https://api.x.com/2/webhooks/1234567890' \
--header 'Authorization: Bearer $BEARER_TOKEN'
```
**Response:**
```json theme={null}
{
"data": {
"deleted": true
}
}
```
| Failure reason | Description |
| :----------------- | :------------------------------------------------------------------------- |
| `WebhookIdInvalid` | The provided `webhook_id` was not found or is not associated with your app |
### Validate and re-enable a webhook
**`PUT /2/webhooks/:webhook_id`** — [API Reference](/x-api/webhooks/validate-webhook)
Triggers a CRC check for the given webhook. If the check succeeds, the webhook is re-enabled with `valid: true`.
```bash theme={null}
curl --request PUT \
--url 'https://api.x.com/2/webhooks/1234567890' \
--header 'Authorization: Bearer $BEARER_TOKEN'
```
**Response:**
A 200 OK response indicates the CRC check was initiated. The `valid` field reflects the status after the check attempt. You can verify the current status using `GET /2/webhooks`.
```json theme={null}
{
"data": {
"valid": true
}
}
```
| Failure reason | Description |
| :-------------------- | :------------------------------------------------------------------------- |
| `WebhookIdInvalid` | The provided `webhook_id` was not found or is not associated with your app |
| `CrcValidationFailed` | The callback URL did not respond correctly to the CRC check |
***
## Testing with xurl
For testing purposes, the `xurl` tool supports temporary webhooks. Install the latest version of the [`xurl` project](https://github.com/xdevplatform/xurl) from GitHub, configure your authorization, then run:
```bash theme={null}
xurl webhook start
```
This will generate a temporary public webhook URL, automatically handle all CRC checks, and log any incoming subscription events. It's a great way to verify your setup before deploying. Example output:
```
Starting webhook server with ngrok...
Enter your ngrok authtoken (leave empty to try NGROK_AUTHTOKEN env var):
Attempting to use NGROK_AUTHTOKEN environment variable for ngrok authentication.
Configuring ngrok to forward to local port: 8080
Ngrok tunnel established!
Forwarding URL: https://.ngrok-free.app -> localhost:8080
Use this URL for your X API webhook registration: https://.ngrok-free.app/webhook
Starting local HTTP server to handle requests from ngrok tunnel...
```
***
## Important notes
* **All incoming Direct Messages** will be delivered via webhooks. DMs sent via [POST /2/dm\_conversations/with/:participant\_id/messages](/x-api/direct-messages/send-a-new-message-to-a-user) will also be delivered, so your app can track DMs sent from other clients.
* If you have **more than one web app** sharing the same webhook URL and the same user mapped to each app, the same event will be sent to your webhook **multiple times** (once per web app).
* In some cases, your webhook may receive **duplicate events**. Your webhook app should be tolerant of this and **deduplicate by event ID**.
* X sends events as **POST requests** with JSON payloads. See the [Account Activity data object structure](/x-api/account-activity/introduction#account-activity-data-object-structure) for example payloads.
***
## Sample apps
| App | Description |
| :------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------- |
| [Simple webhook server](https://github.com/m-rosinsky/XWebhookTest/blob/main/app.py) | A single Python script that shows how to respond to the CRC check and accept POST events |
| [Account Activity API dashboard](https://github.com/xdevplatform/account-activity-dashboard-enterprise/tree/master) | A web app written with [bun.sh](https://bun.sh) that lets you manage webhooks, subscriptions, and receive live events |
| [xurl testing tool](https://github.com/xdevplatform/xurl) | CLI tool for temporary webhook testing — auto-handles CRC checks and logs events |
***
## Next steps
Receive filtered Posts via webhook
Receive account events via webhook
# Filtered Stream Webhooks API
Source: https://docs.x.com/enterprise-api/webhooks/stream/introduction
The filtered stream endpoint group enables developers to filter a stream of public Posts. Reference for the Enterprise X API tier covering stream.
## Overview
The filtered stream endpoint group enables developers to filter a stream of public Posts. This endpoint group’s functionality includes multiple endpoints that enable you to create and manage rules, and apply those rules to filter a stream of Posts that will return matching public Posts. This endpoint group allows users to listen for specific topics and events, monitor the conversation around competitions, understand how trends develop, and much more.
Developers can use the REST [rules endpoint](/x-api/stream/get-stream-rules) to add and remove rules to filter for Posts matching a defined criteria. These [rules](/x-api/posts/filtered-stream/integrate/build-a-rule) can be created with operators that match on Post attributes such as message keywords, hashtags, and URLs. Operators and rule clauses can be combined with boolean logic and parentheses to help refine the filter’s matching behavior.
Once you've added a set of rules, you can register your webhook where X will start to deliver [Post objects](/x-api/fundamentals/data-dictionary/reference#tweet) in JSON format. You will only receive content matching your rules to your webhook.
This endpoint supports edited Posts. Your webhook will receive edited Posts that match one or more of your filters, along with its edit history, including an array of Post IDs. For Posts with no edit history, this array will hold a single ID. For Posts that have been edited, this array contains multiple IDs, arranged in ascending order reflecting the order of edits, with the most recent version in the last position of the array. To learn more about how Post edits work, see the [Posts edits fundamentals](/x-api/fundamentals/edit-posts) page.
**Note:** This endpoint group is similar to the [v2 filtered stream endpoint](/x-api/posts/filtered-stream/introduction) for setting up your rules. The only difference is the delivery mechanisms for the Posts that match your rules.
* In case of v2 filtered stream endpoint, you have to establish a persistent connection and listen for Posts matching your rules.
* In case of this filtered stream webhook endpoint, you register your webhook, and X delivers Posts matching your rules to your webhook.
This eliminates the need for handling disconnects stemming from client drops or server-side drops from normal restarts to our service. Since we will likely be delivering hundreds of events/second, it is necessary for your
webhook server to be able to handle these simultaneous connection attempts.
This endpoint is currently available to Enterprise developers and supports the following configuration:
* 25,000+ rules per project
* Can use all operators when building your rule
* Can build rules up to 2048 characters in length
* Apply [here](https://developer.x.com/en/products/x-api/enterprise/enterprise-api-interest-form) for Enterprise access
The returned Posts from filtered stream count towards the monthly [Post cap](/x-api/fundamentals/post-cap).
**Account setup**
To access these endpoints, you will need:
* An approved [developer account](https://developer.x.com/en/portal/petition/essential/basic-info).
* To authenticate using the keys and tokens from a [developer App](/resources/fundamentals/developer-apps) that is located within a [Project](/resources/fundamentals/developer-apps).
Learn more about getting access to the X API v2 endpoints in our [getting started guide](/x-api/getting-started/getting-access).
# Quickstart
Source: https://docs.x.com/enterprise-api/webhooks/stream/quickstart
The v2 filtered stream webhooks API is similar to the [v2 filtered stream. Reference for the Enterprise X API tier covering stream.
## Getting started with the filtered stream webhooks API
The v2 filtered stream webhooks API is similar to the [v2 filtered stream endpoint](/x-api/posts/filtered-stream/introduction) in terms of setting up the rules to filter on. The difference lies in the delivery mechanism for the Posts that match your rules.
* In case of v2 filtered stream endpoint, you have to establish a persistent connection and listen for Posts matching your rules.
* In case of this filtered stream webhook endpoint, you register your webhook, and X delivers Posts matching your rules to your webhook.
This guide explains how to filter for, and receive posts using the filtered stream webhooks endpoints. There are 3 steps involved
1. Setting up your filtered stream rules
2. Creating your webhook
3. Linking your Filtered Stream instance to your webhook
Once you have linked your Filtered Stream instance to your webhook, X will send Posts that match your rules to your webhooks.
### Setting up your filtered stream rules
Filtered stream rules are made up of one or many operators that are combined using boolean logic and parentheses to help define which Posts will be delivered to your webhooks. The filtered stream webhooks API uses the same set of endpoints as the [v2 filtered stream endpoint](/x-api/posts/filtered-stream/introduction) to create and manage rules. Check out [this detailed guide](/x-api/posts/filtered-stream/integrate/build-a-rule) that demonstrates how you can build filters.
### Creating your webhook
Create a webhook to receive events by registering a publicly accessible HTTPS URL with the X API. Webhooks must handle GET requests for CRC validation and POST requests for event payloads. Follow the [Webhooks Introduction documentation](/x-api/webhooks/introduction) for detailed steps on creating and managing webhooks.
**Note:** If you already use webhooks for [Account Activity API (AAA)](/x-api/account-activity/introduction), the webhooks set up for that are exactly the same here. In fact, you can use the same webhook endpoint you use for AAA for this API, if you have the bandwidth and can separate the events.
### Linking your Filtered Stream instance to your webhook
Once your rules are set and the webhook is created, link the webhook to your Filtered Stream instance. This routes matched post events to your webhook URL.
Use the endpoint: `POST /2/tweets/search/webhooks/:webhook_id `
You can include query parameters identical to those used in the streaming endpoint `/2/tweets/search/stream` such as expansions, fields, and media options. This customizes the
data included in event payloads.
**Example:**
```bash theme={null}
curl --request POST \
--url
'https://api.x.com/2/tweets/search/webhooks/123456789012345678?ex
pansions=author_id&user.fields=username,name,id' \
--header 'Authorization: Bearer $BEARER_TOKEN'
```
Successful response example:
```json theme={null}
{
"data": {
"provisioned": true
}
}
```
**Tip:** You can link multiple webhooks to the same stream for redundancy or to receive different field sets. Each linkage can specify unique parameters.
Once you have your Filtered Stream instance to your webhook, you will start to receive Posts matching your rules like shown below:
```json theme={null}
{
"data": {
"id": "1346889436626259968",
"text": "Learn how to use the user Post timeline and user mention timeline endpoints in the X API v2 to explore Post… https://t.co/56a0vZUx7i",
"created_at": "2021-01-06T18:40:40.000Z",
"author_id": "2244994945"
},
"includes": {
"users": [
{
"id": "2244994945",
"name": "Developers",
"username": "Xdevelopers",
"created_at": "2013-12-14T04:35:55Z",
"protected": false
}
]
},
"matching_rules": [
{
"id": "120897978112909812",
"tag": "api-posts"
}
]
}
```
### Retrieving webhooks linked to Filtered Stream
Retrieve a list of all webhooks currently linked to your Filtered Stream:
```bash theme={null}
GET /2/tweets/search/stream/webhooks
```
Example Response:
```json theme={null}
{
"data": {
"links": [
{
"application_id": "29893711",
"business_user_id": "1877374016438091776",
"fields": [
"user.fields=username",
"name",
"id",
"expansions=author_id"
],
"instance_id": "1877375130462289920",
"webhook_id": "1952390923729424384"
}
]
}
}
```
### Unlinking your webhook from Filtered Stream
To stop receiving events on a specific webhook, unlink it using:
```bash theme={null}
DELETE /2/tweets/search/webhooks/:webhook_id
```
The response will be as follows:
```json theme={null}
{
"data": {
"deleted": true
}
}
```
# Validate webhook
Source: https://docs.x.com/enterprise-api/webhooks/validate-webhook
put /2/webhooks/{webhook_id}
Triggers a CRC check for a given webhook.
# What to Build
Source: https://docs.x.com/enterprise-api/what-to-build
Enterprise project ideas for the X API, including brand monitoring, crisis response, market intelligence, social listening, and academic research.
The X API opens up possibilities across moderation, analytics, community building, and more. Here are ideas to inspire your next project.
***
## Build for safety & moderation
Help create healthier conversations on X.
Build tools to help users manage replies, filter content, and protect their experience.
Detect and flag abusive content, provide bulk blocking tools.
**Relevant endpoints:**
* [Blocks](/x-api/users/blocks/introduction) — Block and unblock users
* [Mutes](/x-api/users/mutes/introduction) — Mute accounts and keywords
* [Hide replies](/x-api/posts/hide-replies/introduction) — Hide unwanted replies
* [Manage posts](/x-api/posts/manage-tweets/introduction) — Control reply settings
***
## Build for creators
Help people express themselves and grow their audience.
Schedule posts, threads, and content calendars.
Sync content across platforms and formats.
Help users compose and publish long-form threads.
Create helpful bots that add value to the conversation.
**Relevant endpoints:**
* [Manage posts](/x-api/posts/manage-tweets/introduction) — Create and delete posts
* [Media upload](/x-api/media/quickstart/media-upload-chunked) — Upload images and videos
* [Spaces](/x-api/spaces/lookup/introduction) — Discover audio conversations
***
## Build for analytics
Help users understand their impact and audience.
Visualize engagement metrics, growth trends, and reach.
Analyze followers, engagement patterns, and demographics.
Track hashtags, topics, and conversation volume.
Compare accounts, benchmark performance.
**Relevant endpoints:**
* [Metrics](/x-api/fundamentals/metrics) — Engagement and performance data
* [Search posts](/x-api/posts/search/introduction) — Historical and recent search
* [Post counts](/x-api/posts/counts/introduction) — Volume analytics
* [Annotations](/x-api/fundamentals/post-annotations) — Topic classification
***
## Build for communities
Help people connect and organize around shared interests.
Moderation, member management, and engagement tools.
Organize Spaces, live events, and group activities.
Aggregate and curate content by topic or interest.
Build tools for specific languages and regions.
**Relevant endpoints:**
* [Lists](/x-api/lists/list-lookup/introduction) — Curated account lists
* [Spaces](/x-api/spaces/lookup/introduction) — Audio conversations
* [Follows](/x-api/users/follows/introduction) — Relationship management
***
## Build for research
Analyze public conversations and extract insights.
Study public discourse, information spread, and trends.
Source stories, verify information, track breaking news.
Monitor brand sentiment, industry trends, and competitors.
Train models, analyze networks, study behavior patterns.
**Relevant endpoints:**
* [Full-archive search](/x-api/posts/search/introduction) — Search posts back to 2006
* [Filtered stream](/x-api/posts/filtered-stream/introduction) — Near real-time matching posts
* [Post annotations](/x-api/fundamentals/post-annotations) — Entity recognition
* [Conversation ID](/x-api/fundamentals/conversation-id) — Thread reconstruction
***
## Build for good
Use the API to make a positive impact.
Monitor emergencies, coordinate aid, spread awareness.
Build tools that make X more accessible to everyone.
Create learning tools, teaching resources, and tutorials.
Help people stay informed and participate in democracy.
***
## Getting started
Ready to build? Here's your path forward:
[Sign up for a developer account](/x-api/getting-started/getting-access) and create an app.
[Make your first request](/x-api/getting-started/make-your-first-request) and explore the API.
Pick an [SDK or library](/tools-and-libraries) for your language.
Start small, iterate, and share what you've built!
***
## Share your work
Built something with the X API? We'd love to see it:
* Share in the [Developer Forum](https://devcommunity.x.com)
* Tag [@XDevelopers](https://x.com/XDevelopers) on X
* Submit to our [Success Stories](/success-stories)
# Enterprise data customers
Source: https://docs.x.com/enterprise/customer-directory
Directory of enterprise customers using the X API for social listening, research, financial analysis, public safety, brand monitoring, and other use cases.
## Discover companies that use X data to help power innovation
Our enterprise data customers receive commercial-level access to APIs and dedicated account and developer support. Apply for enterprise API access to get the highest level of access and reliability.
[Apply for enterprise access →](/forms/enterprise-api-interest)
## X Official Partners
Work with a trusted X Official Partner to expand what's possible for your business. Each Official Partner has been selected for the program after an extensive evaluation, and represents excellence, value, and trust.
[Check our partners →](https://partners.x.com/en)
## Enterprise customers listing
# X Official Partner
Source: https://docs.x.com/enterprise/partner-directory
Directory of X Official Partners offering tools and services built on the X API, including analytics, content moderation, ad management, and more.
## Build your business with X Official Partners
###### Tap into the public conversation on X and turn insights into action with solutions from our partners.
## Work with a trusted X Official Partner to expand what's possible for your business
Our partners are vetted for excellence and can provide technology to help you:
* Understand consumer trends and preferences
* Collect and analyze product and service feedback
* Engage with customers and resolve issues
* Be alerted to breaking news and events
* Create, publish, and analyze content across social channels
* And more!
## Discover the right Official Partner for your business
### Official Partners represent excellence, value, and trust
Each Official Partner has been selected for the program after an extensive evaluation. Our partners are continuously reviewed by X, as this invitation-only program holds its members to the highest performance standards, in order to deliver great experiences for brands.
## See our partners' impressive work
# Registro de cambios
Source: https://docs.x.com/es/changelog
Notas de versión y novedades de la X API v2, las APIs Enterprise, la Ads API, los SDK, streaming, webhooks y la plataforma para desarrolladores.
Para suscribirte a las actualizaciones, [**"Activa las notificaciones"**](https://help.x.com/en/managing-your-account/notifications-on-mobile-devices#:~:text=In%20the%20top%20menu,%20you,you%20would%20like%20to%20receive) para [**@API**](https://x.com/api). También puedes seguir este registro de cambios en tu lector de feeds mediante el [**feed RSS**](https://docs.x.com/changelog/rss.xml).
### Endpoints de borrador y publicación de Articles
Hoy agregamos [nuevos endpoints](/x-api/articles/introduction) para crear borradores y publicar Articles a través de la X API.
### Eventos de creación y eliminación de Posts para la X Activity API
Hoy agregamos los eventos `post.create` y `post.delete` a la [X Activity API](https://docs.x.com/x-api/activity/introduction). Ahora puedes suscribirte por ID de usuario para recibir notificaciones en tiempo real cuando un usuario crea o elimina un Post.
Para actividad básica de Posts por usuario, usa XAA. Para filtrado avanzado por palabras clave y el conjunto completo de operadores de Filtered Stream, sigue usando [Filtered Stream](/x-api/posts/filtered-stream/introduction).
### Campo `paid_partnership` de Post
Se agregó soporte para el campo `paid_partnership` en los Posts.
* Al crear un Post mediante `POST /2/tweets`, establece `"paid_partnership": true` para indicar que el Post es una colaboración pagada (es decir, el autor está divulgando que contiene promoción pagada). El Post se etiquetará como promoción pagada.
* Al leer Posts, solicita `tweet.fields=paid_partnership` para obtener el valor (`true` si el autor ha divulgado que el Post contiene promoción pagada).
### Los endpoints de búsqueda migran al nuevo índice de búsqueda
Hoy migramos los endpoints de búsqueda de la X API v2 (`/2/tweets/search/recent`, `/2/tweets/search/all`, `/2/tweets/counts/recent`, `/2/tweets/counts/all`) al nuevo índice de búsqueda de la plataforma central de X. Esto aporta mejoras de rendimiento importantes, una reducción drástica de errores 503 y tres nuevos operadores de precisión: `min\_likes:`, `min\_replies:` y `min\_reposts:`. Nota: los reposts ya no se devuelven en los resultados de búsqueda basados en palabras clave (el Filtered Stream no cambia). Más información [aquí](https://devcommunity.x.com/t/important-update-x-api-search-endpoints-migrating-to-new-search-index/264595).
### Actualización de precios de la X API: las "Owned Reads" ahora cuestan \$0.001
A partir del 20 de abril de 2026, introdujimos los nuevos precios de "Owned Reads" a \*\*$0.001 por recurso** (1.000 por $1) para los endpoints elegibles cuando accedes a tus propios datos: `GET /2/users/{id}/bookmarks`, `/blocking`, `/muting`, `/pinned_lists`, `/tweets`, `/mentions`, `/liked_tweets`, `/followers`, `/following`, `/owned_lists`, `/followed_lists` y `/list_memberships`. También actualizamos las escrituras: `POST /2/tweets` ahora cuesta $0.015 por publicación, y las publicaciones que contienen una URL cuestan $0.20 por publicación (las respuestas invocadas siguen costando \$0.01). Las acciones de seguir, dar like y citar publicaciones a través de la API se han eliminado de todos los niveles de autoservicio. Más información [aquí](https://devcommunity.x.com/t/x-api-pricing-update-owned-reads-now-0-001-other-changes-effective-april-20-2026/263025).
### Discontinuación del endpoint Replay de Account Activity
Hoy anunciamos la discontinuación de `POST /2/account_activity/replay/webhooks/{webhook_id}/subscriptions/all`, vigente el 25 de marzo de 2026 a las 12:00 p. m. ET. Usa en su lugar el nuevo endpoint consolidado `POST /2/webhooks/replay`, que ofrece la misma funcionalidad. Más información [aquí](https://devcommunity.x.com/t/deprecation-of-account-activity-replay-endpoint/260354).
### Filtro de dirección para las suscripciones de la X Activity API
Hoy añadimos un filtro `direction` opcional a las suscripciones de la X Activity API. Los suscriptores ahora pueden acotar los eventos de DM y de chat a `sent`, `received` o ambos, reduciendo el ruido cuando solo se necesitan eventos salientes o entrantes.
### Actualizaciones del formato de los tipos de evento en la X Activity API
Hoy anunciamos cambios en la nomenclatura de los tipos de evento en la X Activity API, vigentes a partir del 18 de marzo de 2026. Los tipos de evento en PascalCase (por ejemplo, `ProfileBioUpdate`) se están discontinuando en favor de un formato en minúsculas separado por puntos (por ejemplo, `profile.update.bio`). Actualiza cualquier filtrado, sentencias switch o lógica de deserialización que dependa de los valores antiguos. Más información [aquí](https://devcommunity.x.com/t/updates-to-event-types-format-in-the-x-activity-api/259765).
### Eventos de mensajes directos heredados en la X Activity API
Hoy añadimos los eventos de DM heredados (`dm.received`, `dm.sent`, `dm.read`, `dm.indicate_typing`) a la [X Activity API](https://docs.x.com/x-api/activity/introduction). Esto traslada la entrega de eventos de DM desde la Account Activity API a la canalización de XAA, con menor latencia.
### Combate al spam generado por LLM
Hoy realizamos cambios para reducir las respuestas automatizadas y de baja calidad en X. Las respuestas programáticas mediante `POST /2/tweets` solo se permiten cuando el autor de la publicación original ha "invocado" al respondedor (mencionándolo con @ o citando una de sus publicaciones). Se aplican restricciones adicionales para mencionar con @ o citar usuarios de forma programática. Estos cambios afectan únicamente a los niveles de autoservicio: el acceso Enterprise no se ve afectado. Más información [aquí](https://devcommunity.x.com/t/x-api-v2-update-addressing-llm-generated-spam/257909).
### Lanzamiento del modelo de precios Pay-Per-Use de la X API
Hoy lanzamos oficialmente los precios **Pay-Per-Use de la X API**: un modelo flexible basado en créditos, diseñado para desarrolladores independientes, startups y aficionados. Lo más destacado:
* Una nueva Developer Console en [console.x.com](https://console.x.com)
* El [XDK (X Developer Kit)](https://docs.x.com/xdks/overview) con SDKs propios de Python y TypeScript
* Un [Playground](https://github.com/xdevplatform/playground) interactivo para realizar pruebas
* Un [servidor MCP](https://github.com/xdevplatform/xmcp) para modelos de IA
* Gana hasta un **20% en créditos de la API de xAI/Grok** por cada dólar gastado en la X API
Las Public Utility Apps siguen recibiendo acceso escalado gratuito. Los usuarios del nivel Legacy Free recientemente activos reciben un cupón único de \$10. Los planes Basic y Pro siguen disponibles, y los suscriptores actuales pueden optar por Pay-Per-Use. Más información [aquí](https://devcommunity.x.com/t/announcing-the-launch-of-x-api-pay-per-use-pricing/256476).
### Eventos de Spaces en la X Activity API
Hoy añadimos eventos del ciclo de vida de Spaces (`spaces.start`, `spaces.end`) a la [X Activity API](https://docs.x.com/x-api/activity/introduction). Suscríbete por ID de usuario para recibir notificaciones en tiempo real cuando un Space comienza o termina.
### Discontinuación de operadores basados en conteo
Hoy discontinuamos los operadores `min\_likes`, `min\_replies` y `min\_reposts` en `/2/tweets/search/recent` y `/2/tweets/search/all`. Este cambio no afecta a los operadores equivalentes del Filtered Stream. Estamos evaluando la mejor forma de habilitarlos nuevamente en el futuro. Más información [aquí](https://devcommunity.x.com/t/deprecating-count-based-operators-in-the-x-api/254933).
### Compatibilidad con OAuth 2.0 añadida a la Account Activity API v2
Hoy añadimos compatibilidad completa con OAuth 2.0 a la [Account Activity API v2](https://docs.x.com/x-api/account-activity/introduction). Los desarrolladores ahora pueden crear suscripciones usando OAuth 2.0 con scopes granulares (por ejemplo, `follow.read`) en lugar del modelo todo-o-nada de permisos de OAuth 1.0a. Las integraciones existentes basadas en OAuth 1.0a siguen funcionando sin interrupciones; cuando están presentes, los permisos de OAuth 1.0a sustituyen por completo a los scopes de OAuth 2.0. Más información [aquí](https://devcommunity.x.com/t/announcement-oauth2-0-support-added-to-account-activity-api-v2/254633).
### Presentamos el X API Playground
Hoy presentamos el [X API Playground](https://github.com/xdevplatform/playground): un servidor local autohospedado que emula los endpoints de la X API v2. Desarrolla y prueba integraciones sin realizar llamadas reales a la API ni alcanzar los límites de velocidad. Incluye datos simulados realistas, persistencia de estado, validación con OpenAPI, simulación de límites de velocidad y una interfaz web. Instálalo con `go install github.com/xdevplatform/playground/cmd/playground@latest`. Más información [aquí](https://devcommunity.x.com/t/introducing-x-api-playground-local-development-tool-for-x-api-v2/253442).
### Lanzamiento de los endpoints de News
Hoy lanzamos los nuevos [endpoints de News](https://docs.x.com/x-api/news/introduction) en la X API v2:
* `GET /2/news/search`: devuelve historias de noticias en tendencia que coinciden con una consulta de búsqueda
* `GET /2/news/{id}`: busca una historia de noticias específica por ID
Ambos endpoints admiten `news.fields` para seleccionar campos como `name`, `summary`, `contexts`, `cluster\_posts\_results` y `last\_updated\_at\_ms`. Más información [aquí](https://devcommunity.x.com/t/announcing-the-news-endpoints-in-the-x-api-v2/251833).
### Lanzamiento de los XDK de Python y TypeScript
Hoy lanzamos los XDK (X Developer Kits) oficiales de primera mano de [Python](https://docs.x.com/xdks/python/overview) y [TypeScript](https://docs.x.com/xdks/typescript/overview) para la X API v2. Los XDK gestionan la autenticación (Bearer Token, OAuth 2.0 PKCE, OAuth 1.0a), la paginación automática, el streaming en tiempo real con manejo de reconexiones y una cobertura completa de todos los endpoints de v2. Instálalos con `pip install xdk` o `npm install @xdevplatform/xdk`. Más información [aquí](https://devcommunity.x.com/t/announcing-the-python-and-typescript-xdks-for-the-x-api-v2/250860).
### Filtrado por palabra clave para las suscripciones de la X Activity API
Hoy añadimos el filtrado por palabra clave a las suscripciones de la X Activity API. Además del filtrado por ID de usuario, los suscriptores ahora pueden acotar aún más la entrega de eventos por palabra clave, lo cual resulta útil para eventos de News y otros tipos de evento con altos volúmenes que justifican un filtrado adicional.
### Eventos de insignia de verificación, insignia de afiliado y actualización de handle en la X Activity API
Hoy ampliamos la [X Activity API](https://docs.x.com/x-api/activity/introduction) para entregar tipos de evento adicionales relacionados con el perfil:
* `profile.update.verified`: cuando cambia el estado de verificación de un usuario
* `profile.update.affiliate`: cuando cambia la insignia de afiliado de un usuario
* `profile.update.screenname`: cuando un usuario cambia su @handle
### Piloto del modelo Pay-Per-Use de la X API
Hoy anunciamos un piloto cerrado y limitado para un nuevo modelo de precios basado en créditos y uso. Los desarrolladores compran créditos por adelantado y pagan por solicitud: sin cuotas de suscripción fijas ni límites mensuales de objetos. Tarifas iniciales del piloto: $0.005 por lectura de Post, $0.01 por lectura de Usuario, $0.01 por lectura de evento de DM, $0.01 por creación de contenido, $0.01 por interacción de DM, $0.015 por interacción de Usuario. Más información [aquí](https://devcommunity.x.com/t/announcing-the-x-api-pay-per-use-pricing-pilot/250253).
### Lanzamiento de la beta abierta de la X Activity API
Hoy lanzamos la beta abierta de la [X Activity API](https://docs.x.com/x-api/activity/introduction): un nuevo conjunto de endpoints para suscribirse a eventos de actividad en tiempo real en X con latencia inferior a un segundo. Suscríbete a tipos de evento de perfil (`ProfileBioUpdate`, `ProfilePictureUpdate`, `ProfileBannerUpdate`, `ProfileGeoUpdate`, `ProfileUrlUpdate`), filtra por ID de usuario y recibe los eventos coincidentes a través de un stream HTTP persistente (`GET /2/activity/stream`) o webhooks. Las suscripciones se gestionan mediante `POST /2/activity/subscriptions`. Más información [aquí](https://devcommunity.x.com/t/announcing-the-x-activity-api-open-beta/250099).
### Edición de publicaciones mediante la X API
Hoy lanzamos la capacidad de editar publicaciones recientes de forma programática mediante la X API. Usa el endpoint existente `POST /2/posts` con un nuevo objeto `edit_options` que contenga `previous_post_id`. Requisitos: el usuario autenticado debe tener X Premium, la publicación debe ser propia y haberse creado en la última hora. Consulta la documentación actualizada de [Create or Edit Post](https://docs.x.com/x-api/posts/create-post). Más información [aquí](https://devcommunity.x.com/t/announcing-post-editing-via-the-x-api/249534).
### Connections API para gestionar conexiones de streaming activas
Hoy lanzamos la [Connections API](https://docs.x.com/x-api/connections/introduction) para gestionar conexiones de streaming activas de forma programática:
* `GET /2/connections`: lista las conexiones de streaming activas e históricas
* `DELETE /2/connections/all`: termina todas las conexiones de streaming activas de la app
* `DELETE /2/connections/{endpoint_id}`: termina las conexiones de un endpoint de streaming específico
* `DELETE /2/connections`: termina conexiones específicas por UUID
Esto ayuda a los desarrolladores a resolver errores de "TooManyConnections" y a limpiar conexiones obsoletas sin tener que esperar a que expiren.
### Community Notes: endpoint Evaluate Note
Hoy añadimos el endpoint `POST /2/evaluate_note` a la [Community Notes API](https://docs.x.com/x-api/community-notes/introduction). Los AI Note Writers ahora pueden evaluar una nota antes de enviarla y recibir señales sobre su posible utilidad, alineación con afirmaciones/opiniones y otros comentarios del modelo.
### Lanzamiento de la Filtered Stream Webhooks API
Hoy lanzamos la [Filtered Stream Webhooks API](https://docs.x.com/x-api/webhooks/stream/introduction), que entrega publicaciones públicas coincidentes de forma asíncrona a un webhook registrado, en lugar de requerir una conexión persistente. Las reglas se gestionan usando los endpoints existentes de `/2/tweets/search/stream/rules` y las publicaciones coincidentes (incluido el historial de ediciones) se entregan como JSON a tu webhook. Disponible para desarrolladores Enterprise; admite más de 25.000 reglas por proyecto con reglas de hasta 2.048 caracteres. Más información [aquí](https://devcommunity.x.com/t/announcing-the-filtered-stream-webhooks-api/248464).
### Eliminación de los endpoints de Like y Follow del nivel Free
Para combatir el abuso, la manipulación de la plataforma y la interacción falsa, eliminamos `POST /2/users/:id/likes` y `POST /2/users/:id/following` del nivel Free de la X API, con efecto inmediato. Los niveles de pago (Basic, Pro, Enterprise) no se ven afectados. Más información [aquí](https://devcommunity.x.com/t/update-to-x-api-free-tier-removal-of-like-and-follow-endpoints/247646).
### Endpoint de consulta de reglas de PowerStream
Hoy añadimos el endpoint `GET /2/powerstream/rules`, que permite a los clientes de PowerStream recuperar de forma programática las reglas configuradas en sus instancias de PowerStream.
### Difusión de publicaciones de la comunidad mediante `share_with_followers`
Hoy añadimos un nuevo parámetro booleano opcional `share_with_followers` a `POST /2/tweets`. Al publicar con un `community_id` y `share_with_followers: true`, la publicación de la comunidad también se difunde a las cronologías de los seguidores del usuario autenticado, lo que coincide con la casilla "Compartir también con los seguidores" en x.com.
### Lanzamiento de la Community Notes API
Hoy lanzamos la [Community Notes API](https://docs.x.com/x-api/community-notes/introduction): un nuevo conjunto de endpoints para que los AI Note Writers participen de forma programática en Community Notes:
* `GET /2/notes/search/posts_eligible_for_notes`: busca publicaciones elegibles para recibir una Community Note
* `GET /2/notes/search/notes_written`: recupera notas escritas previamente por el AI Note Writer autenticado
* `POST /2/notes`: envía una Community Note
El acceso requiere inscripción en X Developer AI y la aprobación como AI Note Writer de Community Notes.
### Cambio en el comportamiento de DM Events
Hoy realizamos un cambio en el comportamiento de DM Events de X API V2. Con el nuevo cambio, el arreglo `participant_ids` solo se incluirá para los eventos `ParticipantsJoin` y `ParticipantsLeave`, y listará únicamente a los participantes que se unieron o salieron en el momento del evento. El evento `MessageCreate` ya no incluirá el arreglo `participant_ids`. Más información [aquí](https://devcommunity.x.com/t/upcoming-change-to-x-api-dm-events-endpoints-behavior/241841).
### Lanzamiento de los endpoints de Account Activity API
Hoy lanzamos los nuevos [endpoints de Account Activity API](/x-api/webhooks/introduction) de X API v2. Más información [aquí](https://devcommunity.x.com/t/account-activity-api-is-now-available-in-v2/242895).
### Mejoras al endpoint de carga de medios
Hicimos algunas mejoras al endpoint de carga de medios para mejorar la experiencia del desarrollador. Introdujimos endpoints dedicados para la carga de medios en fragmentos en los [endpoints de Media Upload](/x-api/media/introduction). Más información [aquí](https://devcommunity.x.com/t/media-upload-endpoints-update-and-extended-migration-deadline/241818).
### Soporte para obtención de direcciones de correo electrónico con OAuth 2.0
Hoy añadimos compatibilidad para la obtención de direcciones de correo electrónico con OAuth 2.0 en X API V2. Más información [aquí](https://devcommunity.x.com/t/announcing-support-for-email-address-retrieval-with-oauth-2-0-in-the-x-api-v2/240555).
### Cambios en los datos de afiliación de usuario
Hoy realizamos cambios en los datos de User Affiliation de X API V2. Con el nuevo cambio, `affiliation.user_id` devolverá un arreglo de `user_ids`. Anteriormente devolvía un único `user_id` como cadena, incluso si un usuario tenía múltiples afiliaciones. Más información [aquí](https://devcommunity.x.com/t/change-to-x-api-user-affiliation-data/237164).
### Lanzamiento de los endpoints de carga de medios
Hoy lanzamos los nuevos [endpoints de Media Upload](/x-api/media/introduction) de X API v2. Más información [aquí](https://devcommunity.x.com/t/announcing-media-upload-endpoints-in-the-x-api-v2/234175/3).
### Lanzamiento del nuevo sitio de documentación
Hoy lanzamos nuestro nuevo sitio de documentación de la X Developer Platform, [https://docs.x.com](https://docs.x.com).
### Lanzamiento de la herramienta xurl
Hoy lanzamos [xurl](https://github.com/xdevplatform/xurl), una nueva herramienta que simplifica las pruebas de API para desarrolladores de X y que ahora admite OAuth 2.0.
### Adición del campo Community ID en Tweet
Hoy añadimos el campo `community_id` a Tweet en X API v2. Más información [aquí](https://x.com/tapshah21/status/1860061806653317126).
### Adición de endpoints de bloqueo de DM
Hoy añadimos los endpoints de bloqueo y desbloqueo de DM en X API v2.
### Soporte para publicaciones de formato largo
Hoy añadimos la capacidad de crear publicaciones de formato largo con una longitud de 25k en lugar de 4k.
### Soporte para publicaciones de formato largo
Hoy añadimos la capacidad de crear publicaciones de formato largo usando X API v2
### Obtener afiliación de usuario
Hoy añadimos la capacidad de obtener la afiliación de un usuario de forma programática usando X API v2
### Obtener metadatos de Article
Hoy añadimos la capacidad de obtener metadatos de Article usando X API v2
### Obtener imagen de perfil y de portada
Hoy añadimos la capacidad de obtener la URL de la imagen de perfil y la imagen de portada a través de X V2 API
### Adición del campo Connection Status
Hoy añadimos el campo `connection_status` en X API v2. Más información [aquí](https://devcommunity.x.com/t/announcing-connection-status-field-in-the-user-object-in-the-x-api-v2/212588).
### Adición del endpoint de búsqueda de Trends
Hoy añadimos el endpoint de búsqueda de Trends en X API v2. Más información [aquí](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567).
### Adición del endpoint de búsqueda de Users
Hoy añadimos el endpoint de Users Search en X API v2. Más información [aquí](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567).
### Obtener permisos de DM
Hoy añadimos la capacidad de obtener permisos de DM a través de X API v2. Más información [aquí](https://devcommunity.x.com/t/dm-permissions-available-in-the-x-api-v2/209688).
### Lanzamiento del campo Subscription Type
Hoy lanzamos el campo `subscription_type` en el objeto User en X API v2. Más información [aquí](https://devcommunity.x.com/t/new-subscription-type-field-is-available-in-the-twitter-api-v2/209219/2).
### Endpoint Get Posts Usage
Hoy lanzamos un endpoint para obtener de forma programática el uso de tus publicaciones en X API v2. Más información [aquí](https://developer.x.com/en/docs/twitter-api/usage/tweets/api-reference/get-usage-tweets).
### Lanzamiento del endpoint Reposts Lookup
Hoy lanzamos un endpoint para buscar los reposts de una publicación en X API v2. Más información [aquí](https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweets).
### Desuso de endpoints de búsqueda
Hoy quedan en desuso los endpoints `search/tweets`, `users/search` y `geo/search` en X API v1.1. Más información [aquí](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features).
### Desuso del endpoint Replay API
Hoy queda en desuso el endpoint Replay API de la X API enterprise. Puedes usar las funcionalidades de [recovery](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features) en su lugar.
### Desuso de los endpoints de Historical Powertrack
Hoy quedan en desuso los endpoints de Historical Powertrack e Insights Track de la X API enterprise.
### Eliminación de los endpoints de Follows en los niveles Basic y Pro
Hoy eliminamos los endpoints de Follows y List Follows en los niveles Basic y Pro de X API v2.
### Eliminación del endpoint Manage Blocks
Hoy eliminamos el endpoint Manage Blocks de X API v2.
### Soporte para conteo de marcadores y publicaciones largas
Hoy añadimos soporte para obtener el conteo de bookmarks y la capacidad de recuperar publicaciones con más de 280 caracteres en X API v2.
### Desuso del endpoint Statuses/Filter
Hoy queda en desuso el endpoint `statuses/filter` en X API v1.1. Los desarrolladores pueden usar el endpoint Filtered Stream de X API v2.
### Soporte para View Counts
Hoy añadimos soporte para View Counts en X API v2. Se incorpora un nuevo campo llamado `impression_count` dentro de `public_metrics` en el payload de la publicación.
### Adición del campo Verified Type
Hoy añadimos un campo de usuario `verified_type` en X API v2 que indica el tipo de verificación que tiene la cuenta de un usuario (blue, business, government o none).
### Eliminación del campo Source
Hoy eliminamos el campo `source` del payload de publicación en las X APIs.
### Adición de los endpoints de Direct Messages
Hoy añadimos seis endpoints de Direct Messages v2. Esta versión incluye tres métodos GET para recuperar eventos de conversaciones de Direct Message y tres métodos POST para crear nuevos Direct Messages. Estos métodos admiten conversaciones grupales por primera vez.
Visita nuestra [publicación del blog](https://developer.x.com/en/blog/product-news/2022/new-v2-direct-messages-endpoints) para obtener más información sobre esta actualización.
### Soporte para metadatos de publicaciones editadas
Hoy añadimos la capacidad para que los desarrolladores recuperen metadatos de publicaciones editadas usando X API v2.
Visita nuestra [publicación del blog](https://developer.x.com/en/blog/product-news/2022/supporting-edit-tweet-functionality) para obtener más información sobre esta actualización.
### Adición de alias para operadores de filtrado
Se añadieron «alias» de operadores de filtrado/consulta a los endpoints de Search y Filtered Stream, en enterprise, premium y v2. En muchos casos, el operador hace referencia a posts en lugar de statuses, por ejemplo, `in_reply_to_tweet_id` como alias de `in_reply_to_status_id`. En otros casos, el nuevo alias del operador añade mayor claridad a la coincidencia realizada. Por ejemplo, dado que las publicaciones solo pueden tener un video adjunto, se proporciona un nuevo alias `has:video_link` para `has:videos`. Consulta la [tabla de operadores de v2 filtered stream](https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule#list) para ver más ejemplos.
### Actualizaciones a Reverse Chronological Home Timeline
A partir de hoy, el endpoint reverse chronological home timeline v2 puede devolver todas las publicaciones creadas en un timeline durante los últimos 7 días y las 800 más recientes independientemente de la fecha de creación.
### Nuevos operadores de filtrado para Filtered Stream
Hoy, 10 nuevos operadores de filtrado v2 están disponibles para todos los desarrolladores que utilicen los endpoints de filtered stream, y otros 10 están ahora más ampliamente disponibles.
Visita nuestra [publicación del blog](https://developer.x.com/en/blog/product-news/2022/twitter-api-v2-filtered-stream) para obtener más información sobre esta actualización.
### Actualizaciones a la latencia de los endpoints de Streaming
Hoy realizamos actualizaciones en los endpoints de streaming de X API v2 para reducir la latencia en un 50%.
### Habilitación de los endpoints de medios v1.1 en Essential Access
Hoy habilitamos los endpoints de medios v1.1 en el acceso Essential de X API v2.
Visita nuestro [anuncio del foro](https://devcommunity.x.com/t/v1-1-media-endpoints-available-for-essential-access-in-the-twitter-api-v2/171664) para obtener más información sobre esta actualización.
### Lanzamiento del endpoint Reverse Chronological Home Timeline
Hoy lanzamos un nuevo endpoint que te permite recuperar una colección de las publicaciones y reposts más recientes publicados por las personas que sigues.
Visita nuestro [anuncio del foro](https://devcommunity.x.com/t/reverse-chronological-home-timeline-in-the-twitter-api-v2/171549) para obtener más información sobre este lanzamiento.
Junto con los nuevos endpoints, el campo `variants` está ahora disponible para el [objeto media](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/media). Esto te dará el tipo de contenido adjunto con la URL.
### Lanzamiento de los endpoints de Bookmarks
Hoy lanzamos nuevos endpoints que te permiten gestionar y buscar Bookmarks usando X API v2. La función Bookmarks ha estado disponible durante mucho tiempo en la aplicación X, pero hasta ahora no existía un endpoint que permitiera recuperar, crear o construir soluciones para administrar tus Bookmarks vía la API.
Visita nuestro [anuncio del foro](https://devcommunity.x.com/t/build-with-bookmarks-on-the-twitter-api-v2/168804) para obtener más información sobre este lanzamiento.
### Lanzamiento del endpoint Quotes Lookup
Hoy lanzamos el [endpoint quotes lookup](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) que te permite obtener las citas de un ID de publicación.
Visita nuestro [anuncio del foro](https://devcommunity.x.com/t/introducing-the-quote-tweets-lookup-endpoint-to-the-twitter-api-v2/168370) para obtener más información sobre este lanzamiento.
### Actualizaciones a la navegación de la documentación
Hemos escuchado tus comentarios. Encontrar contenido en nuestra documentación podía ser difícil y resultaba confuso cuando hacías clic en un enlace y te llevaba a una navegación lateral completamente distinta.
Hoy lanzamos una navegación de documentación actualizada que te permite explorar la oferta completa de la X Developer Platform desde una sola navegación lateral. Con este lanzamiento, eliminamos páginas redundantes, retiramos íconos confusos y mejoramos la forma en que puedes interactuar con los diferentes elementos dentro de la navegación.
Si tienes algún comentario, háznoslo saber a través de nuestro [canal de feedback](https://twitterdevfeedback.uservoice.com/forums/930250-twitter-api).
### Mejoras a los endpoints Reposts y Likes Lookup
Hoy lanzamos mejoras a los endpoints [reposts lookup](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) y [Likes lookup](https://developer.x.com/en/docs/twitter-api/tweets/likes/introduction), permitiéndote obtener la lista completa de cuentas que han marcado «Me gusta» o reposteado una publicación, no solo las últimas 100 cuentas que lo hicieron.
Para más información sobre este lanzamiento, visita nuestro anuncio del foro.
### Soporte para autenticación OAuth 2.0
Hoy, todos los desarrolladores pueden autenticarse usando OAuth 2.0 seleccionándolo como método de autenticación en el Developer Console. Hemos añadido soporte para clientes confidenciales y públicos, y para todos los endpoints v2 relevantes para usar este método de autenticación como parte de esta versión.
OAuth 2.0 es un protocolo de autorización estándar de la industria que proporciona a los desarrolladores mayor control sobre los scopes de una aplicación y mejora los flujos de autorización en múltiples dispositivos. En otras palabras, los desarrolladores que crean aplicaciones para personas en X tendrán más control sobre la información que su aplicación solicita a sus usuarios, de modo que solo tengas que pedir a tus usuarios finales los datos e información que necesitas.
Este moderno protocolo de autorización te permitirá presentar a tus usuarios finales un flujo de consentimiento más optimizado para autorizar tu aplicación, mostrando únicamente los scopes específicos que has solicitado.
Para obtener más información sobre este lanzamiento, visita nuestro anuncio del foro.
### Actualizaciones importantes de plataforma a X API v2
**Actualizaciones importantes de plataforma: X API v2 es ahora la versión principal, nuevo acceso Essential y Elevated, y cambios en la Política**
Hoy anunciamos que X API v2 es ahora la versión principal de la X API. Hemos lanzado suficientes endpoints y funcionalidad en X API v2 para satisfacer las necesidades del 90% de todas las aplicaciones existentes creadas sobre la X API.
Hoy lanzamos los siguientes cambios para seguir mejorando la experiencia del desarrollador de X API v2:
* Acceso Essential rápido y gratuito a la API, y acceso Elevated gratuito para desarrolladores con casos de uso aprobados. Tenemos muchos más detalles sobre estos niveles de acceso en nuestra página About the X API.
* Estamos eliminando lenguaje en nuestra Developer Policy que restringía cómo se construye con las funcionalidades centrales de X y limitaba el número de usuarios que puedes admitir a través de tu app.
* Estamos abriendo nuestra plataforma para alentarte a crear herramientas y productos que hagan a X mejor, más saludable y que extiendan la conversación pública. [Consulta una lista de soluciones que nos encantaría ver creadas](https://developer.x.com/en/docs/twitter-api/what-to-build).
* Específicamente, hemos eliminado términos que restringían la replicación de la experiencia de X, incluidas las funcionalidades centrales de X, así como términos que requerían permiso para tener un número alto de tokens de usuario.
* Sabemos que crear soluciones que ayuden a las personas en X a menudo significa que un desarrollador tiene que construir (o replicar) algunas de las cosas que están disponibles en X. Estos cambios a nuestra Developer Policy buscan brindar claridad al ecosistema de desarrolladores y proporcionar una plataforma de API abierta que facilite a los desarrolladores crear, innovar y generar impacto en la conversación pública.
Entramos en mucho más detalle sobre este lanzamiento y los lanzamientos de X API que llevaron a este momento en nuestra [publicación del foro](https://devcommunity.x.com/t/ushering-in-a-new-era-for-the-twitter-developer-platform-with-the-twitter-api-v2/162087).
Además de explorar entradas anteriores del changelog, hemos preparado algunos recursos clave que puedes revisar para entender todo lo que se ha lanzado en X API v2 hasta la fecha:
* [X API endpoint map](/x-api/migrate/x-api-endpoint-map)
* [About the X API](/x-api/getting-started/about-x-api)
### Lanzamiento de los endpoints List Lookup
Hoy lanzamos los nuevos endpoints List lookup en X API v2. Estos endpoints permitirán a los usuarios recuperar detalles de Lists especificadas, como seguidores, miembros, publicaciones y más. Los datos recuperados pueden usarse para crear soluciones que resuelvan casos de uso y necesidades de curación, análisis y descubrimiento. Además de los nuevos endpoints de List, ahora está disponible un nuevo operador `list:` en el nivel de acceso Academic Research. Estará disponible para usar en search posts y post counts.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-list-lookup-endpoints-for-the-twitter-api-v2/161965).
### Adiciones a los endpoints de Spaces
Estamos añadiendo funcionalidad al endpoint de Spaces para devolver la lista de personas que compraron una entrada para un Space, así como soporte para Topics.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/adding-new-functionality-to-spaces-endpoints/161959).
### Lanzamiento de los endpoints Manage Posts
Hoy lanzamos nuevos endpoints manage posts en X API v2. Además de la funcionalidad de post y eliminación de post, hemos añadido la capacidad de publicar encuestas, etiquetar personas en imágenes, crear publicaciones con configuración de respuestas y publicar para Super Followers.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-manage-tweets-endpoints-for-the-twitter-api-v2/161501).
### Cambios a los botones embebidos
Hoy realizamos algunos cambios en los botones embebidos de X. Los botones ahora son más redondeados para coincidir con los botones de X.com y hemos (ligeramente) actualizado nuestra paleta de colores.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/embedded-buttons-have-a-new-look/160528).
### Lanzamiento del grupo de endpoints Lists
Hoy lanzamos el nuevo grupo de endpoints de Lists en X API v2. Estos endpoints te permitirán crear soluciones que curen y organicen publicaciones según preferencias, intereses, grupos o temas.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-manage-list-endpoints/159980).
### Lanzamiento del endpoint Mutes Lookup
Hoy lanzamos el nuevo endpoint [mutes lookup](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) en X API v2. Este endpoint permitirá a los usuarios autenticados recuperar y obtener información sobre las cuentas que han silenciado.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-new-mutes-lookup-endpoint-for-the-twitter-api-v2/159680).
### Lanzamiento de la beta de OAuth 2.0
Hoy lanzamos una beta de OAuth 2.0 y scopes detallados en X API v2. Los desarrolladores interesados en dar forma al futuro de OAuth 2.0 en la X Developer Platform pueden solicitar acceso a la beta de OAuth 2.0.
OAuth 2.0 es el estándar de la industria para la autenticación y permitirá una experiencia de autorización más moderna.
La beta de OAuth 2.0 te permite probar esta nueva funcionalidad en un Project v2 y App asociada y darnos comentarios antes de una versión General Availability. Sin embargo, dado que esta implementación de OAuth 2.0 está actualmente en desarrollo, recomendamos encarecidamente que evites probar en un entorno público, de producción o aplicación.
Para obtener más información sobre este lanzamiento, visita nuestro anuncio del foro.
### Lanzamiento de los endpoints de Batch Compliance
Hoy lanzamos los nuevos [endpoints de batch compliance](https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/introduction) en X API v2 para facilitar a los desarrolladores que usan la X API mantener sus datos de X en cumplimiento con nuestro [Developer Agreement and Policy](https://developer.x.com/en/developer-terms/policy). Estos endpoints permiten a desarrolladores e investigadores cargar por lotes grandes cantidades de IDs de publicaciones o Usuarios y comprender qué acción se necesita para asegurar que sus conjuntos de datos reflejen la intención del usuario y el estado actual del contenido en X.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/new-batch-compliance-endpoints-available-on-the-twitter-api-v2/158534).
### Lanzamiento de los endpoints de Spaces
Hoy lanzamos los nuevos [endpoints de Spaces](https://developer.x.com/en/docs/twitter-api/spaces/overview) y un [nuevo diccionario de datos de Spaces de nivel superior](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/space) en X API v2. Los endpoints de Spaces te permiten buscar Spaces por Space ID o user ID, o usando palabras clave, hashtags o nombres de usuario de personas mencionadas en un título. El nuevo diccionario de datos contiene información relevante sobre un Space como su título, estado de venta de entradas y métricas de participantes; todos los IDs de usuario pueden expandirse a objetos completos.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/introducing-new-spaces-endpoints-on-the-twitter-api-v2/158213).
### Nuevo objeto para la limitación de visualizaciones de video
Anteriormente, cuando solicitabas métricas de visualizaciones de video usando el enterprise \[Engagement API]/x-api/enterprise-gnip-2.0/fundamentals/engagement-api) en publicaciones con más de 1800 días de antigüedad, entregábamos un valor cero sin mucho contexto. Hoy, comenzaremos a entregar un nuevo objeto en estos casos llamado `unsupported_for_video_views_tweet_ids`, que incluirá una lista separada por comas de IDs de publicaciones con más de 1800 días de antigüedad. Seguirás recibiendo todas las demás métricas solicitadas para estas publicaciones en un objeto separado.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/new-engagement-api-video-views-object-to-clarify-limitation/158163).
### Adición del campo Alt Text
Hoy estamos haciendo disponible el campo `alt_text` en el objeto media de X API v2, para permitir a los desarrolladores crear de forma más consciente para la accesibilidad.
Para solicitar este campo, debes pasar el parámetro `expansions=attachments.media_keys`, así como el parámetro `media.fields=alt_text`. Si se incluye en tu solicitud, este campo devolverá el texto alternativo para cualquier publicación que incluya imágenes con texto alternativo.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/media-alt-text-field-now-available-in-twitter-api-v2/157939).
### Lanzamiento de los endpoints de Reposts
Hoy lanzamos nuevos endpoints de [reposts](https://developer.x.com/en/docs/twitter-api/tweets/retweets) en X API v2. Los desarrolladores ahora pueden usar estos endpoints para repostear o deshacer un repost en nombre de un usuario autenticado, o para buscar quién reposteó una publicación dada.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-retweets-endpoints/156827).
### Lanzamiento de los endpoints Manage Mutes
Hoy lanzamos nuevos endpoints [manage mutes](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) en X API v2. Estos endpoints permitirán a los usuarios autenticados silenciar o desactivar el silencio de cuentas.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-new-manage-mutes-endpoints-for-the-twitter-api-v2/156261).
Hemos reducido `max_results` que puede entregarse con el endpoint [full-archive search](/x-api/posts/full-archive-search) cuando solicitas el campo `context_annotations` con el parámetro `tweet.fields` a 100, lo que significa que solo puedes obtener hasta 100 publicaciones con el campo por página.
### Funcionalidades de fiabilidad para endpoints de Streaming
Hoy lanzamos dos funcionalidades de streaming de fiabilidad para filtered stream y sampled stream de X API v2 llamadas backfill y redundant connections, ahora disponibles en el producto Academic Research.
La funcionalidad redundant connections te permite conectarte a un stream dado dos veces, lo que puede ayudar a asegurar que maximices el tiempo de actividad del streaming en caso de que una de tus conexiones experimente una desconexión.
Backfill puede utilizarse añadiendo el parámetro `backfill_minutes` y un número entero entre uno y cinco a tu solicitud de streaming, y te permite solicitar datos perdidos que pudieran haber resultado de un stream desconectado.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/new-reliability-and-recovery-functionality-available-for-twitter-api-v2-streaming-endpoints/156244/2).
### Lanzamiento de los endpoints de Post Counts
Hoy lanzamos los nuevos [endpoints de post counts](/x-api/posts/counts/introduction) en X API v2. Esto incluye dos endpoints diferentes: Recent post counts, que está disponible para todos los productos, y full-archive post counts, que actualmente solo está disponible para el producto Academic Research. Puedes usar estos endpoints para recibir el conteo de publicaciones que coincide con una consulta especificada.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/introducing-new-tweet-counts-endpoints-to-the-twitter-api-v2/155997).
### Mejoras a Teams
Hoy lanzamos mejoras clave a la funcionalidad de teams basadas en los comentarios que hemos escuchado de la comunidad. Hemos actualizado el estilo y diseño de la página de teams. También hicimos cambios al flujo de invitación para facilitar la invitación de miembros del equipo o conocer por qué una invitación pudo haber fallado. Si tienes una cuenta de team, puedes ver los cambios visitando la [página de teams](https://developer.x.com/en/portal/teams) del Developer Console. Para obtener más información sobre teams, consulta nuestra \[documentación sobre el tema]\([https://developer.x.com/en/docs/Developer](https://developer.x.com/en/docs/Developer) Console/overview#team) y \[FAQ]\([https://developer.x.com/en/docs/Developer](https://developer.x.com/en/docs/Developer) Console/faq#dev-portal-management-faq) relacionadas.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-improvements-to-the-functionality-of-teams/155447/2).
### Retiro del endpoint Configuration
Hoy retiramos el endpoint estándar v1.1 `GET /help/configuration`.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/retiring-the-1-1-configuration-endpoint/153319).
### Consolidación del endpoint oEmbed
Hoy compartimos que el endpoint oEmbed v1.1 será retirado y eliminado el 23 de noviembre de 2021, para que las nuevas funcionalidades puedan ser soportadas de manera consistente. Después de esa fecha, el único endpoint API oficial y soportado para X oEmbeds (publicaciones y timelines embebidos) será vía publish.x.com/oembed.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/consolidating-the-oembed-functionality/154690/2).
### Lanzamiento de los endpoints Blocks y Likes Lookup
Hoy lanzamos los nuevos endpoints de búsqueda de [blocks](/x-api/users/blocks) y [Likes](/x-api/posts/likes) en X API v2. Estos endpoints te permiten usar la v2 API para obtener información sobre qué publicaciones ha marcado «Me gusta» una cuenta, qué usuarios han dado «Me gusta» a una publicación, y a quién has bloqueado tú o un usuario autenticado.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-twitter-api-v2-likes-lookup-and-blocks-lookup/154353).
### Lanzamiento de los endpoints Manage Likes
Hoy lanzamos los nuevos endpoints [manage Likes](https://developer.x.com/en/docs/twitter-api/tweets/likes) en X API v2. Estos endpoints te permiten usar la v2 API para dar «Me gusta» y quitar «Me gusta» a publicaciones.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-new-manage-likes-endpoints-for-thetwitter-api-v2/152780).
### Lanzamiento de los endpoints Manage Blocks
Hoy lanzamos los nuevos endpoints [manage blocks](/x-api/users/blocks) en X API v2. Estos endpoints te permiten bloquear o desbloquear cuentas en nombre de un usuario usando IDs de usuario.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/announcing-manage-blocks-for-twitter-api-v2/152358/2).
### Eliminación del soporte para Embedded Timelines
Hoy compartimos nuestros planes para el futuro de los [widgets de timeline embebidos](https://developer.x.com/en/docs/x-for-websites/timelines/overview). El 23 de junio de 2021, planeamos retirar los timelines Likes, Collections y Moments. Recomendamos usar los timelines [Profile](https://developer.x.com/en/docs/x-for-websites/timelines/guides/profile-timeline) y [Lists](https://developer.x.com/en/docs/x-for-websites/timelines/guides/list-timeline), que estamos actualizando para ser más rápidos, fáciles de usar y más actualizados con las funcionalidades y la funcionalidad de X.
Puedes obtener más información sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/removing-support-for-embedded-like-collection-and-moment-timelines/150313).
### Lanzamiento de los endpoints Manage Follows
Hoy lanzamos los nuevos endpoints [manage follows](/x-api/users/follows) en X API v2. Estos endpoints te permiten seguir o dejar de seguir cuentas en nombre de un usuario usando su ID de usuario. Este lanzamiento llega unos meses después del lanzamiento de los endpoints [follows lookup](/x-api/users/follows), que te permiten recuperar los seguidores de una cuenta y a quién están siguiendo.
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/introducing-the-new-manage-follows-endpoints-to-the-twitter-api-v2/149465).
### Introducción del producto Academic Research
Hoy presentamos el nuevo [producto Academic Research](/resources/fundamentals/developer-apps) en [X API v2](/x-api/introduction). Esta actualización introduce un nuevo proceso de aplicación para Academic Researchers que proporcionará a los aprobados un [Project](/resources/fundamentals/developer-apps) Academic Research que desbloqueará mayor acceso y funcionalidad avanzada.
Con el nuevo producto Academic Research, podrás acceder a lo siguiente:
* El nuevo [endpoint full-archive search](/x-api/posts/full-archive-search) de X API v2, que actualmente solo está disponible para el producto Academic Research.
* Un [post cap](/x-api/fundamentals/post-cap) incrementado de 10 millones, frente a los 500,000 disponibles en el [producto Standard](/resources/fundamentals/developer-apps) en el [nivel de acceso Basic](https://developer.x.com/en/products/x-api/early-access/guide#na_2).
* Nuevos operadores de filtro disponibles para [recent search](/x-api/posts/recent-search), [full-archive search](/x-api/posts/full-archive-search), y [filtered stream](/x-api/posts/filtered-stream), incluyendo `$` (alias cashtag), `bio` (solo disponible vía filtered stream), `bio_name` (solo disponible vía filtered stream), `bio_location` (solo disponible vía filtered stream), `place`, `place_country`, `point_radius`, `bounding_box`, `-is:nullcast`, `has:cashtags` y `has:geo`.
* Un límite incrementado de reglas para filtered stream de 1,000 reglas concurrentes, frente a las 25 disponibles en el producto Standard en el nivel de acceso Basic.
* Un límite incrementado de caracteres de consulta y regla de 1,024 caracteres, frente al límite de 512 caracteres disponible en el producto Standard en el nivel de acceso Basic
Para obtener más información sobre este lanzamiento, visita nuestro [anuncio del foro](https://devcommunity.x.com/t/introducing-the-new-academic-research-product-track/148632).
### Adición del campo Reply Settings
Hoy lanzamos un nuevo campo en el objeto post llamado `reply_settings`. Este campo está disponible en todos los endpoints de X API v2 que devuelven publicaciones, incluidos los endpoints post lookup, hide replies, recent search, sampled stream, filtered stream, follows lookup, user post timeline, y user mention timeline, o al [expandir](/x-api/fundamentals/expansions) el objeto post en cualquier endpoint.
Este campo indica cómo el autor de la publicación ha permitido a otros responder a sus publicaciones, ya sea todos, solo las personas que mencionan en la publicación o aquellos a quienes siguen. Los valores de campo devueltos por el campo `reply_settings` incluyen `everyone`, `mentionedUsers` y `following`. Si no se establecen controles de conversación para la publicación, esto seguirá mostrándose en el objeto post con el valor `everyone` para el campo.
### Lanzamiento de los endpoints User Post y Mention Timeline
Hoy lanzamos los nuevos [endpoints user post timeline y user mention timeline](/x-api/posts/timelines) en X API v2. Estos endpoints te permiten solicitar las publicaciones compuestas por, o mencionando, a una cuenta especificada en X. Más información en el anuncio de la publicación del foro.
### Lanzamiento de los endpoints Follows Lookup
Hoy lanzamos los nuevos [endpoints follows lookup](/x-api/users/follows) en X API v2. Estos endpoints te permiten recuperar los seguidores de una cuenta y a quién están siguiendo usando su ID de usuario. Más información en el anuncio de la publicación del foro.
### Retiro de los endpoints Labs v2
Retirados los endpoints Labs v2 recent search y hide replies
Hemos retirado los siguientes endpoints. Si estabas usando las versiones de Labs de estos endpoints, puedes usar las guías de migración enlazadas para actualizar tu integración y comenzar a usar las nuevas versiones de X API v2:
* [Recent search v2](/x-api/posts/search/migrate/overview)
* [Hide replies v2](/x-api/posts/hide-replies/migrate)
También tenemos detalles adicionales sobre la migración a la nueva X API v2 a través de nuestro [centro de migración](/x-api/migrate/overview).
Si tienes alguna pregunta, contáctanos a través de nuestra [categoría del foro de Labs](https://devcommunity.x.com/c/labs/57).
### Retiro de los endpoints Labs v1
El 12 de agosto de 2020, lanzamos la nueva X API v2: Early Access. Con esta versión, graduamos varios endpoints a X API v2 desde el programa Labs, y anunciamos que la versión Labs de los endpoints permanecería en estado de retiro durante 60 días antes de retirarlos.
Hoy se cumplen 60 días desde el lanzamiento, lo que significa que hemos retirado los siguientes endpoints. Si estás usando las versiones de Labs de estos endpoints, puedes usar las guías de migración enlazadas para actualizar tu integración y comenzar a usar las nuevas versiones de X API v2:
* Post metrics v1
* Filtered stream v1
* Sampled stream v1
También tenemos detalles adicionales sobre la migración a la nueva X API v2 a través de nuestro [centro de migración](/x-api/migrate/overview).
Si tienes alguna pregunta, contáctanos a través de nuestra [categoría del foro de Labs](https://devcommunity.x.com/c/labs/57).
### Adición de la barra de estado de consumo de Post
En la [página principal del panel](https://developer.x.com/en/portal/dashboard) del nuevo Developer Console, ahora puedes verificar tu uso hacia el [post cap](/x-api/fundamentals/post-cap) de 500,000 publicaciones por mes. Este límite se aplica a nivel de Project, a través de los siguientes endpoints v2 en acceso Basic: filtered stream y recent search.
Para ver esta funcionalidad y usar los nuevos endpoints v2, deberás activar la [nueva experiencia de Developer Console](https://developer.x.com/en/portal/opt-in.html).
### Lanzamiento del endpoint Hide Replies
Hoy lanzamos el nuevo endpoint hide replies en la v2 X API. Este endpoint te permite ocultar respuestas abusivas, distractoras o engañosas a publicaciones — una pieza crucial para mejorar la salud de la conversación pública. Más información en el anuncio de la publicación del foro.
El mismo endpoint en X Developer Labs ahora queda en desuso y se retirará en 90 días. Aprende cómo [migrar al endpoint v2.](/x-api/posts/hide-replies#comparing-twitter-apis-hide-replies-endpoints)
### Early Access a los endpoints de X API v2
Hoy anunciamos [Early Access a los primeros endpoints de la nueva X API](https://blog.x.com/developer/en_us/topics/tools/2020/introducing_new_twitter_api.html).
La nueva X API presenta una nueva base de API que nos permitirá ofrecer nueva funcionalidad más rápido; un formato de datos actualizado y nueva funcionalidad que te da más control sobre qué campos recibes; nuevos campos de post, usuario y media; y un conjunto de endpoints actualizados que te permiten escuchar y analizar publicaciones, incluyendo lo siguiente:
* [Post lookup](/x-api/posts/post-lookup-by-post-ids)
* [User lookup](/x-api/users/user-lookup-by-id)
* [Recent search](/x-api/posts/recent-search)
* [Filtered stream](/x-api/posts/filtered-stream)
* [Sampled stream](/x-api/stream/stream-sampled-posts)
Puedes encontrar una lista completa de la nueva funcionalidad disponible y recursos de migración en nuestra \[página de documentación X API v2: Early Access][https://developer.x.com/en/docs/x-api/early-access](https://developer.x.com/en/docs/x-api/early-access)).
Más información sobre lo que tenemos planeado en nuestra «\[Guide to the future of the X API][https://developer.x.com/en/docs/x-api/early-access)»](https://developer.x.com/en/docs/x-api/early-access\)»).
### Desuso de los endpoints de Labs
Estamos desusando ciertos endpoints de Labs debido al lanzamiento de sus reemplazos en X API v2 en esta versión.
Los siguientes endpoints Labs v1 se retirarán 60 días a partir del lanzamiento de hoy:
* Post metrics v1
* Filtered stream v1
* Sampled stream v1
El siguiente endpoint Labs v2 se retirará 90 días a partir del lanzamiento de hoy:
* Recent search v2
### Mejoras a Hide Replies
Añadimos la capacidad de desocultar una respuesta. Adicionalmente, las respuestas previamente desocultadas ahora pueden ocultarse nuevamente a través de este endpoint.
Obtén más detalles en la [documentación de Hide Replies](https://developer.x.comhttps://developer.x.com/en/docs/labs).
### Retiro de los endpoints Labs v1
Hoy retiramos los endpoints Labs v1 posts and users, hide replies y recent search.
Puedes leer más sobre nuestro plan de Labs v1 en nuestro [anuncio del foro](https://devcommunity.x.com/t/update-on-labs-v1-endpoints/138641).
### Adición de la métrica Quote Tweets
Hoy, la métrica `quote_tweets` está disponible para publicaciones 'unowned' a través del endpoint [/totals](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api#post-insights-engagement). Esto significa que puedes acceder al conteo de citas para todas las publicaciones usando autenticación solo de aplicación.
Puedes leer más sobre este cambio en nuestra [publicación del foro](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131).
### Adición de nuevas métricas de Post
Hoy añadimos dos nuevos subcampos de métricas no públicas, `user_profile_clicks` y `url_link_clicks`, al objeto post en los endpoints post lookup de X Developer Labs. Se devolverán al usar el parámetro `tweet.fields` con cualquiera de los siguientes valores: `non_public_metrics`, `organic_metrics` o `promoted_metrics`.
Para obtener más información, visita la [referencia de la API de post lookup](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets-id)
### Cambios a los conteos de Repost
A partir de hoy, X web, iOS y Android mostrarán el conteo total de 'reposts and comments' por publicación. Usando la X API, el número total de 'reposts and comments' que coincide con la interfaz de X puede calcularse sumando `retweet_count` y `quote_count` cuando estén disponibles. Adicionalmente, `quote_count` será el total de cuentas únicas que han citado la publicación, en lugar del total de publicaciones que citan la publicación. Para más detalles, consulta nuestra [publicación del foro](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131/2).
### Agrupaciones de métricas Organic y Promoted
Estamos añadiendo `organic_metrics` y `promoted_metrics` a los objetos post y media en los endpoints post lookup.
### Adición de métricas a los endpoints
Estamos añadiendo métricas a los objetos post y media en los endpoints post lookup y recent search.
Puedes leer más sobre estos cambios en nuestro [anuncio del foro](https://devcommunity.x.com/t/adding-metrics-to-the-tweets-and-recent-search-endpoints-in-labs/135315)
### Lanzamiento de los endpoints COVID-19
Hoy lanzamos un nuevo endpoint COVID-19 stream y un endpoint de compliance que lo acompaña.
Puedes leer más sobre estos cambios en nuestro [anuncio del foro.](https://devcommunity.x.com/t/new-covid-19-stream-endpoint-available-in-twitter-developer-labs/135540)
### Actualizaciones a perfiles de usuario en la Replay API
A partir de hoy, la Replay API entregará objetos de perfil de usuario que reflejen al usuario referenciado en el momento en que se está ejecutando la Replay API. Este cambio para entregar objetos de perfil de usuario actuales es similar a la actualización reciente de Historical PowerTrack del 25 de noviembre de 2019.
### Adición de Post Annotations
Estamos añadiendo anotaciones al objeto post en los endpoints posts y recent search.
Puedes leer más sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/adding-annotations-to-tweets-and-recent-search-endpoints-in-labs/135193).
### Actualizaciones a la Developer Policy
Hoy anunciamos una [actualización significativa a la Developer Policy](https://developer.x.com/en/developer-terms/policy). Te animamos a leer más sobre esto a través de las publicaciones de nuestro [foro](https://devcommunity.x.com/t/a-new-easier-to-understand-twitter-developer-policy/135038) y [blog](https://blog.x.com/developer/en_us/topics/community/2020/twitter_developer_policy_update.html), y a revisar la política revisada. La Developer Policy es una de las bases para tu uso de la X API y es importante que entiendas tus compromisos.
### Lanzamiento del endpoint Hide Replies
Queremos ayudar a que las personas se sientan seguras y cómodas teniendo conversaciones en X. Como parte de esto, hoy nos complace dar a los autores de publicaciones más control sobre las conversaciones que inician al admitir la funcionalidad de hide replies con un nuevo [endpoint](/x-api/posts/hide-replies).
Puedes leer más sobre este nuevo endpoint en nuestro [anuncio del foro](https://devcommunity.x.com/t/introducing-the-hide-replies-endpoint/134683).
### Lanzamiento de los endpoints v2 de Labs
Hoy llevamos nuestros endpoints posts and Users, Recent Search y Hide Replies a la v2 de Labs. Estamos desusando los endpoints Labs v1 y los retiraremos completamente 90 días después de esta versión inicial. También mantendremos nuestra documentación v1 disponible durante esta duración. Puedes darnos comentarios sobre esta estrategia de versionado a través de nuestro [canal de feedback](https://twitterdevfeedback.uservoice.com/).
Estamos lanzando los siguientes cambios a posts and Users:
* Introducir [fields](/x-api/fundamentals/fields) como parámetro de consulta
* Eliminar [formats](https://developer.x.com/en/docs/labs#payload) como parámetro de consulta
* Añadir variable de ruta para búsqueda de ID único [lookup](https://developer.x.com/en/docs/labs/overview/versioning/migration-guide#id-lookup-path) en posts and Users
* Ajustar la ruta y los parámetros de consulta para búsqueda de nombre de usuario único y múltiple [lookup](/x-api/migrate/overview#username-lookup-path) en GET /users
* Cambiar el nombre del campo `stats` a `public_metrics`
Otros cambios incluyen:
* Eliminar la expansión `most_recent_tweet_id` en Users
* Eliminar las etiquetas HTML del campo `source` en posts para facilitar el análisis de ese campo
La funcionalidad central de búsqueda, paginación y otras funcionalidades de Recent Search permanecerán igual.
Hemos preparado algunos [materiales de migración](/x-api/migrate/overview) para cuando actualices de v1 a v2.
Puedes leer más sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/releasing-a-new-version-of-labs-endpoints/134219).
### Adición de eventos Drop/Undrop al Compliance Firehose
Hoy añadimos nuevos tipos de eventos drop/undrop al Compliance Firehose API. Puedes leer más sobre ellos en nuestra [documentación.](/x-api/enterprise-gnip-2.0/fundamentals/firehouse)
### Cambios a la gestión de Access Tokens
Hoy realizamos cambios en la forma en que se presentan y gestionan los Access Tokens y Access Token Secrets dentro del [panel de aplicaciones en developer.x.com](https://developer.x.com/content/developer-twitter/en/apps).
Para hacer las integraciones de API más seguras, ya no mostraremos el Access Token y Access Token Secret en el panel más allá de la primera vez que se generen estos valores.
Después de la primera vez, estas credenciales no podrán recuperarse. Podrás regenerar los tokens en el panel, pero esto invalidará tu token y secreto actuales.
Puedes leer más sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/upcoming-changes-to-access-token-and-secret-management/130851).
### Eliminación del soporte para SPDY
A partir del 15 de enero de 2020, todas las conexiones a la X API (y todos los demás dominios de X) ya no soportarán conexiones SPDY.
Puedes leer más sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/removing-support-for-spdy-protocol-on-twitter/132530).
### Lanzamiento del endpoint Recent Search en Labs
Hoy lanzamos un nuevo endpoint para [buscar publicaciones publicadas en los últimos 7 días](/x-api/posts/recent-search).
Más información sobre este lanzamiento a través de nuestro [anuncio del foro.](https://devcommunity.x.com/t/new-recent-search-endpoint-available-in-labs/133076)
### Actualización a Twurl CLI
Una nueva versión mayor actualizada de nuestra X API CLI, `[twurl](https://github.com/twitter/twurl)`, ahora está disponible. Esta versión incluye varias correcciones de errores y mejoras, e introduce soporte para Bearer Token que ayuda a añadir funcionalidad alrededor de los endpoints Premium y X Developer Labs. Más información en nuestra [publicación del foro](https://devcommunity.x.com/t/twurl-0-9-5-released/132966).
### Adición de Post Annotations en Streams
Hoy en X Developer Labs, lanzamos nuevos elementos de metadatos al payload predeterminado de post. Estos nuevos campos, renderizados como parte del payload del post, proporcionarán más información contextual sobre el post.
Más información sobre este lanzamiento a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/tweet-annotations-added-to-the-tweet-object-for-the-sampled-stream-and-filtered-stream-endpoints-in-labs/132407).
### Actualizaciones a los perfiles de usuario de Historical PowerTrack
Hoy actualizamos nuestro endpoint «batch historical posts» (Historical PowerTrack) para proporcionar información de ubicación del perfil de usuario, descripción biográfica y nombre que reflejan los valores vigentes en el momento del procesamiento del trabajo. Cuando se entreguen los objetos de usuario actualizados, habrá un nuevo array de cadenas «updated» en el objeto User/Actor.
Hay hasta tres valores posibles: name, description, location:
`"updated": ["name", "description", "location"]`
Consulta la [documentación sobre el formato de datos de Historical PowerTrack](https://aem-author-production-version-6-3.twitter.biz/content/developer-twitter/en/docs/tweets/batch-historical/guides/powertrack-data-format.html) para más detalles.
### Adición a Account Activity API
Hoy lanzamos una nueva función a Account Activity API que proporcionará a los desarrolladores la capacidad de ver si una cuenta que menciona a tu usuario suscrito está bloqueada.
Puedes leer más sobre la [estructura del objeto de datos](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure) `user_has_blocked` y consultar nuestro [anuncio del foro](https://devcommunity.x.com/t/new-release-account-activity-api-user-has-blocked-field/131157) para más detalles.
### Lanzamiento del endpoint Sampled Stream en Labs
Hoy lanzamos un nuevo endpoint para [transmitir una muestra de todas las publicaciones públicas](/x-api/posts/recent-search) en tiempo real, según se publican.
Más información sobre este lanzamiento a través de nuestro [anuncio del foro.](https://devcommunity.x.com/t/new-sampled-stream-endpoint-available-in-labs/130958)
### Lanzamiento del endpoint Filtered Stream en Labs
Hoy lanzamos un [nuevo endpoint de streaming](/x-api/posts/filtered-stream) para recuperar publicaciones, y un endpoint para administrar tus filtros en X Developer Labs. Con estos endpoints, podrás recuperar hasta 500,000 publicaciones por mes (máximo 50 publicaciones por segundo); puedes establecer hasta 10 reglas de filtro en tu stream (estas pueden aplicarse al mismo tiempo).
Más información sobre este lanzamiento a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/new-filtered-stream-endpoints-available-in-labs-and-the-future-of-statuses-filter/129888).
Los parámetros de solicitud documentados en las páginas de referencia de API ahora están claramente marcados como opcionales o requeridos. Adicionalmente, las páginas de referencia de API describirán un payload de cuerpo JSON cuando esto sea permitido por una solicitud.
### Lanzamiento de Post Metrics en Labs
Ahora puedes recuperar datos de engagement de cualquier publicación o lista de publicaciones de cuentas propias/autorizadas. Las publicaciones que consultes no deben tener más de 30 días de antigüedad y no pueden ser reposts.
[GET /tweets/metrics/private](https://developer.x.com/en/docs/labs/tweet-metrics/overview.html) admite las siguientes métricas:
* `impressions`
* `reposts`
* `quotes`
* `likes`
* `replies`
* `video views`
* `video view quartiles` (cuando el solicitante es también el autor del medio)
Más información sobre este lanzamiento a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/new-twitter-developer-labs-release-metrics-endpoint/129122).
### Cambios en los permisos de DM
A partir de hoy, las aplicaciones que necesiten crear Direct Messages deberán tener los permisos de aplicación «Read, Write, and Direct Messages» (RW+DM). Las aplicaciones que intenten crear Direct Messages con solo el permiso de aplicación RW recibirán el siguiente error:
`{"code": 93,"message": "This application is not allowed to access or delete your direct messages."}`
Puedes obtener más información sobre este cambio a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/updates-to-app-permissions-direct-message-write-permission-change/128221).
### Adición de la expansión Pinned Post
`pinned_tweet_id` expandirá el post fijado de un usuario a través de nuestra expansión del objeto user.
### Adición de metadatos de Quote Counts
Los desarrolladores pueden usar los nuevos endpoints Labs para extraer conteos de citas.
### Adición de la expansión Most Recent Post
`most_recent_tweet_id` expandirá el post más reciente de un usuario a través de nuestra expansión del objeto user.
Más información sobre este lanzamiento a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/update-to-twitter-developer-labs/128060).
### Requisito de TLS 1.2
Hoy, todas las conexiones a la X API (y todos los demás dominios de X) requerirán TLS 1.2.
Puedes leer más sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/removing-support-for-legacy-tls-versions-1-0-1-1-on-twitter/126648/2).
### Nuevo endpoint de Account Activity API
A partir de hoy, presentamos el nuevo [endpoint de Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference) para desactivar suscripciones de usuario usando OAuth solo de aplicación.
Este nuevo endpoint ofrece a los desarrolladores la conveniencia de solo tener que proporcionar un bearer token para desactivar una suscripción, sin requerir el access token del usuario suscrito.
Marcamos inmediatamente como en desuso el endpoint de Account Activity API enterprise existente usado para desactivar suscripciones de usuario con 3-Legged OAuth. El endpoint será retirado y dejará de estar disponible a partir del 15 de enero de 2020.
Los desarrolladores pueden obtener más información sobre esta API en nuestra [documentación](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference).
### Nuevas expansiones para el endpoint Tweets
Añadimos dos nuevas expansiones al endpoint \[GET /tweets][https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets.html](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets.html)):
`entities.mentions.username` expandirá el nombre de usuario de cualquier mención de usuario reconocida en una publicación a un objeto user completo.
`referenced_tweets.id.author_id` expande el ID del autor de cualquier publicación referenciada, cuando una de las publicaciones solicitadas es un repost, publicación citada o respuesta. Esta expansión también expandirá el ID del post referenciado a un objeto completo.
### Soporte para los endpoints Tweets y Users en Labs
Los primeros dos endpoints ahora están disponibles a través del portal Labs. Asegúrate de tener una cuenta de desarrollador aprobada y haber solicitado acceso a Labs para comenzar con estos endpoints.
Las [diferencias clave](https://developer.x.com/content/developer-twitter/en/docs/labs/overview/whats-new) respecto a la funcionalidad equivalente de v1.1 incluyen:
* Endpoint único para la función de objeto único «show» y «lookups» en lote
* \[Expansion parameters]) admite la inclusión de objetos adicionales como parte de una solicitud (por ejemplo, usuarios mencionados, publicaciones referenciadas, etc.)
* \[Format parameters]) admite diferentes proyecciones de datos con payloads más o menos verbosos
* El rate limiting es a nivel de aplicación, independientemente del método de autenticación (contexto de usuario o bearer token)
Más información sobre este lanzamiento a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/twitter-developer-labs-is-open-to-all-developers/126717).
### Retiro de los endpoints Terms y Privacy
Hemos retirado completamente los endpoints Terms of Service y Privacy. El estado actual de nuestra [Privacy Policy](https://x.com/en/privacy) y [Terms of Service](https://x.com/en/tos) se sirve mejor en nuestras páginas web actualizadas.
Puedes obtener más información sobre este cambio a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/terms-of-service-and-privacy-endpoints-will-no-longer-serve-content-after-june-10/125714).
### Cambios en los campos del objeto User
Hoy algunos campos del objeto user, incluyendo `user.lang`, comenzarán a devolver 'null' para los campos de metadatos actualizados anunciados previamente en nuestra [publicación del foro](https://devcommunity.x.com/t/upcoming-changes-to-user-object-and-get-users-suggestions-endpoints/124732).
Los desarrolladores pueden obtener información sobre este cambio a través de nuestra [documentación.](/x-api/fundamentals/data-dictionary/reference#user)
### Lanzamiento de Account Activity Replay API
A partir de hoy, presentamos la [Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity), una herramienta de recuperación de datos disponible con el nivel enterprise de la [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)
La [Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) te permite recuperar eventos de hasta cinco días atrás. Debe utilizarse para recuperar datos en escenarios donde tu servidor [webhook](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference) pierde eventos
Los desarrolladores pueden obtener más información sobre esta API en nuestra [documentación](/x-api/enterprise-gnip-2.0/fundamentals/account-activity).
### Soporte para medios nativos en Quotes
A partir de hoy, los medios nativos (fotos, videos y GIFs) pueden añadirse a quotes en X, lo que se mostrará como metadatos de medios adicionales en las secciones de entities de los payloads de quote.
Los desarrolladores pueden obtener más información sobre esto en nuestra [documentación](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/tweet).
### Adición del operador is:reply
Hoy, el operador `is:reply` está disponible para usar con los [enterprise search APIs](/x-api/enterprise-gnip-2.0/fundamentals/search-api) y la versión de pago de los [endpoints premium search](https://developer.x.com/content/developer-twitter/en/docs/tweets/search/api-reference/premium-search).
El operador booleano `is:reply` puede usarse para filtrar todas las respuestas a publicaciones, o para filtrar las respuestas explícitas que coinciden con una regla. Este operador funciona de la misma manera que el operador `is:quote`.
Recuerda que, con la Search API, todos los operadores 'is:' y 'has:' deben usarse junto con un operador independiente como una palabra clave o hashtag.
Puedes obtener más información sobre este operador en la [documentación](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering).
### Cambios en el enriquecimiento de Expanded URL
Hoy, el enriquecimiento de Expanded URL ya no contendrá el objeto unwound URL y los metadatos (incluidos los campos title y description) para URLs que enlacen a publicaciones, Moments o perfiles. Ten en cuenta que otras URLs (a sitios web, etc.) continuarán enriqueciéndose con estos metadatos, y url, expanded\_url y `display_url` seguirán estando disponibles. Este cambio aplica a [Decahose](/x-api/enterprise-gnip-2.0/fundamentals/decahose-api), [PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api), [Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview), y las [Search APIs](https://developer.x.com/en/docs/x-api/v1/tweets/search/overview).
### Adición del operador is:reply en PowerTrack
Hoy presentamos un nuevo operador, `is:reply`, para ayudarte a reducir las conversaciones a las que más te importan. Ahora puedes filtrar las respuestas de tus resultados (además de la capacidad preexistente de filtrar reposts, `is:retweet`, y publicaciones citadas, `is:quote`). Este nuevo operador está disponible hoy en [PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api), [Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview), y [Replay](/x-api/enterprise-gnip-2.0/powertrack-api#replay-api).
El operador booleano `is:reply` puede usarse para filtrar todas las respuestas a publicaciones, o para filtrar las respuestas explícitas que coinciden con una regla. Este operador funciona de la misma manera que el operador `is:quote`.
Puedes obtener más información sobre este operador en la [documentación](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering).
### Acceso a apps en Developer Console
Hoy hemos añadido la capacidad para que los desarrolladores vean y editen sus [X apps](/resources/fundamentals/developer-apps) existentes a través del [panel de X app](https://developer.x.com/content/developer-twitter/en/apps) en developer.x.com siempre que estén conectados a su cuenta de X. Anteriormente, solo podías ver y editar tus X apps existentes en developer.x.com si habías solicitado o sido aprobado para una [cuenta de desarrollador](/resources/fundamentals/developer-portal).
Aún debes tener una cuenta de desarrollador aprobada para poder crear nuevas X apps.
### Soporte para subtítulos de video
Hoy anunciamos que los anunciantes y editores ahora pueden añadir archivos de subtítulos (SRT) a sus videos a través de ads.x.com, Media Studio y nuestra API de carga de publishers. Los subtítulos serán visibles en videos con reproducción automática (cuando no haya sonido disponible) en Android y Web. Liberaremos la funcionalidad para iOS en las próximas semanas.
Para leer más sobre los nuevos endpoints de subtítulos, revisa sus respectivas páginas de referencia de API:
* [POST media/subtitles-create](/x-api/media/create-media-subtitles)
* [POST media/subtitles-delete](/x-api/media/delete-media-subtitles)
### Actualización del endpoint Account Activity API
Hoy anunciamos una actualización del endpoint [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity), [GET subscriptions/count](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count). Para permitir una mayor visibilidad de tus detalles de facturación y uso de la API, a partir de hoy, puedes obtener de forma programática el número de suscripciones aprovisionadas asociadas con tu instancia de Account Activity API dentro del JSON. Esto significa que ahora puedes ver tanto cuál es tu número aprovisionado de suscripciones como cuán cerca estás de alcanzar ese límite a través del endpoint API GET subscriptions/count.
Esta actualización ha sido documentada con la [documentación de Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count).
### Nuevos rate limits en endpoints POST
Hoy estamos implementando nuevos rate limits a nivel de aplicación en varios de nuestros endpoints estándar POST:
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet/:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweets-id)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
Puedes leer más sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/new-post-endpoint-rate-limit-enforcement-begins-today/115355).
### Actualización a la biblioteca twitter-text
Hoy anunciamos una actualización a la biblioteca [twitter-text](https://github.com/twitter/twitter-text) para contemplar los cambios recientes en la forma en que X cuenta los emojis. Si un emoji contaba previamente como más de dos caracteres, su conteo ahora se reducirá a solo dos caracteres para permitir que los usuarios aprovechen al máximo sus 280 caracteres.
Puedes leer más sobre este cambio en nuestro [anuncio del foro](https://devcommunity.x.com/t/new-update-to-the-twitter-text-library-emoji-character-count/114607).
### Retiro de los endpoints DM legacy
Hemos retirado completamente los endpoints legacy de Direct Message. Puedes encontrar una lista de los endpoints DM retirados, así como sus reemplazos en \[esta página]\([https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference).
Puedes obtener más información sobre esta actualización a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746).
### Cambios al acceso de medios en DM
Hoy estamos implementando algunos cambios al proceso para [recuperar medios adjuntos de Direct Messages](https://developer.x.com/en/docs/x-api/v1/direct-messages/message-attachments/overview). Ya no soportaremos acceder a `media_url` o `media_url_https` vía una sesión autenticada de [www.x.com](http://www.x.com). La solicitud para obtener `media_url_https` DEBE siempre estar firmada con el access token del usuario usando OAuth 1.0A.
Puedes obtener más información sobre esta actualización a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/direct-message-api-change-to-how-apps-can-access-images-sent-in-direct-messages/112722).
### Retiro de User y Site Streams
Hemos retirado completamente [User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) y [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction).
Puedes obtener más información sobre esta actualización a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746).
### Nueva versión de Usage API
Hoy lanzamos una nueva versión de Usage API. Con esta actualización, estamos haciendo la API más estable al migrar a un nuevo sistema.
Con la actualización del sistema, los usuarios experimentarán un «hueco» de datos ya que los desarrolladores solo podrán obtener datos hasta el 1 de mayo de 2018. Por lo tanto, durante el próximo año, perderán algunos meses de datos históricos (hasta junio de 2019).
Un nombre de producto cambia dentro de la Usage API de Historical PowerTrack Subscription a Historical PowerTrack 2.0, lo que hará que el nombre del producto sea consistente con el resto de nuestro lenguaje de cara al usuario. Los clientes recibirán exactamente los mismos datos en el mismo formato con la actualización. Verás este cambio dentro del objeto JSON `products.type`.
Si tienes alguna pregunta, contacta con tu administrador de cuentas.
### Desuso de API
El producto [Account Activity API DM Beta](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) fue retirado completamente hoy.
Los siguientes servicios y endpoints experimentarán servicio degradado a partir de hoy:
* [User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [GET direct\_messages](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/list-events)
* [GET direct\_messages/sent](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message)
* [GET direct\_messages/show](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-message)
* [POST direct\_messages/new](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/new-message)
* [POST direct\_messages/destroy](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message)
User Streams y Site Streams serán retirados completamente el 23 de agosto.
Los endpoints Direct Messages legacy serán retirados completamente el 17 de septiembre.
Puedes obtener más información sobre esta actualización a través de nuestro [anuncio del foro](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746).
### Cambios a la creación de apps y rate limits
A partir de hoy, ya no podrás crear nuevas [X apps](/resources/fundamentals/developer-apps) a través de [apps.x.com](https://apps.x.com/). Ahora serás redirigido a tu cuenta de [Developer Console](/resources/fundamentals/developer-portal) o, si aún no tienes una cuenta de Developer Console, a la página donde [puedes solicitar acceso](https://developer.x.com/content/developer-twitter/en/apply-for-access).
También anunciamos que implementaremos nuevos rate limits a nivel de aplicación a los siguientes endpoints POST el 10 de septiembre de 2018.
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-retweet-id)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-favorites-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
Finalmente, presentamos una nueva opción para que las personas reporten violaciones sospechadas de nuestras políticas de plataforma para que las revises.
Puedes obtener más información sobre todas estas actualizaciones a través de nuestra [publicación del blog](https://cli.re/g32qKr).
### Gestión de App en Developer Console
Si tienes una cuenta de [Developer Console](/resources/fundamentals/developer-portal), ahora puedes crear y administrar tus [X apps](/resources/fundamentals/developer-apps). Por favor lee nuestra \[publicación del foro]\([https://devcommunity.x.com/t/app-creation-and-management-now-available-in-the-Developer](https://devcommunity.x.com/t/app-creation-and-management-now-available-in-the-Developer) Console/107723) para más detalles.
### Cambios a Sign in with X y Account Activity
Hoy comenzamos a requerir que registres las [URLs de callback](/resources/fundamentals/developer-apps#callback-urls) que usas con el proceso Sign in with X. Puedes leer más sobre esta actualización [aquí](https://devcommunity.x.com/t/action-required-sign-in-with-twitter-users-must-whitelist-callback-urls/105342).
También anunciamos la adición de la actividad `tweet_delete_events` a Account Activity API. Esta nueva actividad se enviará para los correspondientes eventos eliminados para permitir a los desarrolladores proporcionar más fácilmente una experiencia conforme para sus clientes y usuarios de aplicación. Puedes leer más sobre esta nueva actividad en nuestra [publicación del foro](https://devcommunity.x.com/t/adding-delete-events-to-the-account-activity-api/106783) o en nuestra [documentación](/x-api/enterprise-gnip-2.0/fundamentals/account-activity).
### Actualizaciones a Terms y Policies
Hoy realizamos algunos cambios a nuestros [Terms of Service](https://x.com/en/tos), [Privacy Policy](https://x.com/en/privacy) y \[X Developer Agreement][https://developer.x.com/en/developer-terms/agreement-and-policy](https://developer.x.com/en/developer-terms/agreement-and-policy) que incluyen actualizaciones de privacidad, seguridad y protección de datos. Por favor lee nuestra [publicación del foro](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) para más detalles.
### Campos de zona horaria privados
Hoy, los valores de zona horaria en los objetos user de X se convirtieron en campos privados. A partir de ahora, todos\* los objetos de datos `time_zone` y `utc_offset` se devolverán como null. Por favor lee nuestra [publicación del foro](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) para más detalles.
\* Continuarán estando disponibles en el endpoint `account/settings`, solo para usuarios autenticados.
### Eliminación de datos Klout
Hoy, eliminamos todos los datos Klout de los payloads de post como parte de nuestras actualizaciones GDPR.
### Cambios a Profile Background y Account Activity
Hoy, estamos cambiando todas las instancias de `profile_background_image_url` y `profile_background_image_url_https` a sus valores predeterminados. Por favor lee nuestra [publicación del foro](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) para más detalles.
Además del cambio anterior, estamos añadiendo un nuevo campo a los payloads de [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) para hacer referencia a qué suscripción se entregó la actividad. Este objeto JSON se llama `for_user_id` e incluirá el ID del usuario suscrito que produjo esa actividad como su valor. Puedes ver algunos ejemplos de este nuevo objeto JSON en nuestra página de [objetos account activity](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure).
### Cambios a la representación de Quote Payload
Hoy estamos añadiendo un cambio en la forma en que se representarán las URLs en el payload de quote.
Estamos añadiendo una nueva entidad llamada «quoted\_status\_permalink» para asegurar que la publicación citada pueda ser referenciada y eliminaremos el enlace t.co del campo «text» de la publicación citada.
Con el nuevo formato, el enlace t.co ya no se añade al campo «text» de la publicación citada en el objeto «quoted\_status».
Además, ya no pondremos el t.co url, expanded\_url y display\_url de la publicación citada en la entidad 'urls'. En su lugar, estos se añadirán a un nuevo objeto «quoted\_status\_permalink» con atributos de URL «url», «expanded» y «display». Esto significa que el objeto «quoted\_status\_permalink» se reservará para el enlace t.co de vuelta a la publicación citada, mientras que el array «entities.urls» puede usarse para identificar cualquier enlace compartido dentro de la publicación original o quote.
Por favor lee nuestra [publicación del foro](https://devcommunity.x.com/t/updating-how-urls-are-rendered-in-the-quote-tweet-payload/105473) y la [documentación actualizada](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) para más detalles.
### Desuso de X Kit
El anuncio del desuso de [X Kit](https://developer.x.com/en/docs/x-for-websites), después del 31 de octubre de 2018 X Kit ya no será mantenido activamente. Por favor lee nuestra [publicación del blog](https://blog.x.com/developer/en_us/topics/tools/2018/discontinuing-support-for-twitter-kit-sdk.html) para más detalles.
### Actualizaciones de plataforma para GDPR
Hoy anunciamos varias actualizaciones a la plataforma relacionadas con GDPR. Por favor lee nuestra [publicación del foro](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603) para más detalles.
### Adición del objeto Additional Media Info
La adición de un nuevo objeto al payload de post – objeto `additional_media_info` – y también restringiendo algunos detalles de video (`video_info`) para publicaciones promocionadas donde los anunciantes han solicitado que limitemos la reproducción de video a clientes propiedad de X. Puedes encontrar información adicional sobre este cambio en el siguiente enlace: [Extended Entities Objects > publicación con video nativo](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities).
### Lanzamiento de Premium Full-Archive Search
Lanzamiento del [endpoint premium full-archive search](https://blog.x.com/developer/en_us/topics/tools/2018/access-the-full-history-of-tweets.html).
### Lanzamiento de Account Activity APIs
Lanzamos las Account Activity APIs Standard beta para ([All Activities](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)) y ([Direct Messages](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)). Más información sobre este lanzamiento [en nuestro blog](https://blog.x.com/developer/en_us/topics/tools/2017/announcing-more-functionality-to-improve-customer-engagements-on-twitter.html). Anunciamos el desuso de User streams y Site streams y la fecha de sunset del martes 19 de junio de 2018.
### Actualización a la biblioteca twitter-text
La versión 2.0 de twitter-text ahora está disponible [en GitHub](https://github.com/twitter/twitter-text). Esta actualización aborda el cambio en nuestro límite de caracteres que se lanzó el 7 de noviembre de 2017. Para obtener más información sobre esta actualización, por favor [visita nuestro foro](https://devcommunity.x.com/t/shipped-twitter-text-2-0/98577).
### Lanzamiento de las Premium APIs
Lanzamos las Premium APIs.
Estas nuevas APIs se basan en la calidad y estabilidad de nuestra plataforma de datos enterprise, y la hacen disponible más ampliamente a través de un modelo de precios escalonado. Por primera vez, puedes comenzar a buscar a través de 30 días de publicaciones (en lugar de los 7 días limitados de datos en el endpoint estándar), y opcionalmente, también puedes acceder a nuestros enriquecimientos premium para profile geo, expansión de URL y datos de encuestas. Aquí hay un vistazo de algunas de las nuevas funcionalidades:
* Más publicaciones por solicitud (Sandbox + Premium)
* Un lenguaje de consulta mucho más rico que permite consultas más complejas (Sandbox + Premium)
* Un endpoint counts que devuelve conteos de series temporales de publicaciones (Premium)
* Enriquecimientos de metadatos, como Expanded URLs y Profile Geo (Premium)
Más información sobre este lanzamiento [en nuestro blog](https://blog.x.com/developer/en_us/topics/tools/2017/introducing-twitter-premium-apis.html).
### Lanzamiento de publicaciones de 280 caracteres
Lanzamiento oficial de publicaciones de 280 caracteres en idiomas donde el cramming era un problema. Por favor consulta nuestro [anuncio del foro](https://devcommunity.x.com/t/updating-the-character-limit-and-the-twitter-text-library/96425) o la [publicación del blog](https://blog.x.com/official/en_us/topics/product/2017/tweetingmadeeasier.html) oficial para más referencia.
### Eliminación de comandos DM en Statuses/Update
La capacidad de enviar Direct Messages a través del endpoint API `statuses/update` se ha eliminado completamente, y los parámetros `enable_dm_commands` y `fail_dm_commands` ya no tendrán efecto. Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653 "en nuestro foro").
### Cambios al flujo de OAuth Login
Se realizó un cambio en los endpoints de la API OAuth del backend de X que alteró el comportamiento del endpoint `/oauth/authenticate` para coincidir con el del endpoint `/oauth/authorize`. Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/recent-changes-to-twitter-s-oauth-login-flow-and-api-endpoints/94943).
### Actualizaciones a las métricas de Engagement API
La Engagement API se actualizó para usar la misma metodología de agregación de métricas en uso por el panel de analítica de X. Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/changes-to-the-engagement-api/94523).
### Cambios a la falla de comandos DM
El valor predeterminado del parámetro `fail_dm_commands` dentro del endpoint DM `statuses/update` se ha cambiado a *true*. Todas las actualizaciones de estado destinadas como Direct Messages comenzarán a devolver errores (a menos que `enable_dm_commands` sea *false*, en cuyo caso la publicación se publicará). Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653).
### Tratamiento de tweets de 280 caracteres
El payload de respuesta para tweets de 280 caracteres se tratará de la misma manera que los tweets largos. Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/testing-280-characters-for-certain-languages/94126).
### Adición de Additional Media Info
Añadiendo nuevos datos al payload de post (`additional_media_info object`) y también restringiendo algunos detalles de video (`video_info`) para publicaciones promocionadas donde los anunciantes han solicitado que limitemos la reproducción de video a clientes propiedad de X. Puedes encontrar información adicional sobre este cambio en el siguiente enlace: [Extended Entities Objects > publicación con video nativo](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities)
### Fin del soporte para el operador url\_contains en 30-Day Search
30-Day y Full-Archive Search terminaron el soporte para el operador `url_contains:`. El desuso de este operador se anunció como parte de la migración Gnip 2.0 en agosto de 2016. Cualquier consulta de Search que use el operador `url_contains:` será rechazada como inválida.
### Próxima eliminación del operador url\_contains en las Search APIs
La 30-Day Search API (tanto 30-Day como Full-Archive) ya no admitirá el operador `url_contains:` a partir de 30 días desde hoy, o después del 4 de agosto de 2017 (el soporte de `url_contains:` realmente terminará con el primer despliegue después de esa fecha). El desuso de este operador se anunció como parte de la migración Gnip 2.0 en agosto de 2016. Cuando termine el soporte del operador, cualquier consulta que use `url_contains:` será rechazada como inválida.
### Retiro de xAuth
El mecanismo de autenticación xAuth ha sido eliminado de todas las X APIs. Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/retirement-of-xauth/88022).
### Encabezados HTTP forzados a minúsculas
Todos los encabezados HTTP han sido forzados a minúsculas (`content-type`, `x-rate-limit-remaining`, `x-access-level`, etc.). Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/upcoming-http-header-changes/86715).
### Parámetros opcionales para comandos DM
El parámetro opcional `enable_dm_commands` para `statuses/update` permitirá a las aplicaciones eliminar el soporte de comandos DM temprano, antes de que finalice el período de transición. El valor predeterminado es *true* (es decir, el comportamiento legacy actual), pero esto puede establecerse en *false* para obtener el nuevo comportamiento posterior al 1 de noviembre. El parámetro opcional `fail_dm_commands` para `statuses/update` hará que los comandos DM devuelvan HTTP 403 (código de error 151) desde la API cuando se establece en *true*. El valor predeterminado es *false*. Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653).
### Soporte para emojis en reglas
Las reglas con emojis ahora están disponibles en las Search APIs enterprise
### Mayor disponibilidad de las Direct Message APIs
El acceso a varias nuevas Direct Message APIs ahora está más ampliamente disponible. Lee más sobre esta actualización [en nuestro blog](https://blog.twitter.com/developer/en_us/topics/tools/2017/new-apis-to-power-the-future-of-customer-engagement-in-direct-me.html).
### Retiro del soporte de video MPEG-DASH
Las URLs MPEG-DASH (.mpd) han sido eliminadas del payload de una publicación que contiene video. Lee más sobre esta actualización [en nuestro foro](https://devcommunity.x.com/t/retiring-mpeg-dash-video-support-on-march-9th-2017/82761).
### Nuevos enriquecimientos y cambios en payload
¡Nuevo enriquecimiento! Poll Metadata ahora está disponible a través de nuestras APIs enterprise. Consulta la [documentación](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) para más detalles.
Nuevo campo de payload: el campo Image Alt-Text (description) puede estar presente en las secciones `entities.media[]` y `extended_entities.media[]` del payload si un usuario elige la opción «Add description» al añadir una foto a una publicación. Esto está disponible solo en formato nativo enriquecido.
Formato de payload predeterminado: los streams recién creados en productos Gnip ahora tendrán por defecto JSON en formato original.
### Actualizaciones a Historical PowerTrack y Replay API
Historical PowerTrack API y Replay API
* el filtrado de citas ahora está soportado
* Las publicaciones citadas ahora están completamente rehidratadas dentro de los payloads de HPT y Replay
### Nuevos campos de payload para Counts
Nuevos campos de payload: `quote_count` y `reply_count` ahora están disponibles en payloads de formato nativo enriquecido a través de las APIs Realtime e Historical
### Soporte para operadores Geo en Full-Archive Search
Full-Archive Search API (FAS):
* Se añadió soporte para operadores geo adicionales:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
### Gestión de reglas por ID en PowerTrack
La gestión de reglas (GET y DELETE) por ID de regla ahora está disponible para PowerTrack 2.0 y PowerTrack Replay 2.0
### Soporte para operadores Geo en 30-Day Search
30-Day Search API:
* Se añadió soporte para operadores geo adicionales:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
# Directrices para desarrolladores
Source: https://docs.x.com/es/developer-guidelines
Políticas y directrices de la X API: casos de uso permitidos, comportamientos restringidos, requisitos de cumplimiento y mejores prácticas para apps.
**Las infracciones pueden resultar en la suspensión de la app, la revocación del acceso a la API o el baneo permanente de la cuenta.** Revisa siempre las políticas oficiales antes de construir.
Términos legales vinculantes para el acceso a la API
Reglas para construir en X
Reglas específicas para bots
Actividades prohibidas
***
## Verificación rápida: ¿está permitida mi app?
Antes de construir, hazte estas preguntas. Si respondes **"no"** a alguna de ellas, es probable que tu app infrinja las políticas de X.
Para las interacciones, ¿el usuario lo **solicitó explícitamente**?
¿El propósito y el comportamiento de tu app son **claros para los usuarios**? (Las cuentas automatizadas deben estar etiquetadas).
¿Pueden los usuarios **darse de baja fácilmente** de cualquier interacción en curso?
¿Ofrece **valor real** más allá de la autopromoción?
¿Estás **usando únicamente la API oficial** (sin scraping ni automatización del navegador)?
¿Estás **dentro de los límites de tasa** y respetando las políticas de uso?
En caso de duda, pregúntate: "¿Estaría un usuario contento con esta experiencia?" Si no, reconsidera tu enfoque.
***
## Escenarios comunes: ¿permitido o no?
Ejemplos reales para ayudarte a entender qué está permitido. **Estas reglas aplican a todas las apps**, ya sea que estés construyendo un bot, una app móvil, una integración web, una extensión de navegador, un panel de analítica o cualquier otra herramienta que use la X API.
| Escenario | ¿Permitido? | Por qué |
| ---------------------------------------------------------------------------------- | :--------------------------: | ---------------------------------------------------------- |
| Cuenta automatizada publica contenido programado (noticias, clima, citas) | | Informativo, sin menciones no solicitadas |
| La app publica actualizaciones de un feed RSS en nombre del usuario | | Difusión útil |
| Servicio de alertas publica notificaciones de terremotos o desastres | | Valor de seguridad pública |
| App deportiva publica actualizaciones de partidos en la timeline del usuario | | Informativo |
| La app publica precios de acciones o criptomonedas según un calendario | | Informativo, sin manipulación |
| La app publica contenido idéntico en varias cuentas | | Spam / manipulación de la plataforma |
| La app publica en temas tendencia para ganar visibilidad | | Manipulación de tendencias |
| Varias cuentas de alertas específicas por ciudad (p. ej., @WeatherNYC, @WeatherLA) | | Permitido: contenido no duplicado, específico de ubicación |
| Escenario | ¿Permitido? | Por qué |
| --------------------------------------------------------------------------- | :----------------------------------: | -------------------------------------------------------------------------------------------------- |
| La app responde a @menciones que piden ayuda | | Solicitud iniciada por el usuario |
| La app responde automáticamente a cualquiera que mencione una palabra clave | | Interacción no solicitada |
| La app responde automáticamente a usuarios que responden a tu post | | El usuario interactuó primero: límite de 1 respuesta. [Aplican condiciones](#gray-areas-explained) |
| App con IA genera y publica respuestas | | Requiere **aprobación previa** de X |
| La app responde con "¡sígueme para más!" a usuarios al azar | | Spam, no solicitado |
| App de utilidad que despliega hilos cuando se la menciona | | Utilidad iniciada por el usuario |
| Escenario | ¿Permitido? | Por qué |
| --------------------------------------------------------------------------------- | :--------------------------: | -------------------------------------------------------------------------------------- |
| La app responde a DMs con información útil | | Iniciado por el usuario |
| La app envía enlaces de afiliados cuando el usuario envía DM primero | | Iniciado por el usuario: debe divulgarse. [Aplican condiciones](#gray-areas-explained) |
| La app envía DMs automáticos a los nuevos seguidores con un mensaje de bienvenida | | No solicitado, incluso a seguidores |
| La app envía DMs masivos sobre el lanzamiento de un producto | | Spam |
| Integración de soporte pregunta "¿Cómo puedo ayudar?" después del DM del usuario | | Conversación iniciada por el usuario |
| Escenario | ¿Permitido? | Por qué |
| -------------------------------------------------------------------------- | :--------------------------: | ---------------------------------------------------------------------------------------- |
| App de terceros permite al usuario tocar un botón de "me gusta" en un post | | Iniciado por el usuario a través de la app |
| La app da likes automáticamente a posts con un hashtag | | Automatizado, no iniciado por el usuario |
| App móvil tiene función de "auto-like" para usuarios seleccionados | | Automatizado, no iniciado por el usuario |
| Servicio vende likes u ofrece paquetes de "likes masivos" | | Vender interacciones está prohibido |
| La app republica contenido desde una lista curada | | OK con fines informativos, sin spam masivo. [Aplican condiciones](#gray-areas-explained) |
| Herramienta de crecimiento sigue cuentas en masa para ampliar audiencia | | Manipulación |
| La app sigue de vuelta a cualquiera que la siga | | Seguimiento masivo o agresivo |
| La app agrega usuarios a listas en masa | | Manipulación indiscriminada de listas |
**Los likes deben iniciarse directamente por el usuario autenticado.** Dar likes de forma automatizada, masiva o indiscriminada — incluyendo el auto-liking por palabra clave, hashtag, usuario o calendario — está prohibido. Las apps no pueden ofrecer funciones de "auto-like" ni vender likes como servicio. Esto aplica a todas las apps: bots, apps móviles, extensiones de navegador o cualquier integración.
| Escenario | ¿Permitido? | Por qué |
| ------------------------------------------------------------------- | :----------------------------------: | ---------------------------------------------------------------------------------------------------------- |
| La app envía recomendaciones de productos cuando se le pregunta | | Iniciado por el usuario |
| La app responde a posts al azar con enlaces de afiliados | | Spam no solicitado |
| App de sorteos que requiere seguir/retuitear para participar | | Riesgoso: puede considerarse manipulación de interacción |
| Servicio que vende likes, follows o retweets | | Estrictamente prohibido |
| Servicio de propinas que envía cripto cuando el usuario lo solicita | | Iniciado por el usuario: cumple con regulaciones financieras. [Aplican condiciones](#gray-areas-explained) |
| Escenario | ¿Permitido? | Por qué |
| ------------------------------------------------------------------------ | :--------------------------: | ------------------------------------ |
| La app rastrea menciones de marca para un panel de analítica | | Caso de uso válido |
| La app hace scraping de X mediante automatización del navegador (no API) | | **Suspensión permanente**: solo API |
| La app almacena datos de X para entrenar modelos de IA/ML | | Prohibido (excepto Grok) |
| La app redistribuye más de 1.5M de posts en 30 días | | Supera los límites de redistribución |
| La app compara el rendimiento de X con la competencia | | Análisis competitivo prohibido |
| Investigación académica sobre tendencias de la conversación pública | | Válido con manejo adecuado de datos |
**La automatización fuera de la API (scraping, automatización del navegador) resulta en suspensión permanente.** Usa siempre la X API oficial.
***
## Actividades prohibidas
Estas actividades causarán la suspensión o el baneo permanente de tu app. No hay excepciones.
| Categoría | Ejemplos |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| **Spam y manipulación** | Contenido idéntico en varias cuentas, interacción falsa, manipulación de tendencias, publicación masiva |
| **Contacto no solicitado** | Respuestas automáticas a usuarios al azar, DMs masivos, @menciones no invitadas |
| **Bots engañosos** | Suplantar a humanos, ocultar la identidad de bot, enlaces/redirecciones engañosos |
| **Venta de interacciones** | Apps que venden likes, follows, retweets o vistas |
| **Abuso de límites de tasa** | Superar los límites, diseñar apps que fomenten el uso excesivo |
| **Automatización fuera de la API** | Scripts en navegador, scraping, cualquier automatización fuera de la API oficial |
| **Granjas de cuentas** | Varias cuentas para el mismo propósito duplicado |
| **Vigilancia** | Perfilado, rastreo o monitoreo de usuarios sin consentimiento |
| **Entrenamiento no autorizado de IA** | Usar datos de X para entrenar modelos de ML (excepto Grok) |
| **Derivación de datos sensibles** | Inferir atributos de salud, políticos, religiosos u otros sensibles |
| **Redistribución excesiva** | Compartir más de 1.5M de Post IDs por período de 30 días |
***
## Reglas de automatización
Esta sección se aplica específicamente a **cuentas automatizadas** (bots) que publican, responden o interactúan en nombre de los usuarios. Si estás creando un panel de analítica, una herramienta de investigación u otra app no automatizada, estos requisitos de etiquetado no aplican a ti, pero las restricciones técnicas sí.
### Requisitos para cuentas automatizadas
Todas las cuentas automatizadas que utilicen la X API deben cumplir con estos requisitos:
Esta etiqueta aparece bajo el nombre/handle del bot en su perfil. Habilítala en la configuración de tu app para garantizar transparencia.
Indica claramente que se trata de un bot y quién lo opera. Ejemplo: *"Bot de @tuempresa"* o *"Cuenta automatizada gestionada por Example Inc."*
Por motivos de responsabilidad y contacto, tu bot debe estar asociado con una cuenta gestionada por una persona.
Si un usuario dice "detener", detente. Implementa detección de palabras clave para frases comunes de opt-out.
Nada de scraping, automatización del navegador o métodos no oficiales. Las infracciones causan suspensión permanente.
No intentes eludir ni abusar de los límites de tasa. Diseña tu app para manejar los límites de forma adecuada.
### Acciones automatizadas: ¿qué está permitido?
| Acción | ¿Permitido? | Reglas |
| -------------------------- | :----------------------------------: | ------------------------------------------------------------------------------------------------------------ |
| **Publicar tweets** | | Sin @menciones no solicitadas. Sin publicaciones cruzadas idénticas. |
| **Responder a usuarios** | | Solo si el usuario interactuó primero. Máx. **1 respuesta por interacción**. |
| **Enviar DMs** | | Solo después de que el usuario te envíe un DM. Opt-out fácil obligatorio. |
| **Dar like a posts** | | Debe ser iniciado directamente por el usuario. Auto-liking, liking masivo y venta de likes están prohibidos. |
| **Republicar** | | OK con fines informativos/de entretenimiento. Sin spam masivo. |
| **Quote tweet** | | Mismas reglas que repost: sin spam ni manipulación. |
| **Seguir/Dejar de seguir** | | Sin seguimientos masivos, agresivos ni automatizados. |
| **Agregar a listas** | | Sin adiciones masivas ni indiscriminadas. |
| **Marcadores** | | Apto para uso personal/automatizado. |
| **Buscar/Leer** | | Uso estándar dentro de los límites de tasa. |
***
## Zonas grises explicadas
Muchos desarrolladores tienen dudas sobre casos límite. Aquí hay orientación sobre las zonas grises más comunes.
**Permitido si:**
* El usuario lo solicita explícitamente (p. ej., envía DM pidiendo una recomendación)
* Divulgas claramente la relación de afiliación/patrocinio
* Los enlaces no son engañosos (sin redirecciones engañosas)
**No permitido si:**
* Respondes automáticamente a posts al azar con enlaces de afiliados
* Envías DMs a usuarios que no lo pidieron
* Ocultas la relación comercial
* **Requiere aprobación previa de X** antes del despliegue
* Aún debe cumplir todas las reglas (sin menciones no solicitadas, debidamente etiquetadas)
* Contacta a X mediante el [formulario de soporte de políticas](https://help.x.com/forms/platform) antes de lanzar
* Incluso con aprobación, no puede suplantar a humanos
Desplegar respuestas generadas por IA sin aprobación es una infracción, incluso si el contenido es útil.
**No permitido** como DMs automatizados: cuenta como contacto no solicitado, aunque te hayan seguido.
**Alternativas:**
* Tweet fijado dando la bienvenida a los nuevos seguidores
* Bio con información introductoria y enlaces
* Auto-respuesta solo si te envían DM primero
**Permitido si:**
* Cada cuenta sirve a propósitos **no duplicados** (p. ej., @EarthquakeJP, @EarthquakeCA)
* El contenido es significativamente distinto (específico por ubicación, idioma)
* No se usa para eludir límites o amplificar el mismo mensaje
**No permitido si:**
* Publicas contenido idéntico/similar en varias cuentas
* Se crearon para evadir suspensiones o límites de tasa
**Permitido si:**
* El usuario inicia (te menciona, te envía DM o se da de alta explícitamente)
* Existe un mecanismo claro de opt-out
* Las respuestas son útiles, no promocionales
* Incluye un enlace a la política de privacidad en los DMs
**No permitido si:**
* Contactas a usuarios que se quejaron públicamente (no solicitado)
* Las respuestas son principalmente promocionales
**Procede con precaución:**
* Exigir follows/retweets como entrada puede considerarse manipulación de interacción
* Debe cumplir con las [directrices de concursos de X](https://help.x.com/en/rules-and-policies/x-contest-rules)
* No uses varias cuentas para amplificar
* Asegúrate de que los premios sean reales y se entreguen
Considera métodos de entrada que no requieran acciones de interacción, como responder con una frase específica.
***
## Requisitos de manejo y visualización de datos
Estos requisitos son legalmente vinculantes según el Acuerdo para Desarrolladores. El incumplimiento puede resultar en la terminación y en acciones legales.
### Eliminación de contenido
Debes eliminar el contenido de X de tus sistemas cuando se solicite:
| Desencadenante | Plazo |
| ----------------------------------------- | --------------------------------------------------------- |
| X solicita la eliminación | **24 horas** |
| El usuario solicita la eliminación | **24 horas** |
| El contenido es suspendido/eliminado en X | **24 horas** |
| Tu acceso a la API es terminado | **10 días hábiles** (debes eliminar todos los datos de X) |
Usa [Compliance Firehose](https://docs.x.com/x-api/compliance/streams) para recibir eventos de eliminación en tiempo real y cumplir con las normas automáticamente.
### Matching fuera de X
El **matching fuera de X** consiste en asociar datos de X (nombre de usuario, ID de usuario, posts) con identificadores fuera de la plataforma (tu base de datos de clientes, listas de correo, IDs de dispositivos, etc.).
**Permitido con consentimiento explícito (opt-in):**
* El usuario acepta explícitamente vincular su cuenta de X con tu servicio
* Divulgación clara de qué datos se harán coincidir y por qué
**Sin consentimiento, solo puedes hacer matching de:**
* Información que el usuario te proporcionó directamente
* Datos de X disponibles públicamente (posts, bio, nombre para mostrar, nombre de usuario)
* Recursos públicos como directorios profesionales
**Nunca hagas matching si sorprendería al usuario.**
### Datos sensibles
**No puedes** derivar, inferir ni almacenar información sobre usuarios de X en estas categorías:
| Categoría | Ejemplos |
| ---------------------------------- | --------------------------------------------------- |
| **Salud** | Condiciones médicas, embarazo, discapacidades |
| **Estado financiero** | Situación financiera negativa, problemas de crédito |
| **Político** | Afiliación a partidos, creencias políticas, voto |
| **Racial/Étnico** | Origen, etnia |
| **Religioso/Filosófico** | Creencias, afiliaciones |
| **Vida sexual/Orientación sexual** | Cualquier inferencia sobre la sexualidad |
| **Sindical** | Afiliación o pertenencia |
| **Penal** | Actividad delictiva presunta o real |
**Excepción:** El análisis agregado sin almacenar identificadores personales (sin IDs de usuario, nombres de usuario o datos vinculables) puede permitirse con fines de investigación, sujeto a las leyes aplicables.
### Visualización de contenido de X
| Requisito | Detalles |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| **Atribución** | Usa la marca X correctamente. Sigue las [Directrices de marca](https://about.x.com/en/who-we-are/brand-toolkit). |
| **Sin alteraciones** | Modifica solo para el formato de visualización (redimensionar). No edites el contenido, elimines marcas de tiempo ni quites metadatos. |
| **Sin iframes** | No muestres el contenido de X en iframes. Usa los embeds oficiales o renderiza directamente. |
| **Respeta las eliminaciones** | Elimina el contenido en un plazo de 24 horas si se elimina en X. |
***
## Restricciones técnicas
Estos límites aplican a todos los desarrolladores. Superarlos puede dar lugar a limitaciones de tasa o a la suspensión.
| Restricción | Límite |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| **Redistribución de Post IDs** | Máx. 1.5M de Post IDs por período de 30 días a una sola entidad |
| **Redistribución de contenido hidratado** | Máx. 50,000 Posts o Usuarios hidratados por destinatario por día |
| **Límites de tasa** | Varían según endpoint y nivel — [consulta los documentos de la API](/x-api/fundamentals/rate-limits) |
| **Entrenamiento IA/ML** | Prohibido (excepto para Grok) |
| **Acceso fuera de la API** | Prohibido: scraping y automatización del navegador = baneo permanente |
| **Benchmarking competitivo** | Prohibido: no se puede medir el rendimiento de X frente a competidores |
| **Múltiples apps para el mismo caso de uso** | Prohibido: no crees apps duplicadas para eludir límites |
### Casos de uso especiales
| Caso de uso | Requisito |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| **Uso gubernamental** | Requiere nivel Enterprise |
| **Uso comercial** | Requiere el nivel pagado apropiado; el nivel gratuito es solo no comercial |
| **Investigación académica** | Puede tener distintos límites de redistribución; contacta a X para más detalles |
| **Investigación bajo la Ley de Servicios Digitales de la UE** | Existen disposiciones específicas de investigación no comercial |
***
## Seguridad y cumplimiento
Tus obligaciones como desarrollador:
* Usa **prácticas de seguridad estándar de la industria** para proteger los datos de X
* Nunca compartas tus credenciales o tokens de la API
* Almacena las credenciales de forma segura (variables de entorno, gestores de secretos, no en el código)
* Implementa autenticación adecuada en tus apps
Si sufres una brecha de seguridad que involucre datos de X:
* **Notifica a X inmediatamente**
* Toma medidas para mitigar la brecha
* Coopera con la investigación de X
* Trata como confidencial cualquier información no pública de X
* No divulgues límites de tasa de la API, datos internos de X ni funciones no públicas
* No uses información confidencial con fines competitivos
* X puede auditar tu cumplimiento **hasta una vez por año**
* Debes proporcionar acceso y documentación razonables
* Mantén registros de cómo usas los datos de X
***
## Resumen: lo que debes y no debes hacer
**Para cuentas automatizadas:**
* Habilita la etiqueta de perfil "Automatizada"
* Divulga al operador en la bio
* Espera a que los usuarios inicien la interacción
* Proporciona un opt-out sencillo
* Obtén aprobación para respuestas generadas por IA
**Para todas las apps:**
* Usa únicamente la X API oficial
* Respeta los límites de tasa y de redistribución
* Elimina contenido en un plazo de 24 horas cuando se solicite
* Obtén consentimiento opt-in para el matching fuera de X
* Usa la atribución adecuada al mostrar contenido de X
* Asegura tus credenciales y notifica a X las brechas
* Mantén registros del uso de los datos de X
**Para cuentas automatizadas:**
* Ocultar la naturaleza automatizada
* Enviar DMs, respuestas o @menciones no solicitados
* Ignorar las solicitudes de "detener"
* Publicar contenido idéntico en varias cuentas
* Auto-likes, likes masivos o venta de likes (los likes deben iniciarse por el usuario)
**Para todas las apps:**
* Hacer scraping o usar automatización del navegador
* Entrenar modelos de IA/ML con datos de X (excepto Grok)
* Derivar datos sensibles de usuarios (salud, política, religión, etc.)
* Hacer matching de datos de X con IDs fuera de la plataforma sin consentimiento
* Mostrar contenido de X en iframes
* Redistribuir más de lo que permiten los límites
* Crear múltiples apps para el mismo caso de uso
* Usar datos de X para vigilancia o rastreo de usuarios
# Políticas y acuerdos
Source: https://docs.x.com/es/developer-terms
Políticas, acuerdos y requisitos de visualización para desarrolladores de X, que cubren el Acuerdo del Desarrollador, la Política del Desarrollador, el acuerdo de Ads API y los casos de uso restringidos.
## Descripción general
El uso de los materiales y contenido de X por parte de los desarrolladores está sujeto y regido por nuestra Política del Desarrollador y nuestros acuerdos.
# Acuerdo de Ads API
Source: https://docs.x.com/es/developer-terms/ads-api-agreement
El Acuerdo de Ads API de X regula el uso de los endpoints de publicidad de X, incluidas las integraciones permitidas, las restricciones y las obligaciones para los socios publicitarios.
Hemos actualizado nuestro Acuerdo de Ads API. Los cambios que se indican a continuación entran en vigor a partir del 23 de febrero de 2025.
## Acuerdo de Productos y Servicios de X Ads
**Fecha de entrada en vigor: 23 de febrero de 2025**
Este Acuerdo de Productos y Servicios de X Ads (el "**Acuerdo**") se celebra entre la entidad identificada en el formulario de solicitud del "Programa X Ads API" enviado a X por dicha entidad (o su representante autorizado) (denominada en el presente documento "**Empresa**") y X Corp., si la Empresa se encuentra fuera de la Unión Europea, los Estados de la AELC o el Reino Unido, incluso si su Empresa está en los Estados Unidos de América, o X Internet Unlimited Company, si la Empresa se encuentra en la Unión Europea, los Estados de la AELC o el Reino Unido, en nombre propio y de sus Afiliadas (según se definen a continuación) (en cualquier caso, "**X**") y rige el acceso y uso por parte de la Empresa de los Productos de Anuncios (según se definen a continuación). Tal como se utiliza en el presente documento, "**Afiliada**" se refiere a cualquier otra entidad que controle directa o indirectamente, sea controlada por, o esté bajo control común con X.
LEA CUIDADOSAMENTE LOS TÉRMINOS Y CONDICIONES DE ESTE ACUERDO, INCLUYENDO, SIN LIMITACIÓN, TODOS LOS ANEXOS ADJUNTOS Y CUALQUIER TÉRMINO Y CONDICIÓN VINCULADO QUE APAREZCA O SE REFERENCIE A CONTINUACIÓN, LOS CUALES SE INCORPORAN POR EL PRESENTE COMO PARTE DE ESTE ACUERDO. AL MARCAR LA CASILLA ETIQUETADA "Sí, acepto" Y HACER CLIC EN "ENVIAR" (O UN LENGUAJE QUE SEA EQUIVALENTE A "Sí, acepto", COMO POR EJEMPLO, "Acepto") O AL USAR LOS MATERIALES DE X, LA EMPRESA ACEPTA QUE HA LEÍDO, Y QUE ACEPTA CUMPLIR Y QUEDAR OBLIGADA POR, LOS TÉRMINOS Y CONDICIONES DE ESTE ACUERDO. SI LA EMPRESA NO ACEPTA QUEDAR OBLIGADA POR ESTE ACUERDO, LA EMPRESA NO PODRÁ ACCEDER NI UTILIZAR DE OTRO MODO LOS MATERIALES DE X. ESTE ACUERDO ENTRA EN VIGOR EN LA FECHA MÁS TEMPRANA DE: (I) LA FECHA EN QUE LA EMPRESA MARCA "Sí, acepto" Y HACE CLIC EN "ENVIAR" PARA ACEPTAR ESTE ACUERDO, O (II) LA PRIMERA FECHA EN QUE LA EMPRESA ACCEDE A LOS MATERIALES DE X ("**FECHA DE ENTRADA EN VIGOR**"). SI Y EN LA MEDIDA EN QUE, SIN EMBARGO, LA SOLICITUD DE LA EMPRESA PARA ACCEDER Y UTILIZAR LOS MATERIALES DE X NO SEA APROBADA POR X (A SU ENTERA Y ABSOLUTA DISCRECIÓN), ESTE ACUERDO SERÁ NULO, INVÁLIDO Y SIN EFECTO. SI USTED ES UN INDIVIDUO QUE REPRESENTA A LA EMPRESA, RECONOCE, DECLARA Y GARANTIZA QUE (A) HA LEÍDO Y ENTENDIDO ESTE ACUERDO, (B) TIENE LA AUTORIDAD ADECUADA PARA ACEPTAR ESTE ACUERDO EN NOMBRE DE LA EMPRESA, Y (C) ACEPTA, EN NOMBRE DE LA EMPRESA, LOS TÉRMINOS DE ESTE ACUERDO. USTED NO PODRÁ USAR LOS MATERIALES DE X NI ACEPTAR ESTE ACUERDO SI NO TIENE LA AUTORIDAD LEGAL PARA VINCULAR A LA EMPRESA, NO TIENE LA EDAD LEGAL O DE OTRO MODO NO PUEDE CELEBRAR UN CONTRATO VINCULANTE CON X, O SI TIENE PROHIBIDO UTILIZAR O RECIBIR LOS MATERIALES DE X CONFORME A LA LEY APLICABLE.
### 1. Introducción; Alcance; Términos de Producto Individual.
**1.1 Introducción.** X mantiene, opera y ofrece un conjunto de productos y servicios que habilitan diversas funcionalidades para los socios publicitarios de X. Los productos, servicios y programas específicos (cada uno, un "**Producto Individual**") que habilitan o están relacionados con estas funcionalidades son: (i) el Programa X Ads API (según se describe con más detalle en el [Anexo A](#Exhibit-A)); y (ii) el Programa de Audiencias Personalizadas de X (según se describe con más detalle en el [Anexo B](#Exhibit-B)). En conjunto, estos Productos Individuales se denominan en el presente documento los "**Productos de Anuncios**". Este Acuerdo rige el uso y/o acceso a los Productos de Anuncios colectivamente, y a los Productos Individuales de manera individual. Además, en la medida en que la Empresa participe en el programa X Marketing Partner ("**TMP**") en relación con un Producto de Anuncios cubierto por este Acuerdo, los términos y condiciones establecidos en el [Anexo C](#Exhibit-C) serán aplicables a la Empresa.
**1.2 Alcance.** Sujeto a este Acuerdo, durante el Plazo, la Empresa puede acceder y utilizar los Productos Individuales específicos a los que X le haya otorgado o proporcionado acceso. La Empresa no tiene obligación de utilizar todos o alguno de los Productos Individuales a los que X le haya otorgado o proporcionado acceso, y X no tiene la obligación de proporcionar (ni continuar proporcionando) a la Empresa el uso y/o acceso a ningún Producto Individual o función particular de los Productos de Anuncios. X puede otorgar o denegar el uso y/o acceso a cualquier Producto Individual, o a cualquier función del mismo, en cualquier momento a su entera discreción. En la medida en que la Empresa acceda o utilice cualquier función de los Productos de Anuncios, los términos de este Acuerdo regirán dicho acceso o uso. Para evitar dudas, este Acuerdo regirá exclusivamente el uso por parte de la Empresa de los Productos de Anuncios descritos en el presente documento. El acceso y uso por parte de la Empresa de cualquier dato, contenido u otros materiales proporcionados (directa o indirectamente) por X a la Empresa en virtud de un acuerdo independiente y/o en relación con un programa independiente de X se regirá en su totalidad por los términos y condiciones de dicho acuerdo y/o programa independiente (y no por los términos y condiciones de este Acuerdo), salvo que X y la Empresa acuerden lo contrario por escrito de mutuo acuerdo.
**1.3 Términos de Producto Individual.** Cada Producto Individual puede incluir términos y condiciones específicos que, además de y sin limitación de los términos de este Acuerdo, serán aplicables en la medida en que la Empresa acceda o utilice el Producto Individual correspondiente. El acceso de la Empresa a cualquier Producto Individual y/o los Materiales de X asociados (según se definen a continuación) está condicionado a la aceptación por parte de la Empresa de, y su cumplimiento con, los Términos de Producto Individual y cualquier limitación técnica sobre el acceso, las llamadas y el uso de los Productos Individuales. Los Términos de Producto Individual se adjuntan al presente como [Anexo A](#Exhibit-A) y [Anexo B](#Exhibit-B). X puede establecer y modificar dichas políticas o términos del Producto Individual a su entera discreción, según se establece en la Sección 15.15 a continuación.
### 2. Definiciones.
**2.1** "**Campaña**" significa una campaña publicitaria de escritorio, sitio web móvil o aplicación móvil, o una fracción de la misma.
**2.2** "**Cliente**" significa un anunciante de X (que también es cliente de la Empresa) que utiliza uno (1) o más de los Productos de Anuncios, según sea aprobado por X en cada caso.
**2.3** "**Marcas de la Empresa**" significa el nombre de la Empresa y cualquier logotipo, marca comercial y/o marca de servicio de la Empresa proporcionados por la Empresa a X para su uso conforme al presente (o autorizados de otro modo por la Empresa para el uso de X conforme al presente).
**2.4** "**Materiales de la Empresa**" significa cualquier dato, entregable o contenido de usuario de la Empresa proporcionado por la Empresa a X a través de los Productos de Anuncios.
**2.5** "**Servicio de la Empresa**" significa los sitios web, aplicaciones y otras ofertas de la Empresa que muestran o utilizan de otro modo Materiales de X o aspectos de los mismos.
**2.6** "**Datos**" significa métricas, datos y cualquier otra información y/o contenido que X ponga a disposición de la Empresa, incluidos los resultados, estadísticas de uso, datos u otra información (agregada o de otro modo) derivada del análisis o uso de cualquiera de los anteriores.
**2.7** "**Usuarios Finales**" significa un empleado o agente autorizado de un Cliente que utiliza los Productos de Anuncios en nombre de dicho Cliente.
**2.8** "**Marcas**" significa las Marcas de X y/o las Marcas de la Empresa, según sea el caso (con base en el contexto).
**2.9** "**Materiales**" significa los Materiales de X y/o los Materiales de la Empresa, según sea el caso (con base en el contexto).
**2.10** "**Datos Personales**" significa datos relacionados con un individuo vivo que sea o pueda ser identificado ya sea a partir de los datos o a partir de los datos en conjunto con otra información que esté, o pueda llegar a estar, en posesión del responsable del tratamiento.
**2.11** "**X Ads**" significa los productos y servicios publicitarios de X, incluida la colocación de anuncios en la Red de X.
**2.12** "**Código de X**" significa código informático que llamará (como mínimo) a un servidor de X, desarrollado por X y proporcionado a la Empresa.
**2.13** "**Marcas de X**" significa el nombre de X y cualquier logotipo, marca comercial y/o marca de servicio de X proporcionados por X a la Empresa para su uso conforme al presente (o autorizados de otro modo por X para el uso de la Empresa conforme al presente).
**2.14** "**Materiales de X**" significa cualquier dato, entregable o contenido de usuario de X (incluidos los derivados de los mismos) generado por X, y cualquier dato, entregable o contenido de usuario de X (incluidos los derivados de los mismos) generado, recopilado o desarrollado por X, o que sea proporcionado o puesto a disposición de la Empresa por X conforme a este Acuerdo, incluidos los datos derivados de, basados en, o que surjan de la asociación de la Empresa con X, o cualquier dato a nivel de dispositivo, o cualquier dato de conversión, interacción, seguimiento o segmentación que la Empresa o cualquier tercero aprobado por X recopile, infiera, derive u obtenga de o en relación con las campañas publicitarias de X de la Empresa. Para mayor claridad y sin limitación, "Materiales de X" incluye la X Ads API (según se define en el [Anexo A](#Exhibit-A)), el Código de X, los Datos, los Productos de Anuncios y cualquier ID de usuario de X utilizado para crear una Audiencia Personalizada (definida a continuación).
**2.15** "**Red de X**" significa la red de canales publicitarios, incluidas todas las formas de medios, aplicaciones y dispositivos, a través de los cuales X puede distribuir anuncios, en cualquier medio conocido actualmente o desarrollado en el futuro.
**2.16** "**Programa X Marketing Partners**" significa el programa de asociación y marca ofrecido por X, según se describe con más detalle en el [Anexo C](#Exhibit-C).
**2.17** "**Servicio de X**" significa: (i) los servicios de contenido e información en tiempo real operados por X, (ii) la tecnología y los sistemas que habilitan dichos servicios, lo que incluye, colectivamente, los productos y servicios para consumidores y publicidad actualmente proporcionados por X o en sus sitios web, y las aplicaciones móviles propiedad de, operadas y/o controladas por X y los plug-ins sociales y APIs, incluyendo, sin limitación, el Código de Medición, cualquier etiqueta HTML u otros códigos, portales de internet, paneles, sistemas y herramientas analíticas y servicios relacionados, y (iii) todos los demás productos o servicios ofrecidos por X y sus Afiliadas, incluyendo (sin limitación y a modo de ejemplo únicamente) la X Audience Platform y Data & Enterprise Solutions.
### 3. Gestión de X Ads/Campañas; Asunción de Responsabilidad.
**3.1 Gestión de X Ads/Campañas.** La Empresa puede tener acceso a uno o más Productos Individuales que le permitirán, a su entera discreción y/o bajo la dirección de los Clientes de la Empresa, optimizar, modificar, gestionar, iniciar o manipular X Ads en la Red de X, o de otro modo tomar decisiones de gestión y segmentación de anuncios (denominado en el presente documento "**Gestión de Campañas**"). Si la Empresa accede o utiliza dichos Productos Individuales: (a) la Empresa deberá proporcionar prontamente cualquier material publicitario que tenga la intención de publicar en la Red de X; y (b) la Empresa autoriza a X a colocar los materiales publicitarios de la Empresa y/o del Cliente en cualquier contenido o propiedad disponible a través del Producto Individual aplicable, ya sea que dicho contenido o propiedad se proporcione en la Red de X o a través de un tercero. La Empresa obtendrá las licencias y autorizaciones necesarias del Cliente correspondiente para que la Empresa pueda utilizar dichos materiales publicitarios en nombre de dicho Cliente. La Empresa no está obligada a utilizar ningún Producto Individual que permita la Gestión de Campañas, pero si la Empresa utiliza dichos productos, servicios o funciones, por el presente asume todo y cualquier riesgo, y acepta toda y cualquier responsabilidad y obligación que surja de o en relación con la Gestión de Campañas de la Empresa, incluidos, entre otros: (i) la creación y selección de audiencias, errores de ingreso de datos, selección de tácticas y los costos asociados de inventario, datos y otros terceros; (ii) las propiedades a las que los anuncios proporcionados por la Empresa dirijan a los espectadores (por ejemplo, páginas de destino) y cualquier redirección desde las mismas; (iii) los servicios y productos anunciados en cualquier página de destino; y (iv) cualquier Material de la Empresa asociado, incluyendo, sin limitación, los materiales publicitarios, la tecnología y/o la creatividad proporcionada a X. La Empresa reconoce y acepta que X no tendrá ninguna responsabilidad u obligación en relación con la Gestión de Campañas de la Empresa. Sin limitar la generalidad de lo anterior, X no será responsable, y la Empresa será la única responsable, de capacitar al personal de la Empresa en la Gestión de Campañas y en la funcionalidad de los Productos de Anuncios.
**3.2 Vinculación de los Clientes a estos Términos; Asunción de Responsabilidad.** Si la Empresa accede o utiliza los Productos de Anuncios (o cualquier aspecto de los mismos, incluida la Gestión de Campañas) en nombre de Clientes o cualquier otro tercero, la Empresa garantiza que: (i) está autorizada a actuar en nombre de dichos Clientes u otros terceros, y ha vinculado a dichos Clientes u otros terceros a las Políticas Aplicables (según se define en la Sección 6 a continuación), incluyendo el Acuerdo Maestro de Servicios de X aplicable ("**MSA**"), que regirá todas las compras de X Ads realizadas por la Empresa, y los términos de este Acuerdo que se aplican al acceso y uso de los Productos de Anuncios aplicables (o cualquier aspecto de los mismos) y (ii) será responsable de su cumplimiento y responderá por su incumplimiento.
### 4. Privacidad.
**4.1 Recolección Directa de Datos.** La Empresa declara y garantiza que (i) en caso de que la Empresa recopile datos de los usuarios directamente (incluyendo, sin limitación, en o a través del Servicio de la Empresa), ha proporcionado a dichos usuarios un aviso legalmente suficiente (incluyendo, sin limitación, publicando de manera visible una política de privacidad legalmente suficiente desde todos los sitios web, aplicaciones móviles y otros servicios desde los cuales se recopilan datos de los usuarios y/o se ponen a disposición de X que cumpla con todas las leyes y regulaciones aplicables, divulgue el hecho de que terceros recopilan información sobre las actividades de los usuarios en o a través de los sitios web, aplicaciones móviles y otros servicios relevantes (por ejemplo, navegar o comprar) con fines de publicidad basada en intereses, y proporcione a los usuarios instrucciones legalmente suficientes para que dichos usuarios puedan optar por no participar en la publicidad basada en intereses); (ii) ha obtenido todo el consentimiento informado legalmente exigido de dichos usuarios, incluyendo el relativo al uso por parte de la Empresa de cookies y/o píxeles de seguimiento en relación con dicha recopilación de datos; y (iii) los Materiales de la Empresa no contienen ni se refieren a, y los datos de audiencia proporcionados, puestos a disposición o importados por la Empresa a X no contienen ni se refieren a, ningún dato relativo a ningún(os) usuario(s) o sujeto(s) de datos que haya(n) ejercido la opción de no recibir publicidad basada en intereses.
**4.2 Datos Personales.** La Empresa declara y garantiza que la Empresa no conectará ni combinará, ni intentará conectar o combinar, cualquier Material de X, ya sea directa o indirectamente, con ningún Dato Personal ni con identificadores que a su vez estén directa o indirectamente asociados con cualquier Dato Personal. Además, la Empresa implementará salvaguardas razonables para prohibir que los Materiales de X sean vinculados a cualquier Dato Personal (ya sea directamente o por inferencia).
**4.3 Cumplimiento de la Privacidad.** La Empresa declara y garantiza que (i) no proporcionará a X Materiales de la Empresa relacionados con información sensible, incluyendo la presunta o real comisión de un delito, salud, situación o condición financiera negativa, afiliación o creencias políticas, origen racial o étnico, afiliación o creencias religiosas o filosóficas, vida sexual, o afiliación sindical, o recopilados de sitios web, aplicaciones móviles u otros servicios donde el producto, mensaje o servicio que se ofrece esté prohibido por las políticas de Anuncios de X ([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies)), y (ii) no (1) proporcionará a X ningún Material de la Empresa relativo a niños menores de trece (13) años, ni (2) enviará a X ningún Material de la Empresa u otros datos de un sitio web, aplicación móvil o servicio en línea dirigido a niños, según se define en la Children's Online Privacy Protection Act, actualmente en 16 CFR 312. La Empresa reconoce y acepta que cumplirá en todo momento con los términos del Adendum de Tratamiento de Datos de X ubicado en [https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa).
**4.4 Datos de Terceros.** La Empresa declara y garantiza que, en caso de que la Empresa esté obteniendo datos sobre los usuarios indirectamente de uno o más terceros (incluyendo, sin limitación, socios de datos y/o anunciantes, incluyendo, sin limitación, Clientes) para apoyar las obligaciones de desempeño de la Empresa frente a X en virtud de este Acuerdo, ha obligado contractualmente a cada uno de dichos terceros a los requisitos contenidos en este Acuerdo incluyendo, sin limitación, en esta Sección 4.
### 5. Propiedad; Licencia; Limitaciones y Restricciones.
**5.1 Propiedad.** Entre la Empresa y X, la Empresa conserva todos los derechos, títulos e intereses en todo el mundo sobre los Materiales de la Empresa, las Marcas de la Empresa y el Servicio de la Empresa, excluyendo cualquier Material de X, Marcas de X y Servicio de X (y cualquier trabajo derivado o mejora de los anteriores) incorporados en los mismos, incluyendo, entre otros, todos los derechos de propiedad intelectual sobre los mismos. Cualquier derecho no otorgado expresamente en el presente documento queda reservado. Entre la Empresa y X, X posee todos los derechos, títulos e intereses en todo el mundo sobre los Materiales de X, las Marcas de X y el Servicio de X y todas las mejoras futuras, desarrollos, mejoras, trabajos derivados y derechos relacionados basados en, relacionados con, derivados de, o asociados con (i) los Materiales de X, (ii) las Marcas de X, y (iii) el Servicio de X, incluso cuando dichas mejoras, desarrollos, mejoras o trabajos derivados se creen utilizando o haciendo referencia a datos, conocimientos, información o aprendizajes derivados de cualquier Material de la Empresa de conformidad con los términos de este Acuerdo, o datos relacionados con la actividad publicitaria de la Empresa en el Servicio de X), incluyendo, entre otros, todos los derechos de propiedad intelectual sobre los mismos.
**5.2 Licencia a la Empresa.** Durante el Plazo (incluido cualquier Periodo de Cierre), en la medida en que la Empresa utilice, o tenga acceso a, los Productos de Anuncios (o cualquier aspecto de los mismos), X por el presente otorga a la Empresa un derecho y licencia limitados, libres de regalías, no exclusivos, no sublicenciables y no transferibles para utilizar y mantener cualquier Material de X y Marcas de X que X pueda proporcionar a la Empresa en virtud de este Acuerdo únicamente si es necesario y en la medida necesaria para utilizar los Productos de Anuncios (o cualquier Producto Individual) que X proporcione o ponga a disposición de la Empresa, y para ejercer sus derechos y cumplir sus obligaciones en virtud de este Acuerdo, en cada caso de conformidad con los términos de este Acuerdo (incluyendo, sin limitación, las restricciones y/o limitaciones sobre el uso de los Materiales de X). La Empresa acepta que su uso de las Marcas de X cumplirá en todo momento con las Directrices de Marca Registrada de X (definidas a continuación en la Sección 6).
**5.3 Licencia a X.** Durante el Plazo (incluido cualquier Periodo de Cierre), si la Empresa utiliza, o tiene acceso a, los Productos de Anuncios (o cualquier aspecto de los mismos), la Empresa otorga a X un derecho y licencia libres de regalías, no exclusivos, sublicenciables y no transferibles para utilizar, copiar, mostrar, mantener, transferir, modificar, duplicar y transmitir los Materiales de la Empresa y las Marcas de la Empresa según sea necesario para cumplir con las instrucciones de la Empresa (incluyendo, sin limitación, mediante la compra y/o colocación de anuncios en cualquier inventario publicitario accesible en la Red de X), para operar los Productos de Anuncios (o cualquier Producto Individual), y para ejercer sus derechos y cumplir sus obligaciones en virtud de este Acuerdo, en cada caso de conformidad con los términos de este Acuerdo.
**5.4 Limitaciones y Restricciones.**
5.4.1 Los Materiales de X se proporcionan a la Empresa, y los Materiales de la Empresa se proporcionan a X, únicamente para el uso y/o la prestación de los Productos de Anuncios y para cualquier otro propósito expresamente permitido en este Acuerdo.
5.4.2 Excepto según lo permitido expresamente en este Acuerdo o salvo que se acuerde por escrito mutuamente con anticipación por X y la Empresa, la Empresa no explotará, duplicará, copiará, modificará, derivará y/o reutilizará, ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga, ningún Material de X, ni ninguna información, datos o conocimientos derivados de los Materiales de X para ningún propósito interno o externo (incluyendo, entre otros, la segmentación de anuncios, la optimización de anuncios, el remarketing, la segmentación conductual, el retargeting, la redirección o la creación o aumento de cualquier manera de agrupaciones de usuarios o segmentos de dispositivos, o la creación o adición de perfiles de usuario final, incluidos los asociados con cualquier identificador de dispositivo móvil u otro identificador único conectado a cualquier usuario final, computadora, navegador o dispositivo, o la redirección de un usuario con publicidad a través de redes o intercambios de publicidad, corredores de datos o cualquier otro servicio de publicidad o monetización). Además, la Empresa no utilizará los Materiales de X para identificar o volver a identificar a los usuarios de ninguna manera (incluyendo mediante la combinación de Materiales de X o datos derivados de los mismos con datos derivados de fuentes de terceros).
5.4.3 La Empresa no puede, ni permitir que ninguna otra parte (incluidos los Clientes) lo haga, incorporar cualquier Material de X (incluyendo, sin limitación, código informático, píxeles, etiquetas o cualquier otro producto digital proporcionado por X a la Empresa) en otro producto o servicio (excepto lo necesario para el desempeño de este Acuerdo y permitido por los términos y condiciones de este Acuerdo), traducir, modificar, someter a ingeniería inversa o compilación inversa, desensamblar, hacer trabajos derivados de, o de otro modo intentar descubrir cualquier código fuente, ideas subyacentes o algoritmos de cualquier Material de X sin el permiso expreso por escrito de X.
5.4.4 La Empresa no interferirá, modificará, interrumpirá ni deshabilitará, ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga, las funciones o funcionalidades de cualquier Material de X, incluyendo, sin limitación, cualquier mecanismo utilizado para restringir o controlar la funcionalidad, ni derrotará, evadirá, omitirá, eliminará, desactivará o eludirá de otro modo cualquier mecanismo de protección de software o de monitoreo de los Materiales de X.
5.4.5 La Empresa no venderá, alquilará, arrendará, sublicenciará, distribuirá, redistribuirá, sindicará, creará trabajos derivados, cederá o de otro modo transferirá o proporcionará acceso, en su totalidad o en parte, a los Materiales de X a cualquier tercero, excepto según lo permitido expresamente en el presente, ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga.
5.4.6 La Empresa no eliminará ni alterará ningún aviso o marca de propiedad en o sobre los Materiales de X, ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga.
5.4.7 La Empresa no proporcionará el uso de los Materiales de X en régimen de service bureau, alquiler o servicios gestionados, ni permitirá que otras personas o entidades creen enlaces a los Materiales de X ni que "enmarquen" ni "reflejen" los Materiales de X en ningún otro servidor, ni en un dispositivo inalámbrico o basado en Internet, o, si corresponde, no pondrá a disposición de un tercero, ningún token, clave, contraseña u otras credenciales de inicio de sesión para los Materiales de X, ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga.
5.4.8 La Empresa no utilizará los Materiales de X para ningún fin ilegal, no autorizado u otros fines indebidos, ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga.
5.4.9 La Empresa no puede compartir los Materiales de X (incluyendo, sin limitación, los Datos) con ningún tercero (ya sea verbalmente o por escrito), incluidos cualquier cliente o socio comercial de la Empresa o cualquier personal de la Empresa no relacionado con los Productos de Anuncios, excepto si y según se describe explícitamente en el presente, o según lo permitido por X con anticipación por escrito (se acepta correo electrónico), ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga.
5.4.10 La Empresa no puede mezclar ni crear de otro modo ninguna visualización combinada de Materiales de X con Materiales de la Empresa, datos, contenido u otros materiales recibidos de X en virtud de un acuerdo separado, ni con cualquier otro material de terceros o a través de campañas publicitarias, excepto si y según se detalla expresamente en el presente o según lo aprobado por X por escrito con anticipación, ni permitirá que ninguna otra parte (incluidos los Clientes) lo haga.
5.4.11 La Empresa no puede ofrecer ni proporcionar el Servicio de la Empresa y/o los Materiales de X como parte de una red de publicidad y no puede habilitar ninguna exportación programática ni de otro modo habilitar el consumo por máquina de los Materiales de X por o para ningún tercero (incluyendo, sin limitación, Clientes) sin el consentimiento previo por escrito de X, ni permitir que ninguna otra parte (incluidos los Clientes) lo haga.
5.4.12 La Empresa no puede alentar ni exigir a los usuarios que interactúen con cualquier Producto de Anuncios de una manera que pueda ser engañosa o falaz para el usuario que accede a la Red de X, lo cual puede incluir métodos como ofrecer incentivos, puntos, recompensas, dinero en efectivo, premios o cualquier otra cosa de valor monetario, o cualquier otro método malicioso o fraudulento, ni permitir que ninguna otra parte (incluidos los Clientes) lo haga.
### 6. Términos Incorporados.
El acceso de la Empresa a cualquier Producto Individual y/o los Materiales de X asociados está condicionado a la aceptación por parte de la Empresa de, y su cumplimiento con, las siguientes políticas (colectivamente, las "**Políticas de X**"), cada una únicamente en la medida aplicable al Producto Individual y a los Materiales de X a los que la Empresa esté accediendo y/o utilizando:
**6.1** Política de Privacidad ([https://x.com/privacy](https://x.com/privacy))
**6.2** Términos de Servicio ([https://x.com/tos](https://x.com/tos))
**6.3** Acuerdo Maestro de Servicios de X aplicable ([https://legal.x.com/ads-terms/us.html](https://legal.x.com/ads-terms/us.html)) ([https://legal.x.com/ads-terms/international.html](https://legal.x.com/ads-terms/international.html)) u otro Acuerdo Maestro de Servicios de X referenciado en una orden de inserción.
**6.4** Directrices de Política de Anuncios ([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies)), incluidas las Políticas para el Seguimiento de Conversiones y las Audiencias Personalizadas ([https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences))
**6.5** Acuerdo y Política del Desarrollador ([https://docs.x.com/developer-terms/agreement](/developer-terms/agreement))
**6.6** Directrices de Marca Registrada y Marca de X ([https://about.x.com/who-we-are/brand-toolkit](https://about.x.com/who-we-are/brand-toolkit))
La Empresa acepta las Políticas de X en la medida en que la Empresa acceda o utilice los Productos Individuales a los que se apliquen las políticas individuales. La Empresa acepta y reconoce que las Políticas de X pueden ser modificadas por X de vez en cuando a entera discreción de X. En caso de una modificación material de las Políticas de X que afecte a la Empresa, X proporcionará a la Empresa un aviso (por ejemplo, por correo electrónico o según se publique en el Servicio de X) de dicho cambio. El acceso o uso continuo por parte de la Empresa de los Materiales de X y las Marcas de X después de dichas actualizaciones o modificaciones constituirá la aceptación vinculante de las actualizaciones y modificaciones.
### 7. Plazo; Derechos de Rescisión; Derechos de Suspensión.
**7.1 Plazo.** Este Acuerdo comenzará en la Fecha de Entrada en Vigor y permanecerá vigente por un (1) año (el "**Plazo Inicial**") y continuará automáticamente por plazos sucesivos adicionales de un (1) año (cada uno, un "**Plazo de Renovación**"), a menos que cualquiera de las partes proporcione notificación por escrito de no renovación al menos treinta (30) días antes de la expiración del Plazo Inicial o rescinda este Acuerdo de conformidad con la Sección 7.2 a continuación. El Plazo Inicial y todos los Plazos de Renovación constituirán colectivamente el ("**Plazo**").
**7.2 Rescisión; Suspensión.** Tras la finalización del Plazo Inicial y el comienzo del Plazo de Renovación, cualquiera de las partes puede rescindir este Acuerdo por conveniencia mediante la provisión de un aviso previo de treinta (30) días a la otra parte. X puede rescindir inmediatamente este Acuerdo mediante notificación por escrito a la Empresa si la Empresa: (a) se fusiona o es adquirida, en su totalidad o en parte, por cualquier tercero, ya sea voluntaria o involuntariamente, y/o por operación de la ley (incluyendo, sin limitación, en relación con una fusión, adquisición o venta de activos, ya sea que la Empresa sea la entidad superviviente o desaparecida); o (b) tiene un síndico o parte similar designada para su propiedad, se vuelve insolvente, reconoce su insolvencia de cualquier manera, cesa de hacer negocios, hace una cesión en beneficio de sus acreedores o presenta una petición de quiebra. Sin limitar cualquier otro recurso en este Acuerdo o disponible en derecho o en equidad, X puede suspender inmediatamente el acceso o uso por parte de la Empresa a los Productos de Anuncios, cualquier Producto Individual y/o los Materiales de X (o cualquier parte de los mismos) o rescindir cualquiera y todas las licencias otorgadas a la Empresa en virtud de este Acuerdo o este Acuerdo en su totalidad, en cualquier momento y sin aviso, si X, a su entera discreción, cree o determina que: (i) la Empresa está en violación de alguna de las Políticas Aplicables, o ha incumplido o intenta incumplir o no cumple con algún término o condición de este Acuerdo, y/o (ii) el acceso continuo de la Empresa a los Productos de Anuncios, un Producto Individual dado, y/o los Materiales de X causará o puede causar responsabilidad para X y/o los Clientes de X o de otro modo dañar el servicio, negocio o reputación de X o del Cliente de X.
**7.3 Efecto de la Rescisión.** Tras la expiración o rescisión de este Acuerdo: (a) todos los derechos y licencias otorgados en el presente cesarán inmediatamente y la Empresa dejará inmediatamente de acceder y utilizar los Materiales de X; (b) dentro de los treinta (30) días de dicha expiración o rescisión, la Empresa eliminará, borrará y borrará de forma segura todos los Materiales de X (incluidas todas las copias y partes de los mismos) en todas las formas y tipos de medios del Servicio de la Empresa o de otro modo en posesión o control de la Empresa; y (c) dentro de los treinta (30) días de dicha expiración o rescisión, la Empresa eliminará y borrará de forma segura todas las copias de cualquier Información Confidencial (según se define a continuación en la Sección 9) en posesión o control de la Empresa. X no será responsable de ningún costo, gasto o daño como resultado de su rescisión de este Acuerdo.
**7.4 Periodo de Cierre.** No obstante lo anterior, en caso de que cualquiera de las partes rescinda este Acuerdo conforme a esta Sección 7, los términos y condiciones de este Acuerdo, y los respectivos derechos y obligaciones de las partes en el mismo, a la sola elección de X (y tras la notificación por escrito de X a la Empresa de tal elección), continuarán aplicándose durante un Periodo de Cierre (según se define a continuación) únicamente con respecto a todas y cada una de las campañas publicitarias de los Clientes que estén en curso en el momento de dicha rescisión (lo cual incluirá, sin limitación, las circunstancias en las que X y/o el Cliente aplicable hayan elegido ejecutar una campaña publicitaria, incluso si dicha campaña publicitaria no ha comenzado realmente en el momento de la rescisión). Tal como se utiliza en el presente, "**Periodo de Cierre**" significará un periodo que comienza tras la rescisión del Plazo y continúa hasta el que ocurra primero de: (i) noventa (90) días después de dicha fecha de rescisión; o (ii) la finalización de todas las campañas publicitarias de los Clientes que estaban en curso (según se describió anteriormente) a partir de dicha fecha de rescisión.
**7.5 Supervivencia.** Aquellos términos que por su naturaleza deban sobrevivir a la expiración o rescisión de este Acuerdo, sobrevivirán, incluyendo, entre otros, las Secciones 3-15.
### 8. Seguridad; Violaciones de Seguridad; Notificación Regulatoria; Eliminación de Datos; Auditoría.
**8.1 Seguridad.** La Empresa utilizará medidas de seguridad estándar de la industria en relación con su desempeño bajo este Acuerdo, incluyendo, entre otras, medidas de seguridad administrativas, técnicas y físicas para la transmisión y almacenamiento de datos al menos tan restrictivas como las medidas de seguridad estándar de la industria para la transmisión y almacenamiento de los tipos de datos incluidos en los Materiales de X. La Empresa también utilizará medidas técnicas y organizativas de seguridad razonables (incluyendo, como mínimo, protección con contraseña y restricciones de protocolo de acceso), y en ningún caso menos cuidado del que utiliza en relación con la transmisión y protección de los propios datos de la Empresa de naturaleza igual o similar, para restringir el acceso a los Materiales de X y a la Información Confidencial únicamente a aquel personal individual de la Empresa que necesite acceder a dichos Materiales de X para ejercer los derechos de la Empresa y/o cumplir con las obligaciones de la Empresa de conformidad con este Acuerdo.
**8.2 Violaciones de Seguridad.** La Empresa notificará a X por escrito (lo cual puede incluir correo electrónico) dentro de las veinticuatro (24) horas de tener conocimiento de cualquier violación de seguridad u otro acceso indebido que haya resultado, pueda haber resultado o tenga el potencial de resultar en la exposición de cualquier Material de X y/o dato relacionado con, basado en o que surja de este Acuerdo. La Empresa consultará y cooperará con X en cualquier investigación, proporcionará las notificaciones requeridas y/o proporcionará cualquier información razonablemente solicitada por X.
**8.3 Consultas Regulatorias.** La Empresa notificará a X por escrito (lo cual puede incluir correo electrónico) dentro de las veinticuatro (24) horas siguientes a la recepción por parte de la Empresa del aviso de cualquier consulta de una agencia gubernamental o regulatoria relacionada con una violación de seguridad (u otro incidente similar), el presunto uso indebido de datos de consumidores por parte de la Empresa, o cualquier otro aspecto de las operaciones de la Empresa que estén razonablemente relacionados, ya sea directa o indirectamente, con este Acuerdo.
**8.4 Eliminación de Datos.** La Empresa eliminará y borrará de forma segura todos y cada uno de los Materiales de X de sus sistemas cuando la Empresa ya no tenga una necesidad comercial legítima de retener dichos Materiales de X para ejercer los derechos de la Empresa y/o cumplir las obligaciones de la Empresa bajo este Acuerdo (incluyendo, sin limitación, en caso de que el Cliente aplicable deje de utilizar los Productos de Anuncios o de otro modo deje de utilizar los Servicios de la Empresa), pero en ningún caso más tarde de lo que ocurra primero de: (a) noventa (90) días desde la fecha en que la Empresa reciba por primera vez los Datos aplicables, o (b) treinta (30) días después de la fecha de expiración o rescisión del Acuerdo. Además, en cualquier momento, la Empresa acepta eliminar y borrar de forma segura, inmediatamente después de la solicitud por escrito de X (que puede entregarse por correo electrónico), cualquier Material de X que X considere necesario o deseable eliminar y borrar de forma segura (a entera y absoluta discreción de X).
**8.5 Auditoría.** Tras una notificación previa por escrito razonable (de no menos de diez (10) días), no más de dos veces por año calendario durante el Plazo y una vez durante el periodo de seis (6) meses posterior a la fecha en que este Acuerdo se rescinda o expire, a cargo de X, se proporcionará a X acceso a las instalaciones de la Empresa para auditar los procesos, metodologías, prácticas y sistemas utilizados por la Empresa en el desempeño de sus obligaciones y en el ejercicio de sus derechos bajo este Acuerdo. Para mayor claridad, la Empresa reconoce y acepta que (i) X puede contratar a un auditor externo para realizar dicha auditoría en su nombre; y (ii) no obstante cualquier disposición en contrario en el presente, X puede compartir cualquier Información Confidencial relevante sobre la Empresa (incluyendo, sin limitación, los términos y condiciones de este Acuerdo) con dicho auditor externo únicamente según sea necesario para facilitar dicha auditoría.
### 9. Información Confidencial.
Cada parte acepta que toda la información comercial, técnica y financiera que se designe como "confidencial" o "propietaria", o que se divulgue de una manera que una persona razonable entendería la naturaleza confidencial de la información divulgada por la parte divulgadora ("**Información Confidencial**"). Para mayor claridad, toda la información propietaria proporcionada por X a la Empresa conforme a este Acuerdo, que incluye, sin limitación, información (tangible o intangible) relativa a la tecnología, diseños, técnicas, investigación, know-how, especificaciones, planes de producto, precios, información de clientes, datos de usuario, información estratégica actual o futura, planes comerciales, políticas o prácticas actuales o futuras, información de empleados y otra información comercial y técnica de X (incluyendo, sin limitación, resultados, análisis o datos sobre el tiempo de actividad, fiabilidad, métricas de tráfico y crecimiento, calidad de la red y otras estadísticas de uso del Servicio de X, en el agregado o de otro modo, derivadas del uso por parte de la Empresa de los Materiales de X o del Servicio de X y/o del acceso a documentación técnica, boletines de desarrollo y/o portales o foros en línea) es Información Confidencial de X y propietaria de X. Sin limitar lo anterior, los términos y condiciones de este Acuerdo, los Materiales de X, cualquier requisito de producto y cualquier otra documentación, procesos de incorporación u otros materiales proporcionados por X a la Empresa bajo este Acuerdo se considerarán Información Confidencial de X. Excepto según se permita expresamente en el presente, la parte receptora mantendrá en confidencialidad y no utilizará ni divulgará (excepto en relación con el desempeño de las obligaciones de dicha parte bajo este Acuerdo) ninguna Información Confidencial de la parte divulgadora. La parte receptora no estará obligada bajo esta Sección con respecto a la información que la parte receptora pueda documentar mediante escritura o testimonio que dicha información: (i) es o se ha vuelto fácilmente disponible al público sin culpa de la parte receptora o sus empleados o agentes; (ii) se recibe de un tercero legalmente en posesión de dicha información, y la parte receptora no tiene conocimiento de ninguna restricción de divulgación sobre dicho tercero para divulgar dicha información; (iii) es divulgada a un tercero por la parte divulgadora sin restricción de divulgación; (iv) estaba legítimamente en posesión de la parte receptora sin restricción antes de su divulgación por la otra parte; o (v) fue desarrollada independientemente por empleados o consultores de la parte receptora sin depender de dicha información. La parte receptora puede realizar divulgaciones requeridas por ley u orden judicial, siempre que la parte receptora notifique a la parte divulgadora de la emisión de dicha orden y permita a la parte divulgadora participar en el procedimiento.
### 10. Declaraciones y Garantías.
La Empresa declara y garantiza que: (i) tiene todo el poder legal y corporativo requerido para celebrar este Acuerdo; (ii) ha tomado todas las acciones necesarias para hacer de este Acuerdo una obligación legal, válida y vinculante; (iii) no tiene ningún acuerdo o entendimiento con ningún tercero que interfiera o vaya a interferir con su desempeño de sus obligaciones bajo este Acuerdo; (iv) ha obtenido y mantendrá todos los permisos, consentimientos, derechos, aprobaciones y licencias necesarios para desempeñar sus obligaciones y otorgar todos los derechos y licencias otorgados bajo este Acuerdo incluyendo, sin limitación, todos los derechos necesarios para que la Empresa otorgue a X una licencia para utilizar los Materiales de la Empresa para colocar anuncios en cualquier inventario publicitario disponible o accesible a X en el Servicio de X o de otro modo y proporcionar el Servicio de la Empresa; (v) el Servicio de la Empresa y los Materiales de la Empresa no infringen ni infringirán, no se apropian indebidamente ni violan de otro modo los derechos de ningún tercero; y (vi) su negocio y desempeño bajo este Acuerdo, incluyendo su prestación del Servicio de la Empresa, cumple y cumplirá con todas las leyes y reglamentos gubernamentales extranjeros, federales, estatales y locales aplicables. La Empresa además declara y garantiza que: (a) no tiene conocimiento de ninguna reclamación, demanda, acción o cargo real, pendiente o amenazado relacionado con el Servicio de la Empresa, los Materiales de la Empresa u otros entregables relacionados con este Acuerdo o con las prácticas de la Empresa en materia de seguridad de datos, uso de datos o privacidad; y (b) en caso de que la Empresa esté accediendo o utilizando los Productos de Anuncios (o cualquier aspecto de los mismos) en nombre de un Cliente, la Empresa tiene la autoridad como agente de dicho tercero para utilizar dichos Materiales de la Empresa en nombre de dicho tercero, para transmitir los derechos sobre dichos materiales de terceros que puedan proporcionarse a X en los Materiales de la Empresa, y para vincular a dicho tercero a los términos de este Acuerdo.
### 11. Comentarios. Servicios Beta.
Si y en la medida en que X proporcione (a su entera y absoluta discreción) a la Empresa cualquier acceso a características y funcionalidades que estén designadas como privadas, no lanzadas, en desarrollo o en "alfa" o "beta" (colectivamente, "**Servicios Beta**"), la Empresa reconoce y acepta que los Servicios Beta no cuentan con soporte de X, y los Servicios Beta (o cualquier parte de los mismos) pueden lanzarse públicamente o quedar no disponibles en cualquier momento (en cada caso, a entera y absoluta discreción de X). Los Servicios Beta se proporcionan "TAL CUAL" en la máxima medida permitida por la ley, y el uso por parte de la Empresa de dichos Servicios Beta es bajo el propio riesgo y consentimiento de la Empresa. Todos los Servicios Beta se considerarán Información Confidencial de X. La Empresa acepta que la participación en cualquier Servicio Beta ayudará a X en la investigación, análisis y validación de algunos programas, productos y/o herramientas existentes y/o potenciales, y que si la Empresa proporciona a X comentarios, opiniones u otra información para ayudar a X a evaluar y mejorar dichos programas, productos y/o herramientas ("**Comentarios**"), X y sus designados serán libres de copiar, modificar, crear trabajos derivados, exhibir públicamente, divulgar, distribuir, licenciar y sublicenciar, incorporar y utilizar de otro modo los Comentarios, incluidos los trabajos derivados de los mismos, para todos y cada uno de los fines comerciales y no comerciales sin ninguna obligación o compensación de ningún tipo hacia la Empresa o cualquier tercero. Para mayor claridad, los Comentarios no incluyen y X no utilizará el nombre de la Empresa ni divulgará públicamente los resultados de rendimiento de los Servicios Beta de la Empresa. Los Comentarios también incluirán cualquier comentario de la Empresa relativo a los Materiales de X, los Productos de Anuncios y/o la evaluación y uso de los mismos por parte de la Empresa. La Empresa acepta que nada en este Acuerdo impedirá que X desarrolle productos o servicios que puedan ser competitivos con los productos o servicios de la Empresa o de cualquier Cliente o Usuario Final.
### 12. Renuncia de Garantía.
LOS MATERIALES DE X, LOS PRODUCTOS DE ANUNCIOS Y CUALQUIER OTRO PRODUCTO Y SERVICIO DE X (INCLUYENDO, SIN LIMITACIÓN, CUALQUIER SERVICIO BETA) Y CUALQUIER MARCA DE X PROPORCIONADA EN EL PRESENTE SE PROPORCIONAN "TAL CUAL" Y "SEGÚN DISPONIBILIDAD", SIN GARANTÍA DE NINGÚN TIPO. X RENUNCIA A TODAS LAS GARANTÍAS, YA SEAN EXPRESAS, IMPLÍCITAS, LEGALES O DE OTRO TIPO, INCLUYENDO, SIN LIMITACIÓN, LAS GARANTÍAS DE COMERCIABILIDAD, NO INFRACCIÓN, IDONEIDAD PARA UN PROPÓSITO PARTICULAR, Y CUALQUIER GARANTÍA O CONDICIÓN QUE SURJA DEL CURSO DE LAS OPERACIONES O DEL USO COMERCIAL. X NO GARANTIZA QUE LOS MATERIALES DE X, LOS PRODUCTOS DE ANUNCIOS Y CUALQUIER OTRO PRODUCTO Y SERVICIO DE X (INCLUYENDO, SIN LIMITACIÓN, CUALQUIER SERVICIO BETA) O CUALQUIER MARCA DE X PROPORCIONADA EN EL PRESENTE CUMPLIRÁN CON LOS REQUISITOS DE LA EMPRESA O QUE EL USO DE DICHOS MATERIALES DE X, OTROS PRODUCTOS Y SERVICIOS DE X Y/O CUALQUIER MARCA DE X ESTARÁ LIBRE DE ERRORES, ININTERRUMPIDO, LIBRE DE VIRUS O SEGURO. ESTA RENUNCIA DE GARANTÍA PUEDE NO SER VÁLIDA EN ALGUNAS JURISDICCIONES, Y LA EMPRESA PUEDE TENER DERECHOS DE GARANTÍA CONFORME A LA LEY QUE NO PUEDEN SER RENUNCIADOS O DESCONOCIDOS. CUALQUIER DICHA GARANTÍA SE EXTIENDE ÚNICAMENTE POR TREINTA (30) DÍAS DESDE LA FECHA DE ENTRADA EN VIGOR DE ESTE ACUERDO (A MENOS QUE DICHA LEY DISPONGA LO CONTRARIO).
### 13. Indemnización.
La Empresa defenderá, a su propio costo, cualquier reclamación, demanda o acción contra X presentada por un tercero en la medida en que dicha reclamación, demanda o acción se base en una alegación de que (i) los Materiales de la Empresa, el Servicio de la Empresa, las Marcas de la Empresa, el uso por parte de X de los Materiales de la Empresa o de las Marcas de la Empresa, o la tecnología utilizada para generar los Materiales de la Empresa y/o el Servicio de la Empresa infringen cualquier derecho de cualquier tercero (incluyendo, sin limitación, cualquier derecho de propiedad intelectual, derecho de privacidad o derecho de publicidad); (ii) la Empresa ha incumplido cualquiera de sus obligaciones, declaraciones o garantías en el presente, incluyendo las obligaciones de seguridad de datos, uso de datos y privacidad de la Empresa; o (iii) el uso no autorizado por parte de la Empresa de los Materiales de X y/o las Marcas de X en violación de los términos, condiciones y restricciones establecidos en el Acuerdo. La Empresa indemnizará y mantendrá indemne a X de y contra cualquier pérdida, daño, responsabilidad, sanción, costo y gasto atribuible a cualquier dicha reclamación. La Empresa es responsable de defender cualquier reclamación contra X, sujeto al derecho de X a participar con su propio abogado, y del pago de todas las sentencias, acuerdos, daños, pérdidas, responsabilidades, costos y gastos, incluyendo los honorarios razonables de abogados, resultantes de todas las reclamaciones contra X, siempre que la Empresa no acepte ningún acuerdo relacionado con cualquier reclamación sin el consentimiento previo expreso por escrito de X, independientemente de si dicho acuerdo libera o no a X de cualquier obligación o responsabilidad. X notificará prontamente a la Empresa sobre una obligación de indemnización (siempre que el hecho de no hacerlo sólo liberará a la Empresa de su obligación en la medida en que pueda demostrar un perjuicio material por dicho incumplimiento).
### 14. Limitación de Responsabilidad.
EN NINGÚN CASO X SERÁ RESPONSABLE ANTE LA EMPRESA O CUALQUIER CLIENTE O USUARIO FINAL POR NINGÚN DAÑO ESPECIAL, INCIDENTAL, EJEMPLAR, PUNITIVO O CONSECUENTE, O POR LA PÉRDIDA DE INGRESOS, LA PÉRDIDA DE BENEFICIOS, LOS COSTOS DE REEMPLAZO DE BIENES O SERVICIOS, LA PÉRDIDA DE TECNOLOGÍA, FONDO DE COMERCIO, DERECHOS DE SERVICIOS, LA PÉRDIDA DE DATOS O LA INTERRUPCIÓN O LA PÉRDIDA DEL USO DEL SERVICIO QUE SURJAN DE O EN RELACIÓN CON ESTE ACUERDO, O POR EL USO POR PARTE DE LA EMPRESA O EL CLIENTE O EL USUARIO FINAL DE LOS MATERIALES DE X, LAS MARCAS DE X O CUALQUIER PRODUCTO Y/O SERVICIO DE X (INCLUYENDO, SIN LIMITACIÓN, LOS PRODUCTOS DE ANUNCIOS) PROPORCIONADOS EN EL PRESENTE, YA SEA QUE DICHA RESPONSABILIDAD SURJA DE CUALQUIER RECLAMACIÓN BASADA EN CONTRATO, GARANTÍA, RESPONSABILIDAD EXTRACONTRACTUAL (INCLUYENDO NEGLIGENCIA), RESPONSABILIDAD ESTRICTA O DE OTRO MODO, Y INDEPENDIENTEMENTE DE SI X HA SIDO INFORMADA O NO DE LA POSIBILIDAD DE DICHA PÉRDIDA O DAÑO. EN LA MEDIDA EN QUE LA LEY APLICABLE PROHÍBA CUALQUIER LIMITACIÓN DE RESPONSABILIDAD EN EL PRESENTE, LAS PARTES ACUERDAN QUE DICHA LIMITACIÓN SERÁ MODIFICADA AUTOMÁTICAMENTE, PERO SÓLO EN LA MEDIDA NECESARIA PARA QUE LA LIMITACIÓN CUMPLA CON LA LEY APLICABLE. LAS PARTES ACUERDAN QUE LAS LIMITACIONES DE RESPONSABILIDAD ESTABLECIDAS EN EL PRESENTE SON ASIGNACIONES DE RIESGO ACORDADAS Y SE APLICARÁN NO OBSTANTE EL FALLO DEL PROPÓSITO ESENCIAL DE CUALQUIER RECURSO LIMITADO. EN CUALQUIER CASO, LA RESPONSABILIDAD AGREGADA DE X BAJO ESTE ACUERDO NO EXCEDERÁ DE CINCUENTA DÓLARES ESTADOUNIDENSES (USD 50).
### 15. Miscelánea.
**15.1 Publicidad.** La Empresa no puede emitir ningún comunicado de prensa, publicación de blog ni realizar de otro modo ningún anuncio o divulgación pública relativo a este Acuerdo, ninguna de las actividades contempladas en el presente, o relativo a la relación entre la Empresa y X sin el consentimiento previo por escrito de X (que puede proporcionarse por correo electrónico).
**15.2 Protección del Usuario.** La Empresa no (a) permitirá ni asistirá a sabiendas a ninguna entidad gubernamental, autoridades policiales u otras organizaciones para llevar a cabo vigilancia sobre el Servicio de X o los Materiales de X u obtener información sobre los usuarios de X o sus publicaciones que requiera una citación, orden judicial u otro proceso legal válido, o que de otro modo tenga el potencial de ser incompatible con las expectativas razonables de privacidad de los usuarios de X; ni (b) mostrará, distribuirá o de otro modo pondrá a disposición Materiales de X a cualquier persona o entidad que la Empresa razonablemente crea que utilizará dichos datos para violar la Declaración Universal de los Derechos Humanos (ubicada en [https://www.un.org/en/universal-declaration-human-rights/index.html](http://www.un.org/en/universal-declaration-human-rights/index.html)), incluyendo, sin limitación, los Artículos 12, 18 o 19. Cualquier personal de las autoridades policiales que solicite información sobre los usuarios de X será remitido a las Directrices para las Autoridades Policiales de X ubicadas en [https://help.x.com/rules-and-policies/x-law-enforcement-support](https://help.x.com/rules-and-policies/x-law-enforcement-support).
**15.3 Uso Gubernamental.** Los Materiales de X pueden ser "artículos comerciales" tal como ese término se define en 48 C.F.R. 2.101, consistentes en "software informático comercial" y "documentación de software informático comercial" tal como esos términos se utilizan en 48 C.F.R. 12.212. Cualquier uso, modificación, derivado, reproducción, liberación, ejecución, exhibición, divulgación o distribución de los Materiales de X por cualquier entidad gubernamental está prohibido, excepto según lo permitido expresamente por los términos de este Acuerdo. Adicionalmente, cualquier uso por parte de entidades del gobierno de EE. UU. debe realizarse de conformidad con 48 C.F.R. 12.212 y 48 C.F.R. 227.7202-1 hasta 227.7202-4. El contratista/fabricante es X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
**15.4 Cumplimiento de las Leyes; Exportación/Importación.** Cada parte cumplirá con todas las leyes, reglas y reglamentos extranjeros, federales, estatales y locales aplicables. La Empresa no exportará ni reexportará los Servicios de X o los Datos de X en violación de las Políticas Aplicables (según se definen en el presente) o de la ley aplicable. Los Materiales de X pueden estar sujetos a las leyes de exportación de EE. UU. y pueden estar sujetos a las leyes de importación y uso del país donde se entreguen o utilicen. La Empresa acepta cumplir con estas leyes. Bajo estas leyes, los Materiales de X no pueden venderse, arrendarse, descargarse, moverse, exportarse, reexportarse o transferirse a través de fronteras sin una licencia o aprobación de la autoridad gubernamental pertinente, a ningún país o a ningún nacional extranjero restringido por estas leyes, incluidos los países embargados por el Gobierno de EE. UU.; ni a ningún usuario final restringido o denegado, incluyendo, entre otros, cualquier persona o entidad prohibida por la Office of Foreign Assets Control de EE. UU.; ni para ningún uso final restringido.
**15.5 Modificaciones.** X puede actualizar o modificar las Políticas Aplicables, los Requisitos de Visualización de Datos Analíticos (adjuntos como [Anexo A-2](#Exhibit-A-2)), los términos y condiciones relacionados con el programa "X Marketing Partner" (adjuntos como [Anexo C](#Exhibit-C)) y cualquier otra documentación técnica y cualesquiera otras directrices o políticas relacionadas con los Materiales de X de vez en cuando, a entera discreción de X, publicando los cambios, según corresponda, en el sitio para desarrolladores de X, ubicado en: [https://developer.x.com](https://developer.x.com) (según pueda modificarse de vez en cuando), en la URL donde se publique la Política de X aplicable o notificando de otro modo a la Empresa (dicho aviso puede ser por correo electrónico). Si algún cambio no es aceptable para la Empresa, el único recurso de la Empresa es cesar todo uso de los Materiales de X y las Marcas de X.
**15.6 Notificaciones.** Excepto según se indique lo contrario en las Secciones 6 y 15.5, cualquier notificación requerida o permitida por este Acuerdo se hará por escrito y se entregará como sigue, dándose por entregada la notificación según se indica: (a) por entrega personal cuando se entregue personalmente; (b) por mensajería nocturna previa verificación por escrito de la recepción; (c) por correo certificado o registrado, con acuse de recibo, previa verificación de la recepción; o (d) por correo electrónico cuando el destinatario reconozca haber recibido el correo electrónico correspondiente. La notificación se enviará a las direcciones establecidas a continuación o a cualquier otra dirección que cualquiera de las partes pueda especificar por escrito. Las notificaciones de incumplimiento enviadas por la Empresa a X deben enviarse únicamente por mensajería nocturna o por correo certificado o registrado. Las notificaciones a la Empresa se enviarán a la dirección de la Empresa registrada con X. Las notificaciones a X Corp. se entregarán a: X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA, Attn: Legal Department, con una copia obligatoria a: Head of Ads API y [legalnotices@x.com](mailto:legalnotices@x.com). Las notificaciones a X Internet Unlimited Company se entregarán a: Legal Department, X Internet Unlimited Company, One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland.
**15.7 Cesión.** La Empresa no puede ceder este Acuerdo ni ninguno de los derechos u obligaciones otorgados en el presente, en su totalidad o en parte, a ningún tercero, ya sea voluntaria o involuntariamente y/o por operación de la ley (incluyendo, sin limitación, en relación con una fusión, adquisición o venta de activos, ya sea que la Empresa sea la entidad superviviente o desaparecida), excepto con el consentimiento expreso por escrito de X, y cualquier intento de cesión en violación de este párrafo es nulo e inválido, y X puede rescindir inmediatamente este Acuerdo. Este Acuerdo obligará y redundará en beneficio de los sucesores y cesionarios permitidos de cada parte.
**15.8 Sin Subcontratistas.** La Empresa no puede utilizar a un tercero para desempeñar o cumplir ninguna de las obligaciones o deberes de la Empresa bajo este Acuerdo, salvo que sea aprobado previamente por X por escrito, aprobación que puede proporcionarse por correo electrónico.
**15.9 Sin Asociación.** Este Acuerdo no crea ni implica ninguna asociación, agencia o empresa conjunta. Ninguna renuncia por cualquiera de las partes a cualquier pacto o derecho bajo este Acuerdo será efectiva a menos que se plasme en un escrito debidamente autorizado por dicha parte.
**15.10 Sin Beneficiarios Terceros.** No habrá beneficiarios terceros de este Acuerdo.
**15.11 Divisibilidad.** Si alguna parte de este Acuerdo se determina que es inválida o inaplicable por un tribunal de jurisdicción competente, dicha disposición se hará cumplir en la máxima medida permisible y las disposiciones restantes de este Acuerdo permanecerán en pleno vigor y efecto.
**15.12 Renuncia.** La renuncia por cualquiera de las partes a un incumplimiento de cualquier disposición de este Acuerdo por la otra parte no operará ni se interpretará como una renuncia a cualquier otro o posterior incumplimiento por esa parte. Ninguna renuncia por parte de X a cualquier pacto o derecho bajo este Acuerdo será efectiva a menos que se plasme en un escrito debidamente autorizado por X.
**15.13 Renuncia a Acción de Clase.** En la medida permitida por la ley, usted también renuncia al derecho de participar como demandante o miembro de una clase en cualquier supuesta acción de clase, acción colectiva o procedimiento de acción representativa.
**15.14 Ley Aplicable y Jurisdicción.** Si X Corp. es la entidad contratante en el presente, los términos del Acuerdo y cualquier disputa relacionada con el mismo o entre la Empresa y X se regirán por las leyes del Estado de Texas, sin tener en cuenta los principios de conflicto/elección de ley. La Convención de las Naciones Unidas sobre los Contratos de Compraventa Internacional de Mercaderías no se aplica al Acuerdo. Si surge una disputa, reclamación o controversia derivada de o relacionada con este Acuerdo o el incumplimiento, rescisión, cumplimiento, interpretación o validez del mismo, incluida la determinación del alcance o aplicabilidad de este acuerdo de arbitrar, la Empresa acepta proporcionar a X una notificación de la disputa, y proporcionar un periodo de resolución de diez (10) días hábiles en el cual X y la Empresa puedan intentar resolver la disputa de manera informal. Si, después del periodo de resolución de diez (10) días hábiles, X y la Empresa no pueden resolver la disputa, la Empresa acepta presentar cualquier disputa o reclamación derivada de este Acuerdo ante el Tribunal de Distrito de EE. UU. para el Distrito Norte de Texas o los tribunales estatales ubicados en el Condado de Tarrant, Texas, Estados Unidos, y usted consiente la jurisdicción personal en esos foros y renuncia a cualquier objeción en cuanto a foro inconveniente. Sin perjuicio de lo anterior, usted acepta que, a su entera discreción, X puede presentar cualquier reclamación, causa de acción o disputa que tengamos contra usted en cualquier tribunal competente del país en el que usted resida que tenga jurisdicción y competencia sobre la reclamación.
Si usted es una entidad federal, estatal o local del gobierno en los Estados Unidos actuando en su capacidad oficial y legalmente incapaz de aceptar las cláusulas de ley aplicable, jurisdicción o competencia anteriores, entonces esas cláusulas no se le aplican. Para dichas entidades del gobierno federal de EE. UU., este Acuerdo y cualquier acción relacionada con el mismo se regirán por las leyes de los Estados Unidos de América (sin referencia al conflicto de leyes) y, en ausencia de ley federal y en la medida permitida por la ley federal, las leyes del Estado de Texas (excluyendo la elección de ley).
Si X Internet Unlimited Company es la entidad contratante en el presente, los términos del Acuerdo y cualquier disputa relacionada con el mismo o entre la Empresa y X se regirán por las leyes de Irlanda, sin tener en cuenta los principios de conflicto/elección de ley. Las partes acuerdan que ni la Convención de las Naciones Unidas sobre los Contratos de Compraventa Internacional de Mercaderías, ni la Uniform Computer Information Transaction Act (UCITA) se aplicarán a este Acuerdo, independientemente de los estados en los que las partes hagan negocios o estén constituidas. Cualquier disputa, reclamación o controversia derivada de o relacionada con este Acuerdo o el incumplimiento, rescisión, cumplimiento, interpretación o validez del mismo se presentará exclusivamente ante un tribunal competente en Irlanda sin tener en cuenta las disposiciones de conflicto de leyes y se regirá por la ley irlandesa, no obstante cualquier acuerdo en contrario entre usted y nosotros. Sin perjuicio de lo anterior, usted acepta que, a su entera discreción, X puede presentar cualquier reclamación, causa de acción o disputa que tengamos contra usted en cualquier tribunal competente del país en el que usted resida que tenga jurisdicción y competencia sobre la reclamación.
USTED TIENE UN AÑO PARA PRESENTAR UNA RECLAMACIÓN CONTRA X. Usted debe presentar cualquier reclamación contra X que surja de o esté relacionada con este Acuerdo dentro de un (1) año después de la fecha de ocurrencia del evento o hechos que den lugar a la disputa, a menos que la ley aplicable disponga que el plazo de prescripción normal para dicha reclamación no pueda acortarse por acuerdo. Si usted no presenta una reclamación dentro de este periodo, renuncia para siempre al derecho de perseguir cualquier reclamación o causa de acción, de cualquier tipo o carácter, basada en tales eventos o hechos, y dichas reclamaciones o causas de acción están prohibidas de manera permanente, y X no tendrá responsabilidad alguna con respecto a dicha reclamación.
**15.15 Medidas Cautelares.** Cada parte acepta que los daños monetarios serían un recurso inadecuado en caso de incumplimiento o amenaza de incumplimiento de las disposiciones de este Acuerdo que protegen la propiedad intelectual de X (incluyendo, sin limitación, los Materiales de X) y/o la Información Confidencial de X, y que, en caso de dicho incumplimiento o amenaza, X, además de cualquier otro recurso al que X tenga derecho, tiene derecho a las medidas cautelares preliminares o de urgencia (incluida una orden que prohíba a la otra parte tomar acciones que incumplan dichas disposiciones), sin necesidad de constituir fianza, y al cumplimiento específico según sea apropiado para preservar todos los derechos de X.
**15.16 Actualizaciones.** X puede actualizar los términos de este Acuerdo y cualquier política referenciada en el presente de vez en cuando, a su entera discreción, y proporcionará un aviso por correo electrónico a la Empresa o publicará un aviso en la URL identificada a continuación. Dicho aviso indicará la fecha de entrada en vigor de dichas actualizaciones. Los términos de este Acuerdo estarán disponibles para que la Empresa los consulte en cualquier momento en [https://docs.x.com/developer-terms/ads-api-agreement](/developer-terms/ads-api-agreement). El uso continuo por parte de la Empresa de cualquier Producto(s) Individual(es) después de la fecha de entrada en vigor proporcionada en el aviso aplicable indicará la aceptación por parte de la Empresa de dichas actualizaciones.
**15.17 Acuerdo Completo.** Este Acuerdo (incluidos los Anexos adjuntos al mismo) constituye el acuerdo completo entre las partes relacionado con el objeto del mismo y sustituye y reemplaza todas las propuestas, entendimientos, comunicaciones y acuerdos previos o contemporáneos, orales o escritos, relativos a dicho objeto. Cualquier enmienda a este Acuerdo se hará por escrito y estará firmada por un representante de las partes respectivas autorizado para vincular a las partes.
## Anexo A: Términos de Producto Individual/X Ads API
Los términos con mayúscula inicial no definidos en estos Términos de Producto Individual tienen el significado establecido en el cuerpo principal del Acuerdo. En la medida en que la Empresa participe en el "Programa X Ads API", se aplicarán los siguientes términos y condiciones de este Anexo A (incluidos el Anexo A-1 y el Anexo A-2):
### 1. Introducción a X Ads API; Acceso.
**1.1 Introducción.** La interfaz de programación de aplicaciones (API) de publicidad de X, y la documentación, código y materiales relacionados que la acompañan (colectivamente, la "**X Ads API**") que proporciona a la Empresa acceso "read/write" que le permite participar en la Gestión de Campañas de X Ads y/o con acceso "read" a ciertos informes de Datos sobre el rendimiento de las Campañas de X Ads.
**1.2 Acceso a la API.** X decidirá (a su entera y absoluta discreción) si otorga a la Empresa acceso "read" o "read/write" a la X Ads API. X puede implementar un proceso de revisión para otorgar acceso a la X Ads API, pero no está obligado a hacerlo.
### 2. Licencia de la Ads API.
Con la condición de que X decida proporcionar a la Empresa acceso a la X Ads API, y sujeto al cumplimiento continuo por parte de la Empresa de los términos y condiciones del Acuerdo, X otorga a la Empresa una licencia limitada, no exclusiva, no transferible, no sublicenciable y revocable durante el Plazo para: (a) utilizar la X Ads API para implementar el Servicio de la Empresa con el propósito de proporcionar a los Usuarios Finales de un Cliente acceso a los Datos relacionados con las Campañas de X Ads de dicho Cliente (y, si la Empresa tiene acceso "read/write" a la API, para habilitar la Gestión de Campañas de X Ads a través del Servicio de la Empresa); (b) mostrar los Datos en formato agregado únicamente dentro del Servicio de la Empresa de conformidad con los Requisitos de Visualización de Datos Analíticos (definidos a continuación en la Sección 3 de este Anexo A) a los Usuarios Finales de un Cliente únicamente con el propósito de optimizar las Campañas de X Ads de dicho Cliente; (c) modificar los Datos únicamente según sea necesario para formatearlos y mostrarlos dentro del Servicio de la Empresa; (d) permitir que el Servicio de la Empresa exporte Datos únicamente en un formato que X haya aprobado por escrito y que cumpla con los Requisitos de Visualización de Datos Analíticos y mediante un mecanismo de exportación que sea aprobado por X por escrito; y (e) utilizar y mostrar las Marcas de X que X ponga a disposición para su uso en relación con la X Ads API y/o los Datos únicamente para atribuir a X como la fuente de los Datos o según se permita expresamente de otro modo bajo el Acuerdo (en cada caso, de conformidad con las Directrices de Marca Registrada de X).
### 3. Requisitos de Visualización, Integración y Otros Requisitos.
La implementación y el uso por parte de la Empresa de la X Ads API y los Datos deberán cumplir en todo momento con: (a) los requisitos del producto adjuntos al presente como Anexo A-1 ("**Requisitos del Producto**"); (b) los requisitos de visualización adjuntos al presente como Anexo A-2 ("**Requisitos de Visualización de Datos Analíticos**"); (c) toda la documentación técnica para la X Ads API que se haya proporcionado, o se proporcionará, a la Empresa por X (incluyendo, sin limitación, cualquier especificación o requisito de endpoint); (d) cualquier proceso de incorporación especificado por X relacionado con la X Ads API y los Datos; (e) las Políticas Aplicables; y (f) cualesquiera otras directrices y políticas aplicables a la X Ads API y a los Datos que X pueda proporcionar a la Empresa.
### 4. Cumplimiento.
La Empresa cumplirá con todas las instrucciones proporcionadas o comunicadas a la Empresa por X, incluyendo, sin limitación, las limitaciones sobre acceso, llamadas y uso de la X Ads API y cualesquiera limitaciones o restricciones adicionales relacionadas con tokens, límites de tasa, claves, contraseñas u otras credenciales de inicio de sesión para la X Ads API. Cualquier tal instrucción es determinada por X a su entera y absoluta discreción. La Empresa cumplirá con cualquier solicitud de X para inspeccionar y acceder al Servicio de la Empresa, incluyendo, sin limitación, proporcionar a X cualquier código del Servicio de la Empresa relacionado con la implementación de la X Ads API, para garantizar que la integración de la X Ads API en, y la visualización de los Datos dentro del, Servicio de la Empresa cumpla con los Requisitos del Producto y los Requisitos de Visualización de Datos Analíticos, los controles de calidad de X y/u otros términos y condiciones de este Acuerdo. X puede monitorear el uso por parte de la Empresa de la X Ads API para mejorar los Servicios de X.
### 5. Control de la Asignación del Inventario de X Ads.
Para mayor claridad, y sin limitar la generalidad de ningún otro término o condición de este Acuerdo, nada en este Acuerdo pretende representar o implicar que la Empresa o el Servicio de la Empresa tendrán acceso, a través de la X Ads API, a cualquier inventario o categoría particular de X Ads, y X puede (a su entera y absoluta discreción) elegir de vez en cuando, limitar, sin restricción, la asignación del inventario de X Ads al que la Empresa o el Servicio de la Empresa tengan acceso (por ejemplo, sin limitación, debido a las decisiones estratégicas de X relativas a los canales de venta, relaciones directas vs. no directas con clientes, relaciones de agencia, etc.).
### 6. Control de las Características, Llamadas a la API y Funcionalidades de X Ads.
Para mayor claridad, y sin limitar la generalidad de ningún otro término o condición de este Acuerdo, nada en este Acuerdo pretende representar o implicar que la Empresa o el Servicio de la Empresa tendrán acceso, a través de la X Ads API, a cualquier característica, llamada a la API o funcionalidad particular de X Ads, y X puede (a su entera y absoluta discreción) elegir de vez en cuando, limitar, sin restricción, aquellas características, llamadas a la API y/o funcionalidades de X Ads a las que la Empresa o el Servicio de la Empresa tengan acceso (por cualquier motivo o sin motivo).
### 7. Datos Geográficos.
La Empresa no (ni permitirá a otros) utilizar o acceder a la X Ads API para agregar, almacenar en caché o guardar información de lugar u otra información de ubicación geográfica contenida en cualquier Dato o de otro modo.
### 8. Eliminaciones.
Cuando lo solicite X, a través de la X Ads API o de otro modo, la Empresa prontamente: (a) eliminará los Datos del Servicio de la Empresa que X informe como eliminados o vencidos; (b) cambiará el tratamiento por parte de la Empresa de los Datos que X informe que están sujetos a opciones de intercambio modificadas; y (c) modificará los Datos en el Servicio de la Empresa que X informe que han sido modificados. La Empresa es responsable de la calidad de los X Ads transmitidos al Servicio de X por el Servicio de la Empresa. X se reserva el derecho de revocar el acceso a la X Ads API y/o, si corresponde, eliminar cualquier X Ads específico del Servicio de X por cualquier uso objetable por parte de la Empresa o los Clientes.
### 9. Actualizaciones.
La Empresa reconoce que X puede actualizar o modificar la X Ads API, de vez en cuando, y a entera y absoluta discreción de X (en cada caso, una "**Actualización**"). A menos que se acuerde mutuamente por escrito con anticipación entre X y la Empresa (siendo suficiente un correo electrónico), la Empresa está obligada a implementar y utilizar la versión más actual de la X Ads API y a realizar cualquier cambio en el Servicio de la Empresa, a costo y gasto exclusivo de la Empresa, que sean necesarios como resultado de dicha Actualización, no más tarde de treinta (30) días desde la fecha en que X notifique a la Empresa de la Actualización. La Empresa implementará todas las herramientas (si las hay) proporcionadas por X para habilitar las Actualizaciones, según corresponda. Las Actualizaciones pueden afectar negativamente la manera en que el Servicio de la Empresa accede a o se comunica con la X Ads API o muestra los Datos. El acceso o uso continuo por parte de la Empresa de la X Ads API después de cualquier tal Actualización constituirá la aceptación vinculante de la Actualización.
### 10. Soporte.
La Empresa es responsable de proporcionar todo el soporte y asistencia técnica a los Clientes y a sus Usuarios Finales relativos al uso del Servicio de la Empresa (incluyendo cualquier problema relacionado con cualquier Producto de Anuncios). X no está obligada a proporcionar soporte o asistencia técnica directamente a la Empresa ni a los Clientes ni a ninguno de sus Usuarios Finales, y la Empresa no representará ante ningún Cliente ni ante ninguno de sus Usuarios Finales que X está disponible para proporcionar dicho soporte.
## Anexo A-1: Requisitos del Producto
El Servicio de la Empresa debe permitir a los especialistas en marketing optimizar más eficientemente las campañas de X Ads, aprovechar la conversación en tiempo real de X y desarrollar X Ads que mejoren la experiencia del usuario.
En consecuencia, el Servicio de la Empresa, en todo momento, cumplirá los siguientes requisitos:
### 1. Precios del Producto. Sin Monetización.
El acceso pagado al Servicio de la Empresa debe tener un precio basado en una estructura de tarifas de porcentaje fijo o variable del gasto. La Empresa no cobrará a los Clientes un sobreprecio por el acceso a X Ads y/o Datos a través del Servicio de la Empresa que exceda las tarifas estándar de la Empresa por el Servicio de la Empresa.
### 2. Transparencia.
**2.1 Gasto.**
2.1.1 Cualquier informe de precios entregado por la Empresa a los Clientes y a sus Usuarios Finales debe indicar claramente y desglosar (i) el gasto de X Ads en las métricas nativas de X (por ejemplo, según corresponda, CPE/CPF) y (ii) las tarifas cobradas por el uso del Servicio de la Empresa. Además, la Empresa siempre debe incluir métricas de CPE o CPF (u otras métricas nativas de X aplicables) junto a métricas de atribución de último clic (por ejemplo, CPC) u otras métricas de informe (por ejemplo, CPM).
2.1.2 El Servicio de la Empresa incluirá un panel de informes de autoservicio que incluirá la capacidad para que la Empresa informe sobre todas las métricas proporcionadas a través de la X Ads API.
**2.2 Datos.** La Empresa: (i) utilizará esfuerzos comercialmente razonables para mantener Datos actualizados dentro del Servicio de la Empresa en relación con la Integración de X (definida a continuación en la Sección 6.3 de este Anexo A-1) de conformidad con los Requisitos de Visualización de Datos Analíticos vigentes en ese momento; y (ii) divulgará claramente a los Clientes y a sus Usuarios Finales cualquier retraso material inherente a cualquier información sobre las Campañas de X Ads del Cliente y/o los datos analíticos relacionados.
### 3. Cuentas.
A cada Usuario Final se le debe otorgar una cuenta separada para acceder al Servicio de la Empresa, incluyendo un nombre de usuario y contraseña únicos.
### 4. Servicio de la Empresa.
Cada versión personalizada del Servicio de la Empresa para un Cliente específico (incluyendo, sin limitación, una versión de marca blanca del Servicio de la Empresa para un Cliente específico) debe ser aprobada por X con anticipación y por escrito (siendo suficiente el correo electrónico para tales efectos).
### 5. Clientes y Gestión de Cuentas.
**5.1** A un Cliente se le debe otorgar la capacidad de desasociar rápida y fácilmente sus Campañas de X Ads del Servicio de la Empresa y recuperar el control exclusivo y directo de su(s) cuenta(s) de X Ads.
**5.2** Solo un Cliente y sus Usuarios Finales pueden ser autorizados a ver los datos o características de la cuenta de dicho Cliente a través del Servicio de la Empresa.
### 6. Otros Requisitos.
**6.1** Cualquier funcionalidad del Servicio de la Empresa que replique una característica de X utilizará la nomenclatura de nombres y los nombres de características de X, sujeto a cualquier Directriz de Marca Registrada de X aplicable.
**6.2** A menos que se acuerde mutuamente entre las partes con anticipación y por escrito, la Empresa no proporcionará a los Clientes y a sus Usuarios Finales ni a ningún otro tercero acceso a los Datos, excepto por las derivaciones agregadas de dicho material incorporadas en la interfaz de usuario del Servicio de la Empresa.
**6.3** La Empresa no puede comercializar, mercadear ni proporcionar acceso a ningún Material de X a ningún tercero (incluyendo cualquier Cliente o sus Usuarios Finales) hasta que la implementación de la X Ads API y la integración y visualización de cualquier Dato dentro del Servicio de la Empresa (colectivamente, la "**Integración de X**") haya sido aprobada con anticipación por X a través del proceso descrito en esta Sección. La Empresa dará a X acceso al Servicio de la Empresa para que X pueda revisar la Integración de X. X informará a la Empresa por escrito (siendo suficiente el correo electrónico) si la Integración de X está aprobada o rechazada (a entera discreción de X). Durante todo el Plazo, la Empresa enviará a X cualquier cambio en el Servicio de la Empresa que afecte la Integración de X, la cual X tendrá el derecho de aprobar o rechazar por escrito (siendo suficiente el correo electrónico), a entera discreción de X.
## Anexo A-2: Requisitos de Visualización de Datos Analíticos
Estos Requisitos de Visualización de Datos Analíticos rigen cómo la Empresa puede mostrar Datos dentro del Servicio de la Empresa. La Empresa acepta cumplir con estos Requisitos de Visualización de Datos Analíticos en todo momento.
### Métricas Definidas
Todas las campañas mostradas en el Servicio de la Empresa que muestren Datos deben incluir las métricas específicas definidas por X asociadas con los diversos objetivos de campaña (cada uno, un "**Objetivo de Campaña**"), métricas que deben ser calculadas por la Empresa con base en los endpoints y fórmulas ubicados en: [https://docs.x.com/x-ads-api/analytics#metrics-by-objective](https://docs.x.com/x-ads-api/analytics#metrics-by-objective) (o cualquier otra URL sucesora que X pueda elegir de vez en cuando).
### Directrices de Visualización
**1.** Las métricas definidas aplicables para un determinado Objetivo de Campaña (como se describe anteriormente en la sección Métricas Definidas de este Anexo A-2) deben mostrarse cada vez que se muestre una campaña dentro del Servicio de la Empresa.
**2.** Si el Servicio de la Empresa muestra cualquier dato analítico orgánico de publicaciones, la Empresa debe cumplir con el Acuerdo y Política del Desarrollador de X ubicado en: [https://docs.x.com/developer-terms/agreement](/developer-terms/agreement) en lo que respecta a la implementación, uso y visualización por parte de la Empresa de los datos analíticos orgánicos de las publicaciones.
**3.** Si el Servicio de la Empresa muestra métricas sobre campañas ejecutadas en redes de terceros o por editores terceros (es decir, "métricas multicanal") junto a los Datos, entonces se aplican los siguientes requisitos y restricciones:
**3.1** Cualquier métrica multicanal mostrada junto con los Datos en el Servicio de la Empresa solo puede incluir la misma categoría de métricas de objetivo de campaña que las métricas de Objetivo de Campaña definidas por X aplicables para dicha campaña (como se describe anteriormente en la sección Métricas Definidas de este Anexo A-2).
A modo de ejemplo únicamente - Si un anunciante ejecuta una campaña de instalación de aplicaciones en una red de terceros, solo se pueden mostrar junto a los Datos las métricas multicanal que sean de la misma categoría que las métricas definidas por X aplicables para el Objetivo de Campaña de instalación de aplicaciones.
**3.2** No se permite agregar datos para mostrar métricas multicanal a menos que las métricas agregadas puedan ser referenciadas (a través de todas las redes/editores de terceros) contra una categoría de métricas asociadas con un objetivo de campaña que sea igual a las métricas de Objetivo de Campaña definidas por X aplicables (como se describe anteriormente en la sección Métricas Definidas de este Anexo A-2). A modo de ejemplo únicamente - No se permitiría agregar las interacciones totales para la red A, la red B y la red C si las tasas de interacción a través de todos los canales no se calculan utilizando las mismas fórmulas.
**4.** Si el Servicio de la Empresa muestra cualquier categoría de métricas obtenidas de terceros distintos a X ("**métricas obtenidas de terceros**"), entonces se aplican los siguientes requisitos y restricciones:
**4.1** Los mismos requisitos y restricciones que se aplican a la visualización de métricas multicanal establecidos anteriormente en la Sección 3 se aplican a la visualización de cualquier métrica obtenida de terceros.
**4.2.** Cualquier métrica obtenida de terceros que se muestre junto a los Datos para una campaña en el Servicio de la Empresa debe ser de la misma categoría de métricas de objetivo de campaña que las métricas de Objetivo de Campaña definidas por X aplicables para dicha campaña (como se describe anteriormente en la sección Métricas Definidas de este Anexo A-2). A modo de ejemplo únicamente:
* Si la Empresa muestra métricas de clic en enlace y tasa de clic de una fuente de terceros, la Empresa mostrará las métricas de clic y tasa de clic de X junto a las métricas de clic en enlace y tasa de clic obtenidas de terceros.
* Si la Empresa o alguno de sus Clientes utiliza una solución de seguimiento de terceros para hacer seguimiento de los clics al sitio web desde publicaciones Promocionadas y dichos datos se muestran en el Servicio de la Empresa, la Empresa debe mostrar los clics en enlace, la tasa de clics, el costo por clic en enlace y el CPA de X (si están disponibles) junto a dichos datos obtenidos de terceros.
**4.3** No obstante la Sección 4.2 de este Anexo A-2, si las métricas obtenidas de terceros provienen de una solución de seguimiento de terceros proporcionada por un Socio de Seguimiento de Conversiones de X (según se define a continuación), entonces X requiere que solo los Datos entregados a través de la X Ads API (y no los datos correspondientes entregados por el Socio de Seguimiento de Conversiones de X) se muestren en el Servicio de la Empresa, a menos que X acuerde lo contrario por escrito con anticipación (en cada caso). Para evitar dudas, la Empresa no mostrará ningún dato obtenido de un Socio de Seguimiento de Conversiones de X junto con, o en lugar de, cualquier Dato entregado a través de la X Ads API. Tal como se utiliza en este Anexo A-2, "**Socio de Seguimiento de Conversiones de X**" significa un socio autorizado de seguimiento de conversiones de X (según lo designe X, a su entera y absoluta discreción).
## Anexo B: Términos de Producto Individual/Audiencias Personalizadas
Los términos con mayúscula inicial no definidos en estos Términos de Producto Individual tienen el significado establecido en el cuerpo principal del Acuerdo. En la medida en que la Empresa utilice o acceda al Programa de Audiencias Personalizadas de X, se aplicarán los siguientes términos y condiciones de este Anexo B:
### 1. Audiencias Personalizadas.
**1.1 Introducción.** El Programa de Audiencias Personalizadas de X permite la importación y creación de segmentos específicos de usuarios (cada uno, una "**Audiencia Personalizada**") para la segmentación de Campañas publicitarias en el Servicio de X. Las partes reconocen que para utilizar el Programa de Audiencias Personalizadas de X, la Empresa, su Cliente o un proveedor de servicios externo aprobado por X ("**Socio de Datos**") debe proporcionar a X un conjunto hasheado de usuarios o dispositivos (que puede incluir correo electrónico, cookies, ID de dispositivos, píxeles de seguimiento, etc.) para que X pueda completar una coincidencia con los usuarios de X y crear Audiencias Personalizadas. Las Audiencias Personalizadas creadas en nombre de un(os) cliente(s) específico(s) se almacenarán en la cuenta de X Ads de cada uno de dichos Clientes para su uso por parte de la Empresa o del Cliente para segmentar o retargetear, según corresponda, publicidad en el Servicio de X.
**1.2 Uso de Datos y Exclusión.** Con respecto a cualquier dato utilizado en relación con el Programa de Audiencias Personalizadas, además de las obligaciones establecidas en el Adendum de Protección de Datos que se encuentra en [https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa), la Empresa acepta y, si corresponde, se asegurará de que su(s) Socio(s) de Datos acepten que (i) la Empresa o dicho Socio de Datos (según corresponda) hayan asegurado todos los derechos, consentimientos, renuncias y licencias necesarios para el uso de dichos datos, y (ii) que la Empresa o dicho Socio de Datos (según corresponda) hayan proporcionado a los usuarios de los que se recopilan los datos un aviso legalmente suficiente que divulgue plenamente la recopilación, uso e intercambio de los datos que la Empresa proporciona a X con el propósito de servir anuncios dirigidos a los intereses de los usuarios, e instrucciones legalmente suficientes sobre cómo los usuarios pueden optar por no participar en la publicidad basada en intereses de X a través de los métodos descritos aquí ([https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads](https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads)). Los datos que la Empresa utilice en relación con el Programa de Audiencias Personalizadas y/o para crear una Audiencia Personalizada no incluirán ningún dato de ningún usuario que haya optado por no permitir que sus datos sean utilizados por la Empresa, su Socio de Datos o cualquier tercero en nombre de la Empresa. Si la Empresa recibe una exclusión del usuario después de que dicho usuario haya sido incluido en una audiencia proporcionada a X, la Empresa debe eliminar prontamente, pero no menos de una vez cada veinticuatro (24) horas, a dicho(s) usuario(s) de cualquier Audiencia Personalizada en la que dicho usuario haya sido incluido. La Empresa proporcionará los datos en un formato seleccionado por X y aceptable para el Socio de Datos (si/según corresponda). Además de los términos y condiciones de este Acuerdo, el uso por parte de la Empresa del Programa de Audiencias Personalizadas de X estará sujeto a los términos del [Acuerdo Maestro de Servicios de X](https://legal.x.com/ads-terms.html) y a los T\&C del Programa de Audiencias Personalizadas y a las políticas aplicables, incluidas las Políticas para el Seguimiento de Conversiones y las Audiencias Personalizadas de X, en [https://legal.x.com/ads-terms.html](https://legal.x.com/ads-terms.html) y [https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences).
**1.3 Requisitos Adicionales del Programa.** El acceso y uso por parte de la Empresa del Programa de Audiencias Personalizadas de X está adicionalmente sujeto a su cumplimiento con las instrucciones técnicas y las políticas del programa proporcionadas por X a la Empresa (la "**Especificación de Integración del Programa**"). La Empresa y X acordarán mutuamente un proceso para que la Empresa importe o cargue Audiencias Personalizadas a X.
### 2. Audiencias Compartibles.
No obstante cualquier disposición en contrario establecida en la Sección 1.1 anterior, como un servicio a la Empresa, a solicitud de la Empresa y a entera discreción de la Empresa, X puede permitir a la Empresa "compartir" Audiencias Personalizadas creadas para la Empresa entre cuentas agrupadas de anunciantes de X y/o @handles de X y/o de otro modo con terceros en el Servicio de X. Tal como se utiliza en el presente, "compartir" una audiencia significa que la Empresa instruiría a X para, sin limitación, permitir a las cuentas agrupadas de Anunciantes de X y/o @handles de X y/o terceros acceder, utilizar y segmentar Campañas publicitarias contra la Audiencia Personalizada "compartida". La Empresa declara y garantiza que tiene todos los derechos y autoridad necesarios para compartir dichos datos de audiencia de conformidad con las instrucciones dadas a X por la Empresa. Si la Empresa está proporcionando los datos de audiencia y/o gestionando las Audiencias Personalizadas en nombre de un tercero (incluyendo, sin limitación, un Cliente), la Empresa declara y garantiza que la Empresa tiene la autoridad como agente de dicha parte para utilizar dichos datos en nombre del tercero, para otorgar a X los derechos descritos en el presente, y para vincular a dicho tercero a los términos de este Acuerdo. No obstante lo anterior, nada en esta Sección exige a X poner a disposición la funcionalidad que permite "compartir" Audiencias Personalizadas descritas en el presente (o cualquier parte de las mismas) en cualquier momento a la Empresa o a cualquier otro tercero (incluyendo, sin limitación, cualquier Cliente).
## Anexo C: Términos de Producto Individual/Programa X Marketing Partner (TMP)
Los términos con mayúscula inicial no definidos en estos Términos de Producto Individual tienen el significado establecido en el cuerpo principal del Acuerdo. En la medida en que la Empresa participe en el "programa X Marketing Partner" (el "**TMP**"), se aplicarán los siguientes términos y condiciones de este Anexo C (incluido el Anexo C-1):
### 1. Programa X Marketing Partner.
Si X aprueba la solicitud de la Empresa para el estatus de clasificación "Advanced", y la Empresa mantiene dicho estatus de clasificación durante todo el Plazo, X puede, en cualquier momento, elegir, a su entera y absoluta discreción, calificar a la Empresa como parte del TMP (o cualquier otro nombre de programa sucesor que X pueda seleccionar de vez en cuando). Para mayor claridad, X no está obligada a seleccionar a la Empresa para participar en el TMP, independientemente de si la Empresa ha alcanzado o mantenido el estatus de clasificación "Advanced". Además, X puede, en cualquier momento, elegir, a su entera y absoluta discreción, rescindir o suspender la participación de la Empresa en el TMP por cualquier motivo tras un aviso a la Empresa, en cuyo caso, la elegibilidad de la Empresa para recibir cualquier beneficio asociado con la participación en el TMP cesará inmediatamente (sin ningún aviso adicional de X sobre dicha decisión). Además de las Directrices de Marca Registrada de X que rigen el uso por parte de la Empresa de cualquier Marca de X, la Empresa también debe cumplir con los términos y condiciones establecidos en el Anexo C-1 que rigen el uso de las Insignias (según se definen en el Anexo C-1) proporcionadas por X en relación con la participación en el TMP. Todas las Insignias (según se definen en el Anexo C-1) se consideran Marcas de X bajo el Acuerdo.
### 2. Sin Uso de Insignias Fuera del TMP.
Para evitar dudas, si la Empresa no está actualmente calificada por X (a su entera y absoluta discreción) como miembro del TMP, (i) la Empresa no es elegible para recibir ningún beneficio asociado con la participación en el TMP, incluyendo, sin limitación, el uso de cualquier Insignia (según se define en el Anexo C-1) y (ii) a la Empresa se le prohíbe sugerir que participa en, o tiene cualquier afiliación con, el TMP.
## Anexo C-1: Términos del Programa X Marketing Partner
Los Términos del Programa X Marketing Partner establecidos a continuación, incluyendo, sin limitación, cualquier término y condición enlazado que aparezca o se referencie a continuación, que por el presente se incorporan por referencia (colectivamente, "**Términos del Socio TMP**"), rigen la participación en el programa "X Marketing Partner". En la medida en que la Empresa sea calificada por X, a su entera y absoluta discreción, para participar en el programa "X Marketing Partner", la Empresa acepta cumplir con los términos y condiciones de los Términos del Socio TMP en todo momento durante la participación de la Empresa en el programa "X Marketing Partner". Estos Términos del Socio TMP están sujetos y son regidos por el Acuerdo. Cualquier término con mayúscula inicial utilizado en este Anexo C-1 y no definido de otro modo en los Términos del Socio TMP tendrá los significados que se les atribuyan en el Acuerdo.
### 1. Programa TMP.
Tras la notificación de X a la Empresa de que X ha calificado a la Empresa como "X Marketing Partner", el Socio será miembro del programa "X Marketing Partner", tal como se describe en [https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners) y se le dará acceso a las insignias del TMP y a cualquier otra marca asociada que X ponga a disposición en relación con el TMP (colectivamente, las "**Insignias**"), cuyo uso está sujeto a los términos y condiciones de este Acuerdo.
### 2. Licencia de X.
Sujeto a los términos y condiciones de estos Términos del Socio TMP, y condicionado al cumplimiento continuo por parte de la Empresa de este Acuerdo, X por el presente otorga a la Empresa, y la Empresa acepta, una licencia no exclusiva, libre de regalías, no transferible, no sublicenciable y revocable para copiar y mostrar las Insignias únicamente con, y para promover, la calificación de la Empresa como "X Marketing Partner" en el TMP.
### 3. Restricciones.
Se requiere el cumplimiento estricto de este Acuerdo en todo momento, y cualquier uso de las Insignias en violación de este Acuerdo terminará automáticamente cualquier licencia relacionada con el uso por parte de la Empresa de las Insignias.
**3.1** La Empresa no puede alterar las Insignias de ninguna manera, incluyendo, entre otras, cambiar la proporción, color o fuente de las Insignias, o agregar o eliminar cualquier elemento a o de las Insignias.
**3.2** La Empresa no puede utilizar las Insignias de ninguna manera que implique un falso sentido de patrocinio o respaldo por X.
**3.3** La Empresa no puede utilizar las Insignias para desprestigiar a X, sus productos o servicios, ni de una manera que, a entera discreción de X, pueda disminuir o empañar el fondo de comercio de X en las Insignias.
**3.4** La Empresa no puede utilizar las Insignias para referirse a cualquier otro producto o servicio que no sean los productos y/o servicios de X o de la Empresa relacionados con la participación de la Empresa en el TMP.
**3.5** Las Insignias deben aparecer por sí mismas, con un espaciado razonable entre cada lado de las marcas, y otros elementos visuales, gráficos o textuales.
**3.6** Las Insignias no deben presentarse ni colocarse de ninguna manera que interfiera con la legibilidad o visualización de la totalidad de las Insignias.
**3.7** La Empresa debe enlazar todas las Insignias a [https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners) (o cualquier otra URL sucesora que X pueda elegir de vez en cuando) o de otro modo mostrar la siguiente atribución en cualquier material que muestre las Insignias: "La insignia del programa 'X Marketing Partner', X y el logotipo de X son marcas comerciales de X Corp. o sus afiliadas."
### 4. Requisitos del Programa.
El uso de las Insignias está además sujeto y regido, en todo momento, sin limitación, por las [Directrices de Marca Registrada de X](https://about.x.com/who-we-are/brand-toolkit) y cualquier otro requisito comunicado por X a la Empresa en relación con la participación en el TMP (colectivamente, los "**Requisitos del Programa TMP**"). La Empresa acepta los Requisitos del Programa TMP, que por el presente se incorporan por referencia y están disponibles en copia impresa a solicitud a X. Los Requisitos del Programa TMP no expanden ni extienden la licencia sobre las Insignias otorgada en el presente. La Empresa puede utilizar las Insignias únicamente con el propósito expresamente autorizado por X, y el uso por parte de la Empresa debe cumplir con la versión más actualizada de (i) estos Términos del Socio TMP, y (ii) los Requisitos del Programa TMP. En la medida en que haya cualquier conflicto o inconsistencia entre estos Términos del Socio TMP y los Requisitos del Socio TMP, prevalecerán estos Términos del Socio TMP.
### 5. Licencia a X.
La Empresa por el presente otorga a X una licencia totalmente pagada, no exclusiva, mundial y sublicenciable para: (i) utilizar y mostrar las marcas comerciales de la Empresa para su uso en relación con el TMP, (ii) utilizar el(los) producto(s) y/o servicio(s) de la Empresa relacionados con el TMP para la evaluación, prueba y auditoría interna, no comercial, de X, (iii) desarrollar y publicar casos de estudio u otros materiales que permitan a X destacar la calificación de la Empresa como "X Marketing Partner" en el TMP (incluyendo, sin limitación, el(los) producto(s) y/o servicio(s) de la Empresa relacionados con el TMP), y (iv) producir materiales de marketing en relación con el TMP relacionados con la calificación de la Empresa como "X Marketing Partner" en el TMP (incluyendo, sin limitación, el(los) producto(s) y/o servicio(s) de la Empresa relacionados con el TMP).
### 6. Calificación del Programa.
**6.1 Calificación del Programa.** X se reserva el derecho, de vez en cuando, de revisar la membresía de la Empresa en el TMP, y, a entera y absoluta discreción de X, de recalificar o descalificar a la Empresa de cualquier competencia dada y/o del TMP en su totalidad.
**6.2 Cambios en los Productos o Servicios de la Empresa.** En caso de que la Empresa planee realizar cualquier cambio material en el(los) producto(s) y/o servicio(s) de la Empresa relacionados con el TMP, la Empresa proporcionará a X al menos treinta (30) días calendario para revisar los productos o servicios actualizados de la Empresa antes de la liberación de dicho cambio para determinar si continúan calificando para el TMP. Los productos o servicios actualizados deben ser recalificados por X antes de cualquier uso adicional de las Insignias. X utilizará esfuerzos comercialmente razonables para responder a la solicitud de la Empresa de calificación en nuevas competencias. Si la Empresa se fusiona, es adquirida o de otro modo experimenta un cambio de control, en su totalidad o en parte, por cualquier tercero, ya sea voluntaria o involuntariamente y/o por operación de la ley (incluyendo, sin limitación, en relación con una fusión, adquisición o venta de activos, ya sea que la parte cedente sea la entidad superviviente o desaparecida), la Empresa debe presentar todos los productos y/o servicios de la Empresa relacionados con el TMP a X para su recalificación antes de cualquier uso adicional de las Insignias.
### 7. Suspensión y Rescisión.
X puede rescindir o suspender inmediatamente estos Términos del Socio TMP, cualquier derecho otorgado a la Empresa en el presente y/o la participación de la Empresa en el TMP, a su entera discreción en cualquier momento, por cualquier motivo, proporcionando un aviso a la Empresa. La Empresa puede rescindir su participación en el TMP proporcionando un aviso de noventa (90) días calendario a X. Tras la rescisión de estos Términos TMP y/o la rescisión de la participación de la Empresa en el TMP, todas las licencias otorgadas en el presente expirarán inmediatamente, y la Empresa debe cesar el uso de todas las Insignias. Ninguna de las partes será responsable ante la otra por ningún daño resultante únicamente de la rescisión de estos Términos del Socio TMP según lo permitido bajo este Acuerdo.
### 8. Modificaciones.
X se reserva los derechos, ejercitables a su entera discreción, de modificar los términos y condiciones de estos Términos del Socio TMP y/o las Insignias en cualquier momento y de tomar la acción apropiada contra cualquier uso no autorizado o no conforme de las Insignias. Si la Empresa tiene alguna pregunta sobre el uso de las Insignias, contacte a [trademarks@x.com](mailto:trademarks@x.com) para obtener asistencia, o escríbanos a: X Corp., Attention: Legal Department, 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
# Acuerdo del Desarrollador de X
Source: https://docs.x.com/es/developer-terms/agreement
El Acuerdo del Desarrollador de X establece los términos legales para el uso de la API de X y la plataforma para desarrolladores, cubriendo licencias, restricciones y obligaciones de cumplimiento.
Última actualización: 27 de abril de 2026
Al hacer clic en “Aceptar y suscribirse”, al continuar pagando la tarifa de suscripción recurrente para los Servicios de Pago, o al acceder o utilizar de cualquier otra manera cualquier Material Licenciado, aceptas los términos de nuestro Acuerdo. Las suscripciones se renuevan automáticamente hasta que se cancelan, tal como se describe a continuación. Se requiere un número de teléfono verificado para suscribirse. Si te has suscrito a través de otra plataforma, gestiona tu suscripción a través de esa plataforma.
Este Acuerdo del Desarrollador de X (“**Acuerdo**”) es un acuerdo legal vinculante entre tú (referido en este Acuerdo como “**tú**”) y X y rige tu acceso y uso del Material Licenciado (definido a continuación), incluidos los Servicios de Pago (definidos a continuación).
Al acceder o utilizar cualquier Material Licenciado (definido a continuación), o al hacer clic en un botón para aceptar los términos de este Acuerdo o el pago recurrente de la suscripción a los Servicios de Pago, aceptas quedar vinculado por los términos de este Acuerdo. Si no comprendes los términos aquí incluidos o no aceptas alguna parte de ellos, entonces no puedes usar ni acceder a ningún Material Licenciado. No puedes utilizar el Material Licenciado ni aceptar este Acuerdo si no tienes la edad legal para celebrar un contrato vinculante con X o si tienes prohibido usar o recibir el Material Licenciado bajo la ley aplicable. Para comprar y usar un Servicio de Pago debes: (i) tener al menos 18 años o la mayoría de edad según las leyes de la jurisdicción en la que vivas, o (ii) contar con el consentimiento expreso de tu padre, madre o tutor para comprar y usar ese Servicio de Pago. Si eres padre, madre o tutor legal y permites que tu hijo/a (o un/a menor del que seas tutor) compre o use un Servicio de Pago, aceptas que los términos de este Acuerdo se apliquen a ti, que cumplirás con este Acuerdo, y que eres responsable de la actividad del menor en los Servicios de Pago y de asegurar que el menor también cumpla con los términos de este Acuerdo. En cualquier caso, tal como se indica en la sección Quién puede usar los Servicios de los [**Términos de Servicio de X**](https://x.com/tos), debes tener al menos 13 años para usar los “Servicios” tal como se definen en los Términos de Servicio de X. Si aceptas este Acuerdo o utilizas el Material Licenciado en nombre de una empresa, organización, gobierno u otra entidad legal, declaras y garantizas que tienes la autoridad para vincular a dicha empresa, organización, gobierno u otra entidad legal a este Acuerdo, en cuyo caso las palabras “tú” y “tu/tus” tal como se utilizan en este Acuerdo se referirán a dicha entidad. Si no estás de acuerdo con los términos de este Acuerdo, no puedes (y no puedes permitir a ninguno de tu personal) acceder o utilizar el Material Licenciado.\*\*\*\*
**I. Definiciones.**
En este Acuerdo, se aplican las siguientes definiciones:
1. “**Sitio para Desarrolladores**” significa el sitio para desarrolladores de X ubicado en [**https://developer.x.com/**](https://developer.x.com/)
2. “**Mensaje Directo**” significa un mensaje privado que se envía en las Aplicaciones de X por un usuario a uno o más usuarios específicos utilizando la función de mensajería directa de X.
3. “**Derechos de Propiedad Intelectual**” significa todos los derechos de autor, derechos morales, derechos de patente, marcas comerciales y cualquier otra propiedad intelectual o derechos similares (registrados o no) en todo el mundo.
4. “**Material Licenciado**” significa, individual o colectivamente, la API de X y el Contenido de X.
5. "**Servicio(s) de Pago**” significa características o funcionalidades del Material Licenciado a las que accedes a cambio del pago de una tarifa recurrente, según corresponda a las características o funcionalidades pertinentes y a este Acuerdo. Salvo que se establezca lo contrario en este Acuerdo, todas las referencias a “Material Licenciado” incluyen los Servicios de Pago.
6. “**Portal de Pago**” significa el portal en línea que se pone a tu disposición para aceptar (opt-in) tu uso del Material Licenciado, gestionar suscripciones a los Servicios de Pago, gestionar métodos de pago para los Servicios de Pago y actualizar la información de la cuenta.
7. “**Servicios**” significa tus servicios, sitios web, aplicaciones y otras ofertas (incluidas las de investigación) que muestren Contenido de X o que utilicen de otro modo el Material Licenciado.
8. “**Publicación**” significa un mensaje corto basado en texto y multimedia distribuido a través de las Aplicaciones de X.
9. “**X**” significa (a) X Corp. (865 FM 1209, Building 2, Bastrop, TX 78602, USA) si tu principal lugar de negocios está fuera de la Unión Europea, los Estados de la AELC (EFTA) y el Reino Unido; o (b) X Internet Unlimited Company (One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland) si tu principal lugar de negocios está en la Unión Europea, los Estados de la AELC (EFTA) o el Reino Unido.
10. “**API de X**” significa las Interfaces de Programación de Aplicaciones (cada una, una **“API”**) de X, los Kits de Desarrollo de Software (cada uno, un **“SDK”**), y las herramientas, documentación, datos, tecnología, código y otros materiales relacionados proporcionados por X a través del Sitio para Desarrolladores.
11. “**Aplicaciones de X**” significa el servicio de información en tiempo real de X, comúnmente conocido como “X”, que incluye los servicios actualmente proporcionados por X en sus sitios web y aplicaciones móviles propiedad, operadas o controladas por X, complementos sociales e interfaces de programación de aplicaciones.
12. “**Contenido de X**” significa las publicaciones, el número de identificación único generado para cada publicación, la información de perfil de los usuarios finales de X y cualquier otro dato e información puesta a tu disposición a través de la API de X o por cualquier otro medio autorizado por X, así como cualquier copia y obra derivada de los mismos.
13. “**Marcas de X**” significa el nombre, las marcas comerciales y los logotipos de X que X pone a tu disposición, incluso a través del Sitio para Desarrolladores, únicamente para su uso de acuerdo con este Acuerdo.
14. “**Usuarios**” significa los visitantes, usuarios o clientes de tus Servicios.
**II. API de X y Contenido de X.**
**A. Licencia de X.** Sujeto a tu cumplimiento con los términos de este Acuerdo y los Términos para Desarrolladores Incorporados aplicables (como se define a continuación), X te otorga una licencia no exclusiva, libre de regalías, no transferible, no sublicenciable y revocable únicamente para:
1. Utilizar la API de X para integrar Contenido de X en tus Servicios o realizar análisis del Contenido de X, tal como haya sido aprobado explícitamente por X;
2. Copiar una cantidad razonable de y mostrar el Contenido de X en y a través de tus Servicios a los Usuarios, según lo permita este Acuerdo;
3. Modificar el Contenido de X únicamente para darle formato para su visualización en tus Servicios; y
4. Utilizar y mostrar las Marcas de X para atribuir a las Aplicaciones de X como fuente del Contenido de X, según lo establecido en este Acuerdo.
**B. Licencia a X.** Por la presente otorgas a X una licencia no exclusiva, libre de regalías, no transferible y no sublicenciable revocable para acceder, indexar y almacenar en caché por cualquier medio, incluidos web spiders y/o crawlers, cualquier página web o aplicación en la que muestres Contenido de X utilizando [**publicaciones incrustadas**](https://developer.x.com/docs/twitter-for-websites/embedded-tweets/overview) o [**cronologías incrustadas**](https://developer.x.com/docs/twitter-for-websites/timelines/overview).
**C. Términos Incorporados.** Tu acceso y uso del Material Licenciado también está sujeto, y deberás cumplir, con los siguientes términos y políticas adicionales (colectivamente, “**Términos para Desarrolladores Incorporados**”):
1. la [**Política del Desarrollador de X**](/developer-terms/policy);
2. las [\*\* Reglas de Uso Restringido de la API\*\*](/developer-terms/restricted-use-cases);
3. las [**Reglas de X**](https://help.x.com/rules-and-policies/x-rules);
4. en lo que se refiere a tu visualización de cualquier Contenido de X, los [**Requisitos de Visualización**](https://developer.x.com/developer-terms/display-requirements.html);
5. en lo que se refiere a tu uso y visualización de las Marcas de X, las [**Directrices de Marca de X**](https://about.x.com/who-we-are/brand-toolkit); y
6. en lo que se refiere a la realización de acciones automatizadas en tu cuenta, las [**Reglas de Automatización**](https://help.x.com/rules-and-policies/x-automation).
**III. Restricciones de Uso.**
**A. Ingeniería Inversa y otras Restricciones.** No deberás, ni intentarás (ni permitirás a otros): (a) realizar ingeniería inversa, descompilar, desensamblar o traducir la API de X ni intentar de otro modo derivar el código fuente, secretos comerciales o conocimientos técnicos (know-how) subyacentes a cualquier API de X o cualquier parte de la misma; (b) interferir, modificar, interrumpir o deshabilitar funciones o funcionalidades de la API de X o los mecanismos de monitoreo de la API de X; (c) usar o acceder al Material Licenciado para crear o intentar crear un servicio o producto sustituto o similar a las Aplicaciones de X; (d) vender, alquilar, arrendar, sublicenciar, distribuir, redistribuir, sindicar, crear obras derivadas de, asignar o transferir o proporcionar acceso de otro modo, total o parcialmente, al Material Licenciado a un tercero, excepto según lo expresamente permitido en este Acuerdo; (e) proporcionar el uso de la API de X en base a service bureau, alquiler o servicios administrados, o permitir a otras personas o entidades crear enlaces a la API de X, o hacer “frame” o “mirror” de la API de X en cualquier otro servidor, o dispositivo inalámbrico o basado en Internet, o poner a disposición de un tercero cualquier token, clave, contraseña u otras credenciales de inicio de sesión de la API de X; (f) utilizar el Material Licenciado para cualquier fin ilegal, no autorizado o cualquier otro fin indebido; (g) utilizar el Material Licenciado para derivar u obtener información no pública de usuarios individuales de X; (h) interferir o interrumpir la integridad o el rendimiento de las Aplicaciones de X, la API de X o el Contenido de X contenido en las mismas; (i) eliminar o alterar cualquier aviso o marca de propiedad en el Contenido de X; (j) intentar obtener acceso no autorizado a las Aplicaciones de X, la API de X, el Contenido de X o sistemas o redes relacionados; (k) utilizar la API de X o el Contenido de X para hacer fine-tuning o entrenar un modelo fundacional o frontera; o (l) utilizar el Contenido de X, por sí solo o combinado con datos de terceros, o análisis derivados del mismo, para dirigirse a los usuarios con publicidad fuera de las Aplicaciones de X.
**B. Restricciones de Uso Comercial.** Si tus Servicios están designados como “no comerciales”, no deberás hacer Uso Comercial (como se define a continuación) del Material Licenciado. Las restricciones de Uso Comercial pueden no aplicarse a organizaciones sin fines de lucro registradas oficialmente u ONG. “**Uso Comercial**” significa cualquier uso del Material Licenciado o acceso a la API de X: (a) por parte de o para un negocio (es decir, una entidad cuyo propósito principal es obtener ingresos a través de un producto o servicio), o (b) como parte de un producto o servicio que se monetiza (por ejemplo, publicidad en el sitio web, tarifas de licencia, promociones dentro de la aplicación y patrocinios).
**C. Sin Monitoreo ni Medición.** No obstante cualquier disposición en contrario, puedes utilizar la siguiente información únicamente con fines internos y no comerciales (por ejemplo, para mejorar la funcionalidad de los Servicios): (a) métricas agregadas de usuarios de las Aplicaciones de X, como el número de usuarios o cuentas activos en las Aplicaciones de X; (b) la capacidad de respuesta de las Aplicaciones de X; y (c) resultados, estadísticas de uso, datos u otra información (agregada o de otro modo) derivada del análisis, uso o rendimiento de la API de X. Toda esta información constituye Información Confidencial (como se define a continuación).
**D. Límites de Tasa.** No intentarás exceder ni eludir las limitaciones sobre el acceso, las llamadas y el uso de la API de X ("**Límites de Tasa**") ni utilizarás la API de X de otro modo que exceda un volumen razonable de solicitudes, constituya un uso excesivo o abusivo, o que de otro modo no cumpla con este Acuerdo. Si excedes o X cree razonablemente que has intentado eludir los Límites de Tasa, los controles para limitar el uso de las APIs de X o los términos de este Acuerdo, entonces tu capacidad para usar el Material Licenciado podrá ser suspendida temporalmente o bloqueada permanentemente. X puede monitorear tu uso de la API de X para mejorar el Material Licenciado y las Aplicaciones de X, y para asegurar tu cumplimiento con este Acuerdo y los Términos para Desarrolladores Incorporados.
**E. Datos de Ubicación.** No deberás, ni permitirás a otros, agregar, almacenar en caché o almacenar datos de ubicación y otra información geográfica contenida en el Contenido de X excepto en conjunción con el Contenido de X al que se adjuntan. Solo puedes usar los datos de ubicación y la información geográfica para identificar la ubicación etiquetada por el Contenido de X.
**F. Uso de las Marcas de X.** No deberás incluir ninguna de las Marcas de X en tu(s) nombre(s) corporativo(s) registrado(s), tus logotipos ni tus nombres de servicio o producto. No deberás crear obras derivadas de las Marcas de X ni utilizar las Marcas de X de manera que cree o razonablemente implique un respaldo, patrocinio o asociación con X. Todo uso de las Marcas de X y toda buena voluntad (goodwill) que surja del uso redundarán en beneficio de X. No eliminarás ni alterarás ningún aviso o Marca de X de propiedad en el Material Licenciado.
**G. Seguridad.** Mantendrás la seguridad de la API de X y no pondrás a disposición de ningún tercero ningún token, clave, contraseña u otras credenciales de inicio de sesión de la API de X. Utilizarás medidas de seguridad estándar del sector para prevenir el acceso o uso no autorizado de cualquier función y funcionalidad de la API de X, incluido el acceso por virus, gusanos o cualquier otro código o material dañino. Mantendrás el Contenido de X confidencial y seguro contra el acceso no autorizado utilizando salvaguardas organizativas y técnicas estándar del sector para dichos datos, y con no menos cuidado del que utilizas al asegurar datos similares que almacenas. Notificarás inmediatamente a X, consultarás y cooperarás con las investigaciones, asistirás con cualquier notificación requerida y proporcionarás cualquier información razonablemente solicitada por X si tienes conocimiento o sospechas de cualquier violación de seguridad o posible vulnerabilidad relacionada con el Material Licenciado. Remediarás con prontitud cualquier violación o posible vulnerabilidad resultante de tu acceso al Material Licenciado.
**H. Ley de Servicios Digitales.** No obstante cualquier disposición en contrario en este Acuerdo, en la medida en que se te proporcione acceso al Material Licenciado conforme a los procedimientos descritos en el Artículo 40 de la Ley de Servicios Digitales (Reglamento (UE) 2022/2065) (“DSA”), tu acceso y uso del Material Licenciado se limita únicamente a realizar investigaciones que contribuyan a la detección, identificación y comprensión de los riesgos sistémicos en la Unión Europea y solo en la medida necesaria para que X cumpla sus obligaciones bajo la DSA. Cualquier uso del Material Licenciado es no comercial, tal como se describe en la Sección III(B) de este Acuerdo. No puedes divulgar, reproducir, licenciar ni distribuir de otro modo el Material Licenciado (incluidas obras derivadas del mismo) que recuperes a través de la API de X a ninguna persona o entidad fuera de las personas especificadas en tu solicitud aprobada, a menos que (i) la información se divulgue al Coordinador de Servicios Digitales u otra parte permitida específicamente por la DSA conforme al estado y procedimientos de “investigador acreditado” descritos en el Artículo 40, o (ii) la divulgación sea requerida por la ley.
**I. Tokens.** X puede limitar el número de tokens que te proporciona, incluidos, entre otros, los tokens que permiten el acceso y uso de funcionalidades o características en las Aplicaciones de X.
**J. Niveles de Acceso.** X proporciona diferentes niveles (tiers) de acceso (como se describe en [developer.x.com](http://developer.x.com)) al Material Licenciado, y deberás suscribirte al nivel que mejor se adapte a tu caso de uso. X puede, en cualquier momento, revisar tu uso de sus Materiales Licenciados y requerir un cambio en el nivel de acceso al que estás suscrito, incluida, entre otras cosas, la solicitud de acceso Enterprise (como se describe en [developer.x.com](http://developer.x.com)).
**K. Prohibición del uso de I-Frames:** Bajo ninguna circunstancia deberás incrustar, mostrar o incorporar de otro modo cualquier Material Licenciado, Contenido de X, API de X o elementos de las Aplicaciones de X dentro de un iframe, inline frame o cualquier mecanismo de incrustación similar en tus Servicios o cualquier otra plataforma. Esta prohibición es absoluta e incluye, entre otras cosas, los intentos de frame de Contenido de X con fines de visualización, integración o redistribución. La violación de esta cláusula puede resultar en la terminación inmediata de tu Acuerdo del Desarrollador y tu acceso al Material Licenciado (por ejemplo, la API de X, la Licencia de Datos de X, la Consola de Desarrollador), como se describe en la Sección VII.I.
**L. Uso Autoservicio (Self-Serve).** Los planes Pay-Per-Use, Basic y Pro (como se describe en [developer.x.com](https://developer.x.com)) están diseñados para aficionados, prototipos comerciales, desarrollo inicial, integraciones tempranas de productos X y aplicaciones de soporte con un número limitado de usuarios finales. Si utilizas la API de X más allá de este alcance, entonces debes solicitar (o ya estar suscrito) un plan Enterprise (como se describe en [developer.x.com](https://developer.x.com)).
**M. Uso Comercial:** Si utilizas la API de X más allá del alcance de proyectos de aficionados, prototipos comerciales, desarrollo inicial, integraciones tempranas de productos X, o para aplicaciones con un número limitado de usuarios finales, entonces debes solicitar (o ya estar suscrito) un plan Enterprise (como se describe en developer.x.com).
**IV. Actualizaciones y Eliminaciones.**
**A. Actualizaciones.** X puede actualizar, modificar o discontinuar cualquier característica o función del Material Licenciado, total o parcialmente, de vez en cuando (en cada caso, una “**Actualización**”). Implementarás y utilizarás la versión más actual del Material Licenciado y realizarás cualquier cambio en tus Servicios que sea requerido como resultado de la Actualización, a tu único costo. Las Actualizaciones pueden afectar adversamente la forma en que tus Servicios acceden o se comunican con la API de X o muestran el Contenido de X. X no será responsable de ningún tipo de daño resultante de cualquier Actualización.
**B. Eliminaciones.** Si el Contenido de X se elimina, obtiene estado protegido o es suspendido, retenido, modificado o eliminado de las Aplicaciones de X (incluida la eliminación de la información de ubicación), harás todos los esfuerzos razonables para eliminar o modificar ese Contenido de X (según corresponda) tan pronto como sea posible, y en cualquier caso dentro de las veinticuatro (24) horas después de una solicitud por escrito de X o de un usuario de X con respecto a su Contenido de X, salvo que esté prohibido por ley o regulación y con el permiso expreso por escrito de X.
**V. Propiedad, Betas y Comentarios.**
**A. Propiedad.** Excepto en la medida expresamente indicada en este Acuerdo, ninguna de las partes adquirirá ningún derecho, título o interés sobre los Derechos de Propiedad Intelectual propiedad o licenciados por la otra parte. El Material Licenciado se licencia, no se vende, y X (o sus licenciantes o los usuarios de las Aplicaciones de X, según corresponda) retiene y se reserva todos los derechos, incluidos todos los Derechos de Propiedad Intelectual, no otorgados expresamente en este Acuerdo. No harás nada incompatible con la propiedad de X, incluido sin limitación, cuestionar la propiedad de X sobre las Marcas de X, cuestionar la validez de las licencias otorgadas en este Acuerdo, o copiar o explotar de otro modo las Marcas de X excepto según lo específicamente autorizado en este Acuerdo. Si adquieres algún derecho sobre las Marcas de X o cualquier marca confusamente similar, por operación de la ley o de otro modo, deberás, sin costo alguno para X, asignar inmediatamente esos derechos a X.
**B. Betas.** X puede proporcionarte acceso anticipado a alfas, betas, estudios de investigación, pilotos, servicios de marketing u otros programas no generalmente disponibles de vez en cuando (cada uno, una “**Beta**”). Las Betas se considerarán Información Confidencial. Tu participación en cualquier Beta es a tu propio riesgo, puede estar sujeta a requisitos adicionales, y puede ayudar a X en la investigación, el análisis y la validación de programas, productos y/o herramientas existentes o potenciales.
**C. Comentarios.** X será libre de usar cualquier comentario, retroalimentación o sugerencia que le proporciones relacionados con X, el Material Licenciado, las Betas u otros productos o servicios de X (“**Comentarios**”) de cualquier manera sin compensación u obligación alguna hacia ti o cualquier tercero, y los Comentarios se considerarán Información Confidencial. Por la presente asignas irrevocablemente a X todo derecho, título e interés sobre los Comentarios.
**VI. Confidencialidad.**
Puedes tener acceso a información, software y especificaciones no públicas relacionadas con el Material Licenciado (“**Información Confidencial**”). Solo puedes usar la Información Confidencial según sea necesario para ejercer tus derechos bajo este Acuerdo. No deberás divulgar Información Confidencial a ningún tercero sin el consentimiento previo por escrito de X. Protegerás la Información Confidencial del uso, acceso o divulgación no autorizados de la misma manera que utilizarías para proteger tu propia información confidencial de naturaleza similar y en ningún caso con menos de un grado razonable de cuidado.
**VII. Plazo; Tarifas de Suscripción; Pago; Suspensión y Terminación.**
**A. Plazo.** El plazo de este Acuerdo comenzará en la fecha en que (i) aceptes los términos aquí incluidos o (ii) comiences a acceder o usar cualquier Material Licenciado, lo que ocurra primero, y continuará hasta que dejes de acceder y usar el Material Licenciado, salvo que se termine antes según se describe a continuación.
**B. Términos de Suscripción.** Los Servicios de Pago proporcionados como parte del Material Licenciado se ponen a disposición como un servicio de suscripción recurrente que da acceso a ciertas características, beneficios o servicios, según se describe en el Sitio para Desarrolladores y en el Portal de Pago. Si compras un Servicio de Pago, lo haces pagando una tarifa de suscripción por adelantado de manera mensual conforme a los términos de pago establecidos a continuación. Cuando te suscribes para acceder al/los Servicio(s) de Pago a través del Portal de Pago, aceptas expresamente que estás autorizando pagos recurrentes y que los pagos se realizarán mediante el método de pago que hayas seleccionado hasta que el Servicio de Pago aplicable sea cancelado por ti o por X o este Acuerdo se termine de otro modo. Tu suscripción al Servicio de Pago se renovará automáticamente mensualmente hasta que sea cancelada conforme a este Acuerdo. Tu información de pago será procesada automáticamente por el Procesador de Pagos (como se define a continuación) al comienzo de cada período de suscripción aplicable al/los Servicio(s) de Pago. Si tu información de pago es rechazada, tu suscripción puede cancelarse hasta que proporciones nueva información de pago para el/los Servicio(s) de Pago aplicable(s). Si proporcionas nueva información de pago y se cobra con éxito a tu cuenta de pago, tu nuevo período de suscripción se basará en la fecha de renovación original y no en la fecha en que se realizó el cobro exitoso. Los precios de los Servicios de Pago están sujetos a cambios de vez en cuando. X proporcionará un aviso previo razonable de cualquier cambio material en el precio de los Servicios de Pago, aviso que puede darse a través del Sitio para Desarrolladores. Para las tarifas de suscripción, los cambios de precio entrarán en vigor al comienzo del siguiente período de suscripción posterior a la fecha del cambio de precio. Si no estás de acuerdo con un cambio de precio, tienes derecho a rechazar el cambio cancelando tu suscripción al/los Servicio(s) de Pago aplicable(s) antes de que el cambio de precio entre en vigor.
**C. Términos de Pago.** X puede ofrecer opciones de pago que varían según el Servicio de Pago, el dispositivo, el sistema operativo, la ubicación geográfica u otros factores, que pueden actualizarse de vez en cuando. Estas opciones de pago pueden incluir pagos web utilizando un procesador de pagos de terceros (“**Procesador de Pagos**”). Cuando accedes a un Servicio de Pago, aceptas: (i) pagar el precio indicado por el Servicio de Pago, junto con cualquier cantidad adicional relativa a impuestos aplicables, recargos, comisiones de tarjeta de crédito, comisiones bancarias, comisiones por transacciones en el extranjero, comisiones por cambio de divisas y fluctuaciones cambiarias, de manera recurrente durante el período de suscripción aplicable; y (ii) cumplir con cualquier término de servicio, política de privacidad u otros acuerdos legales o restricciones aplicables (incluidas las restricciones de edad adicionales) impuestas por el Procesador de Pagos en relación con tu uso de un método de pago determinado. La tarifa de suscripción se aplicará automáticamente al comienzo del período de renovación para el período de suscripción aplicable a menos que canceles el/los Servicio(s) de Pago en el Sitio para Desarrolladores. Es tu responsabilidad asegurarte de que tu información bancaria, de tarjeta de crédito, de tarjeta de débito y/o de otra información de pago esté actualizada, completa y sea precisa en todo momento. Si realizas un pago por un Servicio de Pago a través de un Procesador de Pagos, X puede recibir información sobre tu transacción, como cuándo se realizó, cuándo está programada la expiración o renovación automática de una suscripción, en qué plataforma realizaste la compra y otra información. X no será responsable de errores cometidos o retrasos causados por el Procesador de Pagos, tu banco, tu compañía de tarjeta de crédito o cualquier red de pagos. Todos los pagos a X son no reembolsables excepto según se disponga expresamente lo contrario en este Acuerdo o según lo requiera la ley.
**D. Impuestos y tarifas.** Todas las tarifas excluyen todo tipo de impuestos y tarifas similares en vigor, promulgados o impuestos en el futuro sobre la transacción, la entrega del Material Licenciado o la entrega del Contenido de X, incluidos cualquier impuesto sobre ventas, uso o valor añadido, impuesto sobre bienes y servicios, impuesto al consumo, derechos aduaneros, aranceles o cargos similares. Estos impuestos pueden incluir, entre otros, IVA, GST, impuesto sobre las ventas, retención en la fuente y cualquier otro impuesto aplicable, pero excluyen los impuestos basados únicamente en la renta neta de X. Eres responsable del pago de todos esos impuestos, derechos y cargos, así como de cualquier sanción e interés relacionados que surja del pago de tales cantidades. Además, se puede cobrar un recargo para recuperar los costos asociados con el Impuesto sobre Servicios Digitales ("DST") o impuestos similares específicos de la jurisdicción o tarifas regulatorias incurridas por X en determinadas jurisdicciones. Este recargo aparecerá como una partida separada en tu factura, cuando corresponda, y se calculará como un porcentaje de los cargos aplicables determinados por X a su entera discreción. X puede ajustar este recargo en cualquier momento, sin previo aviso, en respuesta a aumentos en las tasas fiscales o de tarifas o los costos administrativos relacionados. Dependiendo de tu ubicación, X puede ser responsable de recopilar y reportar información relacionada con los impuestos sobre transacciones que surjan de tu compra de Servicios de Pago. Nos otorgas permiso para proporcionar tu información de cuenta y personal a las autoridades fiscales pertinentes para cumplir con nuestras obligaciones de recaudación y reporte fiscal.
**E. Cancelación de tu Suscripción a los Servicios de Pago.** Tu suscripción a los Servicios de Pago se renovará automáticamente mensualmente a menos que canceles tu suscripción al menos 24 horas antes del final de tu período de suscripción actual. No hay reembolsos ni créditos por períodos de suscripción parciales, incluso en una situación en la que se modifiquen o discontinúen ciertas características, beneficios y/o servicios. LOS PLANES DE SUSCRIPCIÓN SON PREPAGADOS, NO REEMBOLSABLES (SALVO QUE LA LEY LO REQUIERA), Y SE RENUEVAN AUTOMÁTICAMENTE AL FINAL DE CADA PERÍODO DE SUSCRIPCIÓN A MENOS QUE LA SUSCRIPCIÓN SE CANCELE SIGUIENDO LOS PROCEDIMIENTOS DE CANCELACIÓN AQUÍ ESTABLECIDOS. Puedes cancelar tu suscripción a los Servicios de Pago en cualquier momento a través del Sitio para Desarrolladores y ya no tendrás acceso a los Servicios de Pago (ni a sus características o funcionalidades) al final de tu período de suscripción vigente en ese momento. Cuando canceles los Servicios de Pago, tu suscripción permanecerá activa desde el momento en que canceles hasta el final de tu período de suscripción actual. No recibirás un reembolso ni un crédito por los días restantes en tu período de suscripción actual, a menos que la ley lo exija. Todos los pagos por los Servicios de Pago son finales y no reembolsables ni intercambiables, salvo que la ley aplicable lo exija. X no da ninguna garantía en cuanto a la naturaleza, calidad o valor de un Servicio de Pago ni sobre la disponibilidad o suministro del mismo. No se proporcionan reembolsos ni créditos por ningún Servicio de Pago no utilizado o utilizado parcialmente (por ejemplo, un período de suscripción utilizado parcialmente). **Todas las transacciones son finales** a menos que tengas derecho a desistir conforme a la ley, como se establece a continuación\*\*.\*\*
1. **Derecho de Desistimiento y Reembolsos para Usuarios que Vivan en la UE o el Reino Unido.** Cuando compras Servicios de Pago en modalidad de suscripción, aceptas expresamente hacerlo sobre una base de suscripción y que la suscripción comenzará inmediatamente en tu fecha de compra. Si eres consumidor en un Estado Miembro de la UE o en el Reino Unido, aceptas que tienes catorce (14) días después de tu compra para desistir de tu contrato de compra por cualquier razón.
2. **Sin Derecho de Desistimiento para Usuarios que Vivan en Taiwán.** Cuando compras Servicios de Pago, lo haces sobre una base de suscripción, la suscripción comenzará inmediatamente en tu fecha de compra y el Servicio de Pago se considera plenamente ejecutado una vez iniciado. Si eres consumidor en Taiwán, aceptas que puedes cancelar tu suscripción a cualquier Servicio de Pago conforme a la Sección VII.E anterior, pero que de lo contrario no existe derecho a rescindir tu suscripción y no se emitirá reembolso.
**F. Los Servicios de Pago no son transferibles entre cuentas de X.** Cada compra de un Servicio de Pago se aplica a una única cuenta de X, lo que significa que tu compra se aplicará únicamente a la cuenta que estabas utilizando cuando compraste el Servicio de Pago y no se aplicará a otras cuentas a las que puedas tener acceso o control. Si tienes o controlas varias cuentas y deseas acceder a los Servicios de Pago en cada cuenta, debes comprar el Servicio de Pago en cada cuenta individualmente. No puedes permitir que otros usen tu cuenta de X para acceder a cualquier Material Licenciado que dicha persona no haya ordenado. No puedes comprar un Servicio de Pago o utilizar ningún Material Licenciado si eres una persona con la que las personas de EE. UU. no pueden tener tratos conforme a sanciones económicas, incluidas, entre otras, las sanciones administradas por la Oficina de Control de Activos Extranjeros del Departamento del Tesoro de los Estados Unidos o cualquier otra autoridad de sanciones aplicable ("**Persona Prohibida**"). Esto incluye, entre otras, personas ubicadas en, ciudadanas de o residentes habituales en los siguientes países y regiones: Cuba, Irán, la Región de Crimea de Ucrania, Corea del Norte y Siria. Declaras y garantizas que no eres una Persona Prohibida.
**G. Restricciones y Obligaciones.** Solo puedes comprar y utilizar un Servicio de Pago o utilizar el Material Licenciado si tienes permitido legalmente utilizar el Material Licenciado en tu país y vives en un país compatible con X para el Servicio de Pago o Material Licenciado aplicable. X puede, a su discreción, restringir la capacidad de acceder al Material Licenciado o comprar un Servicio de Pago en determinados países. X se reserva el derecho de modificar la lista de países admitidos de vez en cuando. X se reserva el derecho de rechazar transacciones de Servicios de Pago o de cancelar o discontinuar la venta o uso de un Servicio de Pago o el uso de cualquier Material Licenciado a su entera discreción.
**H. Suspensión.** X puede suspender tu uso y acceso al Material Licenciado inmediatamente sin previo aviso (a) si X cree razonablemente que (i) tu uso del Material Licenciado causaría daños o una carga desmesurada sobre el Material Licenciado, (ii) has violado este Acuerdo, (iii) generas riesgo o posible exposición legal para X, (iv) la prestación del Material Licenciado por parte de X a ti ya no es comercialmente viable; (b) por inactividad prolongada; (c) si X es solicitado o instruido para hacerlo por cualquier tribunal competente, autoridad reguladora o agencia de aplicación de la ley; o (d) por incumplimiento del pago de los Servicios de Pago. X no será responsable por daños de ningún tipo resultantes de dicha suspensión.
**I. Terminación.** X puede terminar este Acuerdo por cualquier motivo a su entera discreción. Salvo cuando dicha terminación anticipada sea consecuencia de tu incumplimiento de este Acuerdo, dicha terminación anticipada por parte de X será efectiva al final del período de suscripción vigente en ese momento. Si violas los términos de este Acuerdo, X puede terminar este Acuerdo por causa inmediatamente tras notificarte y no recibirás un reembolso prorrateado por ningún Servicio de Pago. Puedes cancelar tu suscripción a los Servicios de Pago o tu uso del Material Licenciado en el Sitio para Desarrolladores. Al terminar este Acuerdo: (a) todas las licencias otorgadas en este Acuerdo expiran inmediatamente y debes cesar el uso de cualquier Material Licenciado; y (b) deberás eliminar permanentemente todo el Material Licenciado en todas las formas y tipos de medios, y las copias del mismo, en tu posesión. A petición de X por cualquier motivo, proporcionarás con prontitud (y en cualquier caso dentro de los diez (10) días hábiles a partir de dicha solicitud) evidencia (por ejemplo, capturas de pantalla de la confirmación de eliminación) del cumplimiento de las disposiciones del subapartado (b) mencionado en esta Sección. Las partes de este Acuerdo no serán responsables entre sí de ningún daño resultante únicamente de la terminación de este Acuerdo según lo permitido en este Acuerdo.
**VIII. Auditoría de Cumplimiento.**
X o un agente tercero mutuamente acordado sujeto a obligaciones de confidencialidad tendrá derecho a inspeccionar y auditar cualquier registro relacionado con la ejecución de este Acuerdo bajo tu control o posesión previo aviso razonable, y en un momento razonable durante el horario comercial normal, con el fin de verificar el cumplimiento de este Acuerdo y las tarifas pagaderas a X para el período de dos (2) años anterior a la auditoría. X puede ejercer su derecho de auditoría no más de una vez cada doce (12) meses a menos que tenga causa razonable de incumplimiento, y dicha auditoría no interferirá irrazonablemente con tus actividades comerciales. Prestarás plena cooperación y asistencia con dicha auditoría y proporcionarás acceso a todo el Material Licenciado en tu posesión, los acuerdos aplicables y los registros. Sin limitar la generalidad de lo anterior, como parte de la auditoría, X puede solicitar, y aceptas proporcionar, un informe escrito, firmado por un representante autorizado, que enumere tu despliegue actual del Material Licenciado. Pagarás a X dentro de los treinta (30) días hábiles siguientes a la finalización de la auditoría el monto de cualquier pago insuficiente revelado por dicha auditoría. Además, si dicha auditoría revela un pago insuficiente por tu parte del cinco por ciento (5%) o más, también reembolsarás a X los costos y gastos razonables de dicha auditoría. Los requisitos de esta Sección sobrevivirán durante un (1) año después de la terminación de este Acuerdo.
**IX. Descargo de Responsabilidad.**
EN LA MÁXIMA MEDIDA PERMITIDA POR LA LEY APLICABLE, EL MATERIAL LICENCIADO SE TE PROPORCIONA “TAL CUAL”, “EN EL LUGAR DONDE ESTÁ”, CON TODOS LOS DEFECTOS, Y X RENUNCIA A TODAS LAS GARANTÍAS, YA SEAN EXPRESAS, IMPLÍCITAS, ESTATUTARIAS O DE OTRO TIPO, INCLUIDAS, SIN LIMITACIÓN, LAS GARANTÍAS DE COMERCIABILIDAD, NO INFRACCIÓN, IDONEIDAD PARA UN PROPÓSITO PARTICULAR, Y CUALESQUIERA GARANTÍAS O CONDICIONES QUE SURJAN DE ESTE ACUERDO, DEL CURSO DE LOS NEGOCIOS O DE LOS USOS DEL COMERCIO. X NO GARANTIZA QUE EL MATERIAL LICENCIADO O CUALQUIER OTRO PRODUCTO O SERVICIO DE X PROPORCIONADO EN VIRTUD DEL PRESENTE CUMPLIRÁ CON ALGUNO DE TUS REQUISITOS O QUE EL USO DE DICHO MATERIAL LICENCIADO U OTROS PRODUCTOS O SERVICIOS ESTARÁ LIBRE DE ERRORES, ININTERRUMPIDO, LIBRE DE VIRUS O SEGURO. ERES RESPONSABLE DE TU USO DEL MATERIAL LICENCIADO Y DE CUALQUIER CONTENIDO QUE PROPORCIONES. ESTE DESCARGO DE GARANTÍAS PUEDE NO SER VÁLIDO EN ALGUNAS JURISDICCIONES Y PUEDES TENER DERECHOS DE GARANTÍA CONFORME A LA LEY QUE NO PUEDEN RENUNCIARSE NI DESCARGARSE.
**ADEMÁS, ENTIENDES Y ACEPTAS QUE LOS SERVICIOS DE PAGO SE TE PROPORCIONAN SOBRE UNA BASE “TAL CUAL” Y “SEGÚN DISPONIBILIDAD”.**
**X. Indemnización.**
Deberás defender a X contra cualquier procedimiento, demanda, reclamación y acción judicial (incluidas, sin limitación, reclamaciones por responsabilidad de producto) e indemnizar a X de todas las responsabilidades, daños y costos (incluidos, sin limitación, los honorarios razonables de abogados) en la medida en que surjan de (a) tu uso del Material Licenciado de cualquier manera incompatible con este Acuerdo o (b) el desempeño, la promoción, la venta o distribución de tus Servicios. Si X busca indemnización o defensa por tu parte bajo esta Sección, X te notificará con prontitud por escrito de las reclamaciones presentadas contra X para las que solicita indemnización o defensa. X puede asumir el control total de la defensa de las reclamaciones con asesores legales de su elección. No celebrarás ningún acuerdo con terceros que afecte los derechos de X, constituya una admisión de culpa por parte de X, o vincule a X de alguna manera sin el consentimiento previo por escrito de X. Si X asume el control de la defensa de dicha reclamación, X no llegará a un acuerdo respecto de cualquier reclamación que requiera pago por tu parte sin tu aprobación previa por escrito.
**XI. Limitación de Responsabilidad.**
EN NINGÚN CASO X SERÁ RESPONSABLE ANTE TI O CUALQUIER USUARIO POR DAÑOS INDIRECTOS, ESPECIALES, INCIDENTALES, EJEMPLARES, PUNITIVOS O CONSECUENCIALES, NI POR PÉRDIDA DE USO, DATOS, NEGOCIO, BUENA VOLUNTAD (GOODWILL) O BENEFICIOS QUE SURJAN DE O EN RELACIÓN CON ESTE ACUERDO. EN CUALQUIER CASO, LA RESPONSABILIDAD AGREGADA DE X POR TODAS Y CADA UNA DE LAS RECLAMACIONES BAJO ESTE ACUERDO NO SUPERARÁ LOS CINCUENTA DÓLARES (\$50.00). LAS LIMITACIONES, EXCLUSIONES Y DESCARGOS ANTERIORES SE APLICARÁN INDEPENDIENTEMENTE DE QUE DICHA RESPONSABILIDAD SURJA DE CUALQUIER RECLAMACIÓN BASADA EN CONTRATO, GARANTÍA, RESPONSABILIDAD EXTRACONTRACTUAL, RESPONSABILIDAD ESTRICTA O DE OTRO MODO, Y CON INDEPENDENCIA DE QUE X HAYA SIDO INFORMADO O NO DE LA POSIBILIDAD DE DICHA PÉRDIDA O DAÑO. SI LA LEY APLICABLE PROHÍBE ALGUNA LIMITACIÓN DE RESPONSABILIDAD AQUÍ ESTABLECIDA, LAS PARTES ACUERDAN QUE LA LIMITACIÓN SE ENTENDERÁ MODIFICADA PARA AJUSTARSE A LA LEY APLICABLE. LAS PARTES ACUERDAN QUE LAS LIMITACIONES DE RESPONSABILIDAD AQUÍ ESTABLECIDAS SON ASIGNACIONES DE RIESGO ACORDADAS Y DICHAS LIMITACIONES SE APLICARÁN NO OBSTANTE EL FALLO DEL PROPÓSITO ESENCIAL DE CUALQUIER RECURSO LIMITADO.
**XII. Actualizaciones del Acuerdo.**
X puede actualizar o modificar este Acuerdo o cualquiera de los Términos para Desarrolladores Incorporados de vez en cuando. Deberás consultar regularmente el Sitio para Desarrolladores para conocer las actualizaciones. X te alertará de revisiones materiales a estos términos publicando los términos actualizados en estos sitios, mediante una notificación de servicio o por otros medios adecuados (por ejemplo, por correo electrónico a una dirección de correo asociada con tu cuenta). Los cambios no serán retroactivos y la versión más actual de este Acuerdo, disponible en el Sitio para Desarrolladores, regirá tu acceso y uso del Material Licenciado y cualquier transacción correspondiente. Tu acceso o uso continuado del Material Licenciado constituirá la aceptación vinculante de dichas actualizaciones y modificaciones.
**XIII. Resolución de Disputas y Renuncia a la Acción Colectiva.**
**A. ESTA SECCIÓN SE APLICA A TI SOLO SI VIVES FUERA DE LA UNIÓN EUROPEA, LOS ESTADOS DE LA AELC (EFTA) O EL REINO UNIDO, INCLUYENDO SI VIVES EN LOS ESTADOS UNIDOS. LEE ESTA SECCIÓN CUIDADOSAMENTE — PUEDE AFECTAR SIGNIFICATIVAMENTE TUS DERECHOS LEGALES, INCLUIDO TU DERECHO A PRESENTAR UNA DEMANDA EN UN TRIBUNAL.**
1. **Elección de Ley y Selección de Foro.** Las leyes del Estado de Texas, excluyendo sus disposiciones sobre elección de ley, regirán este Acuerdo y cualquier disputa que surja entre tú y X, no obstante cualquier otro acuerdo entre las partes en contrario. Todas las disputas relacionadas con este Acuerdo, incluidas cualesquiera disputas, reclamaciones o controversias que surjan de o se relacionen con este Acuerdo, la comercialización del Material Licenciado y/o tu participación en el Material Licenciado, se someterán exclusivamente al Tribunal de Distrito de los Estados Unidos para el Distrito Norte de Texas o a los tribunales estatales ubicados en el Condado de Tarrant, Texas, Estados Unidos, y consientes la jurisdicción personal en dichos foros y renuncias a cualquier objeción en cuanto al foro inconveniente. Sin perjuicio de lo anterior, aceptas que, a su entera discreción, X pueda presentar cualquier reclamación, causa de acción o disputa que tenga contra ti en cualquier tribunal competente del país en el que residas que tenga jurisdicción y competencia sobre la reclamación.
Si eres una entidad gubernamental federal, estatal o local en los Estados Unidos que utiliza el Material Licenciado en su capacidad oficial y legalmente no puede aceptar las cláusulas de ley aplicable, jurisdicción o sede antes mencionadas, entonces esas cláusulas no se te aplican. Para tales entidades gubernamentales federales de EE. UU., este Acuerdo y cualquier acción relacionada se regirán por las leyes de los Estados Unidos de América (sin referencia a conflicto de leyes) y, en ausencia de ley federal y en la medida permitida bajo la ley federal, por las leyes del Estado de Texas (excluyendo la elección de ley).
2. **TIENES UN AÑO PARA PRESENTAR UNA RECLAMACIÓN CONTRA X.** Debes presentar cualquier reclamación contra X que surja de o se relacione con este Acuerdo dentro de un (1) año después de la fecha de ocurrencia del evento o los hechos que dieron origen a la disputa, salvo que la ley aplicable disponga que el plazo normal de prescripción para esa reclamación no puede reducirse por acuerdo. Si no presentas una reclamación dentro de este período, renuncias para siempre al derecho de perseguir cualquier reclamación o causa de acción, de cualquier tipo o carácter, basada en tales eventos o hechos, y dichas reclamaciones o causas de acción quedan prohibidas permanentemente y X no tendrá ninguna responsabilidad respecto de dicha reclamación.
3. **Renuncia a la Acción Colectiva.** En la medida permitida por la ley, también renuncias al derecho de participar como demandante o miembro de la clase en cualquier supuesto procedimiento de acción de clase, acción colectiva o acción representativa.
4. **Cambios a esta Sección.** Esta Sección de Resolución de Disputas sobrevive al final de la relación entre tú y X, incluida la cancelación o cancelación de la suscripción a cualquier servicio o comunicación proporcionada por X.
5. **Medidas Cautelares.** No obstante lo anterior, aceptas que los daños monetarios serían un recurso inadecuado para X en caso de una violación o amenaza de violación de este Acuerdo que proteja la propiedad intelectual de X o la Información Confidencial, y que en caso de tal violación o amenaza, X, además de cualquier otro recurso al que tenga derecho, tiene derecho a medidas cautelares o preliminares (incluida una orden que te prohíba realizar acciones en violación de tales disposiciones), sin la necesidad de constituir fianza, y a la ejecución específica según sea apropiado. Las partes acuerdan que ni la Convención de las Naciones Unidas sobre los Contratos de Compraventa Internacional de Mercaderías ni la Uniform Computer Information Transaction Act se aplicarán a este Acuerdo, independientemente de los estados en los que las partes hagan negocios o estén incorporadas. Ninguna renuncia por parte de X a cualquier pacto o derecho bajo este Acuerdo será efectiva a menos que se plasme en un escrito autorizado por X.
**B. ESTA SECCIÓN SE APLICA A TI SOLO SI VIVES EN LA UNIÓN EUROPEA, LOS ESTADOS DE LA AELC (EFTA) O EL REINO UNIDO. LEE ESTA SECCIÓN CUIDADOSAMENTE — PUEDE AFECTAR SIGNIFICATIVAMENTE TUS DERECHOS LEGALES, INCLUIDO TU DERECHO A PRESENTAR UNA DEMANDA EN UN TRIBUNAL.**
1. **Elección de Ley y Selección de Foro.** En la medida permitida por la ley, todas las disputas relacionadas con este Acuerdo, incluidas cualesquiera disputas, reclamaciones o controversias que surjan de o se relacionen con este Acuerdo, la comercialización del Material Licenciado y/o tu participación en el Material Licenciado, se presentarán exclusivamente ante un tribunal competente en Irlanda, sin tener en cuenta las disposiciones sobre conflicto de leyes, y se regirán por la ley irlandesa, no obstante cualquier acuerdo entre las partes en contrario. Sin perjuicio de lo anterior, aceptas que, a su entera discreción, X pueda presentar cualquier reclamación, causa de acción o disputa que tenga contra ti en cualquier tribunal competente del país en el que residas que tenga jurisdicción y competencia sobre la reclamación.
2. **TIENES UN AÑO PARA PRESENTAR UNA RECLAMACIÓN CONTRA X.** Debes presentar cualquier reclamación contra X que surja de o se relacione con este Acuerdo dentro de un (1) año después de la fecha de ocurrencia del evento o los hechos que dieron origen a la disputa, salvo que la ley aplicable disponga que el plazo normal de prescripción para esa reclamación no puede reducirse por acuerdo. Si no presentas una reclamación dentro de este período, renuncias para siempre al derecho de perseguir cualquier reclamación o causa de acción, de cualquier tipo o carácter, basada en tales eventos o hechos, y dichas reclamaciones o causas de acción quedan prohibidas permanentemente, y X no tendrá ninguna responsabilidad respecto de dicha reclamación.
3. **Renuncia a la Acción Colectiva.** En la medida permitida por la ley, también renuncias al derecho de participar como demandante o miembro de la clase en cualquier supuesto procedimiento de acción de clase, acción colectiva o acción representativa.
4. **Cambios a esta Sección.** Esta sección de Resolución de Disputas sobrevive al final de la relación entre tú y X, incluida la cancelación o cancelación de la suscripción a cualquier servicio o comunicación proporcionada por X.
5. **Medidas Cautelares.** No obstante lo anterior, aceptas que los daños monetarios serían un recurso inadecuado para X en caso de una violación o amenaza de violación de este Acuerdo que proteja la propiedad intelectual de X o la Información Confidencial, y que en caso de tal violación o amenaza, X, además de cualquier otro recurso al que tenga derecho (incluidos daños monetarios), tiene derecho a tales medidas cautelares preliminares o de inhibición (incluida una orden que te prohíba realizar acciones en violación de tales disposiciones), sin la necesidad de constituir fianza, y a la ejecución específica según sea apropiado. Las partes acuerdan que ni la Convención de las Naciones Unidas sobre los Contratos de Compraventa Internacional de Mercaderías ni la Uniform Computer Information Transaction Act se aplicarán a este Acuerdo, independientemente de los estados en los que las partes hagan negocios o estén incorporadas. Ninguna renuncia por parte de X a cualquier pacto o derecho bajo este Acuerdo será efectiva a menos que se plasme en un escrito autorizado por X.
**XIV. Varios.**
**A. Cesión.** No cederás ninguno de los derechos u obligaciones otorgados en virtud del presente, total o parcialmente, ya sea voluntariamente o por operación de la ley, contrato, fusión (ya seas la entidad superviviente o la absorbida), venta de acciones o activos, consolidación, disolución, por acción gubernamental, o de otro modo, excepto con el consentimiento previo por escrito de X. X está autorizado a firmar modificaciones y consentimientos para X Internet Unlimited Company, una empresa irlandesa responsable de la información de los usuarios de X que viven fuera de los Estados Unidos. Cualquier intento de cesión en violación de esta Sección será nulo y sin efecto, y X podrá terminar este Acuerdo.
**B. Protección del Usuario.** A menos que sea explícitamente aprobado por X por escrito, no deberás usar, ni mostrar, distribuir o poner a disposición a sabiendas Contenido de X, o información derivada del Contenido de X, con el propósito de: (a) realizar o proporcionar vigilancia o recopilación de inteligencia, incluida, entre otras cosas, la investigación o el seguimiento de usuarios de X o Contenido de X; (b) realizar o proporcionar análisis o investigación para cualquier propósito ilegal o discriminatorio o de una manera que sea incompatible con las expectativas razonables de privacidad de los usuarios de X; (c) monitorear eventos sensibles (incluidos, entre otros, protestas, mítines o reuniones de organización comunitaria); o (d) dirigirse a, segmentar o perfilar a individuos en función de información personal sensible, incluida su salud (por ejemplo, el embarazo), situación o condición financiera negativa, afiliación o creencias políticas, origen racial o étnico, afiliación o creencias religiosas o filosóficas, vida sexual u orientación sexual, afiliación sindical, Contenido de X relacionado con la comisión presunta o real de un delito, o cualquier otra categoría sensible de información personal prohibida por la ley.
**C. Uso Gubernamental.** Si muestras, distribuyes o pones a disposición de otro modo cualquier Contenido de X a Usuarios que sean, o que actúen en nombre de, cualquier entidad relacionada con el gobierno (cada uno, un “**Usuario Final Gubernamental**”); (a) debes solicitar (o ya estar suscrito) un plan Enterprise (como se describe en [developer.x.com](https://developer.x.com)); (b) deberás identificar a todos esos Usuarios Finales Gubernamentales al enviar tu caso de uso para revisión a X; y (c) deberás notificar posteriormente a X por escrito sobre cualquier nuevo Usuario Final Gubernamental o cualquier nuevo caso de uso con Usuarios Finales Gubernamentales existentes antes de que los Servicios muestren, distribuyan o pongan a disposición de otro modo cualquier Contenido de X a un Usuario Final Gubernamental o para cualquier nuevo caso de uso. X puede prohibirte que pongas Contenido de X a disposición de cualquier Usuario Final Gubernamental. No deberás usar, ni mostrar, distribuir o poner a disposición a sabiendas Contenido de X, o información derivada del Contenido de X, a ningún Usuario Final Gubernamental cuya función o misión principal incluya realizar vigilancia o recopilación de inteligencia. Si las fuerzas del orden solicitan información sobre X o sus usuarios con fines de una investigación en curso, puedes remitirlas a las Directrices para las Fuerzas del Orden de X ubicadas en [**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support). La API de X y el Contenido de X son "artículos comerciales" según se define dicho término en 48 C.F.R. 2.101, consistentes en "software informático comercial" y "documentación de software informático comercial" según se utilizan dichos términos en 48 C.F.R. 12.212. Cualquier uso, modificación, derivación, reproducción, publicación, ejecución, exhibición, divulgación o distribución de la API de X o del Contenido de X por parte de cualquier entidad gubernamental está prohibido, salvo lo expresamente permitido por los términos de este Acuerdo. Además, cualquier uso por parte de entidades gubernamentales de EE. UU. debe estar de acuerdo con 48 C.F.R. 12.212 y 48 C.F.R. 227.7202-1 a 227.7202-4. Si utilizas la API de X o el Contenido de X en tu capacidad oficial como empleado o representante de una entidad gubernamental estatal o local de EE. UU. y no puedes aceptar legalmente las cláusulas de indemnización, jurisdicción, sede u otras aquí incluidas, entonces esas cláusulas no se aplican a dicha entidad en la medida requerida por la ley. Contratista/fabricante es X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
**D. Cumplimiento de las Leyes; Exportación e Importación.** Cada parte cumplirá con todas las leyes, reglas y regulaciones extranjeras, federales, estatales y locales aplicables, incluidas, sin limitación, todas las leyes relativas al soborno y/o la corrupción. El Material Licenciado está sujeto a las leyes de exportación de EE. UU. y puede estar sujeto a las leyes de importación y uso del país donde se entrega o utiliza. Deberás cumplir con estas leyes. Bajo estas leyes, el Material Licenciado no puede venderse, arrendarse, descargarse, moverse, exportarse, reexportarse o transferirse a través de fronteras sin una licencia o aprobación de la autoridad gubernamental pertinente, a ningún país o a ningún nacional extranjero restringido por estas leyes, incluidos los países embargados por el Gobierno de EE. UU. (actualmente Cuba, Irán, Corea del Norte, el norte de Sudán y Siria), a ningún usuario final restringido o denegado, incluidas, entre otras, cualquier persona o entidad prohibida por la Oficina de Control de Activos Extranjeros de EE. UU., o para ningún uso final restringido. Mantendrás todos los derechos y licencias que se requieran para tus Servicios.
**E. Adenda de Protección de Datos.** Cada parte cumplirá con la Adenda de Protección de Datos de Controlador a Controlador de X ubicada en [**https://gdpr.x.com/en/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html), que puede ser actualizada por X de vez en cuando.
**F. Supervivencia.** Las Secciones III (Restricciones de Uso), V (Propiedad y Comentarios), VI (Confidencialidad), VII(I) (Terminación), VIII (Auditoría de Cumplimiento), IX (Descargo de Garantías), X (Indemnización), XI (Limitación de Responsabilidad), XIII (Resolución de Disputas y Renuncia a la Acción Colectiva); y XIV (Varios) de este Acuerdo sobrevivirán a la terminación de este Acuerdo.
**G. Acuerdo Completo.** Este Acuerdo constituye el entendimiento completo de las partes con respecto al objeto de este Acuerdo y sustituye a todos los demás acuerdos entre las partes relacionados con el objeto, ya sean escritos u orales. Si alguna disposición de este Acuerdo es declarada inaplicable por un tribunal, las disposiciones restantes del Acuerdo permanecerán en vigor. Ninguna renuncia bajo este Acuerdo será efectiva a menos que sea por escrito y esté firmada por la parte que otorga la renuncia. Una renuncia otorgada en una ocasión no operará como renuncia en otras ocasiones. Este Acuerdo no crea ni implica ninguna sociedad, agencia o joint venture.
# Requisitos de visualización: Publicaciones
Source: https://docs.x.com/es/developer-terms/display-requirements
Requisitos de visualización para mostrar publicaciones de X en tu aplicación, incluyendo la marca, la atribución, la anatomía de una publicación, la interactividad y los metadatos que se deben renderizar.
## Principios generales y anatomía de la publicación
Las publicaciones son uno de nuestros elementos de marca más visibles, por lo que es importante que se presenten correctamente. Debes cumplir con los requisitos de visualización que se indican a continuación cuando muestres publicaciones, cronologías (timelines) y otro contenido de X.
Si sigues estas directrices únicamente para mostrar una publicación, es posible que no necesites contactar a X para obtener permisos adicionales de visualización o marca registrada. Sin embargo, puedes enviar tu uso y contexto propuestos para que X los revise. (Ten en cuenta que, en algunos casos, aún podría ser necesario el permiso del creador original del contenido, ya que X no otorga permiso para usar contenido de terceros/usuarios).
Los siguientes principios generales se aplican a todos los medios de visualización. Ten en cuenta que sí existen requisitos específicos por medio, y se describen en las secciones siguientes.
La imagen a continuación muestra todos los componentes principales de una publicación.
### Sí hacer
* Mostrar publicaciones reales y sin modificar, provenientes de cuentas reales.
* Seguir los [Términos de Servicio](https://x.com/tos?lang=en) de X, los [Recursos y Directrices de Marca de X](https://about.x.com/en_us/company/brand-resources.html) y (si aplica) el [Acuerdo del Desarrollador y la Política del Desarrollador](/developer-terms/agreement).
* Mostrar el logotipo de X.
### No hacer
* Utilizar contenido de X para promocionar cualquier producto o servicio (por ejemplo, mostrando contenido de X en publicidad o mostrando contenido de X para dar a entender un respaldo a cualquier producto o servicio) sin el permiso explícito del usuario.
* Utilizar contenido de X para dar a entender patrocinio, respaldo o una asociación falsa con X.
* Incluir botones o iconos de otras plataformas sociales.
* Modificar el texto de la publicación.
* Utilizar maquetas (mock-ups) de publicaciones que no existen en la plataforma.
***
## Visualización en línea / Móvil, web y más allá
Nos comprometemos a llevar la facilidad y el poder de X a todos. Para asegurar que cada publicación se muestre de manera óptima, recomendamos encarecidamente utilizar [publicaciones incrustadas y/o cronologías incrustadas](https://publish.x.com). Cuando usas estos productos para publicar contenido de X, las publicaciones y cronologías se renderizan automáticamente de forma correcta, incluyendo funciones avanzadas como fotos, reproducción de video, publicaciones editadas y la obtención de datos actualizados de X sin OAuth. Si no te es posible utilizar nuestras funciones de incrustación, debes seguir los requisitos a continuación al mostrar publicaciones y cronologías en línea.
### Autor de la publicación
* La imagen de perfil, el @username y el nombre para mostrar del autor de la publicación deben mostrarse siempre y enlazar al perfil de X del usuario.
* El @username del autor de la publicación debe mostrarse siempre con el símbolo “@”.
* El avatar del autor de la publicación debe estar posicionado a la izquierda del nombre y el @username del autor, excepto para publicaciones en idiomas que se leen de derecha a izquierda, en cuyo caso el avatar del autor debe estar posicionado a la derecha del nombre para mostrar y del @username del autor.
### Texto de la publicación
* El texto de la publicación debe mostrarse en una línea debajo del nombre para mostrar y del @username del autor, y no puede ser alterado ni modificado.
* En dispositivos táctiles, el espacio en blanco alrededor del texto de la publicación y del autor de la publicación debe enlazar al enlace permanente (permalink) de la publicación.
* Las entidades de la publicación dentro del texto de la publicación deben estar correctamente enlazadas a su ubicación adecuada en X. Por ejemplo:
* Las @menciones a usuarios deben enlazar al perfil del usuario mencionado.
* Los hashtags deben enlazar a una búsqueda en X con el hashtag como consulta.
* Los enlaces en el texto de la publicación deben mostrarse utilizando el campo display\_url en la respuesta de la API de entidades de URL y enlazar al campo t.co original.
### Marca de tiempo
* La marca de tiempo de la publicación debe mostrarse y enlazar al enlace permanente de la publicación.
### Acciones de la publicación
* Todos los iconos de Acciones de la publicación (incluyendo responder, republicar y me gusta) deben estar siempre visibles para que el usuario pueda interactuar con la publicación. Estas acciones deben implementarse utilizando [Web Intents](/x-for-websites/web-intents/overview) o con la API de X autenticada. En lugar de las Acciones de la publicación, puede mostrarse “Ver en X” junto a la marca de tiempo, enlazando al usuario al enlace permanente de la publicación.
* No se pueden adjuntar otras acciones sociales o de terceros a una publicación (p. ej., suscribirse, comentar, dar me gusta).
* Si la publicación que se muestra es una republicación, el nombre para mostrar del usuario que la republicó y el icono de republicación deben mostrarse encima o debajo del texto de la publicación. P. ej., “republicado por Jane Doe”. El nombre para mostrar debe enlazar al perfil del usuario que la republicó.
* Sigue las [directrices para mostrar respuestas](/developer-terms/reply-requirements).
### Ediciones de la publicación
* X permite a las personas editar sus publicaciones hasta 5 veces durante los primeros 30 minutos después de publicar la publicación original. Al usar [publicaciones incrustadas](/x-for-websites/embedded-posts/overview), la visualización aparecerá ligeramente diferente dependiendo de si la publicación fue editada antes o después de ser incrustada.
* Cuando una publicación se incrusta primero y luego se edita, debes mostrar esas ediciones tal como ocurren en la plataforma X:
* Si estás mostrando una versión anterior de una publicación editada, debes indicar debajo de la marca de tiempo que hay una nueva versión de la publicación, y a la derecha de esa nota, proporcionar un enlace que expanda el historial de ediciones de la publicación.
* Luego debes mostrar el historial completo de ediciones de la publicación.
Cuando una publicación se ha editado primero y luego se ha incrustado, debes indicar en la marca de tiempo que la publicación fue editada, y la marca de tiempo también debe enlazar a la publicación en vivo en X.
### Marca
* El logotipo oficial de X debe estar siempre razonablemente visible y mostrarse en la esquina superior derecha de una publicación individual o adjuntarse directamente a la cronología (p. ej., en la parte superior de la cronología). El logotipo debe tener la misma altura “x” que en la imagen. Consulta la [página de recursos de marca](https://about.x.com/en_us/company/brand-resources.html) de X para conocer las directrices y los recursos de marca.
### Enlace profundo (deep linking) en móvil
* Los enlaces profundos desde aplicaciones móviles nativas deben dirigir a la aplicación nativa de X. Si la aplicación nativa de X no está instalada en el dispositivo, el enlace debe dirigir a X.com a través de un navegador web.
### Cronologías
* Todas las cronologías deben permitir a los usuarios ver los detalles de una publicación individual (p. ej., enlazando la marca de tiempo de la publicación o enlazando toda el área de la publicación).
Si planeas colocar publicidad cerca de las publicaciones, asegúrate de que cumpla con la [Política del Desarrollador](/developer-terms/policy).
Si por alguna razón no puedes cumplir con una o más de estas reglas, contáctanos directamente a través de nuestro [formulario de Soporte de Política](https://help.x.com/forms/platform) antes de mostrar contenido de X. Para preguntas o más información sobre el uso del nombre y las marcas registradas de X, contáctanos a [trademarks@x.com](mailto:trademarks@x.com).
***
## Transmisión / 15 minutos de fama
Damos la bienvenida y fomentamos el uso de X en medios de transmisión. Nuestros requisitos aseguran que los usuarios de X reciban la atribución adecuada por su contenido, y ayudan a proporcionar la mejor experiencia para tu audiencia.
### Sí hacer
* Mostrar el nombre completo del usuario, el @username, el texto de la publicación y la imagen de perfil.
* Incluir el logotipo de X en proximidad cercana a las publicaciones mientras aparezcan en tu transmisión. Asegúrate de que el logotipo de X tenga un tamaño similar al de la imagen anterior, relativo al contenido.
* Usar el texto completo de la publicación.
* Al mostrar imágenes, el texto de la publicación también debe incluirse junto con el nombre para mostrar del usuario, el @username y el logotipo de X.
### No hacer
* Mostrar contenido de X en publicidad o para dar a entender el respaldo a cualquier producto o servicio sin el permiso explícito del usuario.
* Eliminar, ocultar o alterar el contenido de la publicación o la identificación del usuario (con la excepción de eliminar hipervínculos).
* Excluir la marca de tiempo.
* No utilizar las marcas de X, en su totalidad o en parte, en el título de tu producción sin antes revisar su uso con X, contactándonos en [trademarks@X.com](mailto:trademarks@X.com).
***
## Locución verbal o en voz en off
### Publicaciones
Al leer publicaciones al aire sin visualización gráfica de la publicación, no necesitas mostrar el logotipo de X, pero sí necesitas atribuirla verbalmente a X. Lee la publicación como fue escrita originalmente, sin ediciones.
### Nombres de usuario
Asegúrate de incluir una referencia a X al mencionar nombres de usuario de X. Por ejemplo, “Síguenos en X, en arroba-nombredeusuario” o “Puedes seguir a Lady Gaga en X, en arroba-ladygaga”.
### Hashtags
Asegúrate de incluir una referencia a X al mencionar hashtags de X. Por ejemplo, “Usa el hashtag ‘election2016’ en X” o “El hashtag para esta transmisión en X es bbcaq”.
# Directrices geográficas
Source: https://docs.x.com/es/developer-terms/geo-guidelines
Directrices para el manejo de publicaciones con etiquetas geográficas y datos de ubicación provenientes de la API de X, incluyendo funciones geográficas, objetos de lugar y consideraciones de privacidad del usuario.
Última actualización: 22 de octubre de 2014.
## Introducción
Publicar con ubicación es la función de geoetiquetado en la API de X. Esta función ayuda a proporcionar una experiencia más significativa para los usuarios al hacer que las publicaciones sean más contextuales. Por ejemplo, “¡Fuegos artificiales!” es mucho más relevante cuando se asocia con una ubicación: “¡Fuegos artificiales!” desde el barrio SoMa en San Francisco, California. ¡Esperamos trabajar con el ecosistema de desarrolladores para crear grandes experiencias en torno a esta funcionalidad!
## Privacidad del usuario y control de su información de ubicación
Para garantizar una experiencia buena y segura, los desarrolladores deben ser sensibles a la privacidad del usuario al manejar su ubicación, además de proporcionar una consistencia básica en la experiencia de “Publicar con ubicación”. Estas son algunas cosas clave a tener en cuenta que ayudan a proteger la privacidad del usuario y a garantizar que los usuarios comprendan el impacto de sus acciones:
## Directrices generales
* Los usuarios deben aceptar (opt-in) el uso de la función Publicar con ubicación (activar la ubicación).
* Los usuarios deben otorgar permiso explícito para que su ubicación exacta se muestre con sus publicaciones. Si la función de ubicación en tu cliente es “persistente” — es decir, una vez que la ubicación está activada, siempre acompaña a la publicación — puedes optar por mostrar solo los nombres de lugares (place\_ids) y permitir que los usuarios acepten adicionalmente el uso de la latitud y longitud exactas por publicación o como una configuración alternativa específica.
* Cuando accedas a los datos de ubicación de tus usuarios para publicar una publicación, esa información no debe ser almacenada por ti aparte de la publicación sin el permiso explícito del usuario.
* Debe quedar claro para los usuarios qué nivel de información de ubicación, si hubiera alguno, se mostrará asociado a su publicación. Una forma de hacerlo es mostrando un mapa de cómo se mostrará esta información antes de que se publique la publicación. Si la latitud y longitud exactas forman parte de la información (o son la única información) publicada por el usuario en el cliente, debe quedar claro para el usuario que sus coordenadas exactas se publicarán.
* Los usuarios deberían poder activar y desactivar su ubicación cada vez que redacten una publicación.
* Debes seguir los términos de la [Política del Desarrollador](/developer-terms/policy.html) de X, incluido el requisito de que no puedes agregar, almacenar en caché ni almacenar datos de ubicación y otra información geográfica de la API de X, salvo como parte de una publicación, y no puedes usar dichos datos de ubicación o información geográfica de manera independiente.
## Ejemplos específicos
Ejemplo 1: *Sin adición de latitud y longitud explícitas (esta es la interfaz de usuario actual del cliente web de X)*
1. Muestra un enlace a “Añadir tu ubicación” cuando un usuario redacte una publicación;
2. En segundo plano, utiliza la llamada a la API [reverse\_geocode](https://developer.x.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode.html) de X y pasa la latitud, longitud, precisión de tu localización y la granularidad preferida del usuario (que, por defecto, es “barrio”);
3. Muestra el nombre del lugar predeterminado (X intentará ordenarlos de una manera lógica: el orden es tal que un cliente de X puede simplemente mostrar la lista sin necesidad de modificarla);
4. Permite que el usuario seleccione una ubicación diferente de la lista (p. ej., cambiar de “SoMa, San Francisco” a “South Beach, San Francisco”).
5. Importante: sé transparente con el usuario si vas a mostrar información de ubicación exacta. Asegúrate de que el usuario sepa si se mostrará información de ubicación exacta.
6. Permite que el usuario elija activar o desactivar la ubicación en cada redacción de publicación.
Ejemplo 2: *Implementaciones existentes de geoetiquetado*
Varias aplicaciones cliente de X tienen implementada la función original de geoetiquetado (que solo transmitía latitud/longitud sin proporcionar place\_IDs). El comportamiento predeterminado de la API imita este comportamiento: es decir, como desarrollador no necesitas realizar ningún cambio en tu aplicación existente para mantener el comportamiento actual. De hecho, si simplemente pasas una coordenada de lat/lon a X, X realizará automáticamente la geocodificación inversa de esa latitud y longitud y mostrará el place\_ID además de lat/lon para las áreas donde tengamos datos disponibles.
Asegúrate de que sea transparente para tus usuarios que sus coordenadas exactas se están utilizando y mostrando en X. Una buena práctica para las aplicaciones existentes sería permitir que los usuarios activen o desactiven su ubicación por publicación. También puedes permitir que tus usuarios compartan solo place\_IDs en lugar de coordenadas exactas como configuración predeterminada “persistente”.
## Almacenamiento por parte de X de los datos de ubicación del usuario
X almacenará los datos que el cliente le pase de la siguiente manera:
* X guardará todos los datos que un usuario elija mostrar públicamente a sus seguidores. Esto es similar a cómo X almacena la marca de tiempo que indica cuándo se realizó la publicación, lo que significa que si un usuario publica con sus coordenadas exactas, X almacenará esta ubicación exacta junto con la publicación durante el tiempo que exista la publicación. Los usuarios pueden borrar los datos de ubicación de sus publicaciones haciendo clic en el botón “borrar mi historial de ubicaciones” en la página de Configuración, tal como se describe [aquí](https://support.twitter.com/articles/122236-how-to-tweet-with-your-location).
## Resumen
La adición de ubicación a una publicación aporta una enorme cantidad de contexto y valor desde la perspectiva del usuario. Sin embargo, las implementaciones de ubicación en tu cliente deben tener cuidado de considerar la privacidad y la transparencia del usuario como factores clave al diseñar un producto centrado en la ubicación.
Si tienes alguna pregunta o comentario sobre privacidad, ubicación y otras funciones geográficas, [contáctanos.](https://support.twitter.com/forms/platform)
# Política del Desarrollador de X
Source: https://docs.x.com/es/developer-terms/policy
La Política del Desarrollador de X describe el uso aceptable de la API de X, incluidas las reglas sobre contenido, automatización, privacidad, seguridad y comportamientos prohibidos.
## X + Desarrolladores
X ama a los desarrolladores. Nos encantan y nos asombran las herramientas y los servicios que esta comunidad crea aprovechando el poder de los datos de X. Como parte de nuestro compromiso con esta comunidad, buscamos proporcionar un acceso a los datos que sea abierto y justo para los desarrolladores, seguro para las personas en X y beneficioso para la plataforma de X en su conjunto. Para promover estos objetivos, hemos elaborado la Política del Desarrollador como una guía para ayudar a las personas a comprender nuestras reglas y expectativas sobre el uso apropiado de la API y del Contenido de X.
Esta Política del Desarrollador (“**Política**”) proporciona reglas y directrices para los desarrolladores que interactúan con el ecosistema de aplicaciones, servicios, sitio web, páginas web y contenido de X. Forma parte de tu contrato con X que rige el acceso y uso de la API de X y del Contenido de X (ya sea como parte del Acuerdo del Desarrollador u otro acuerdo escrito con X). Las violaciones de la Política se consideran violaciones de tu acuerdo. Esta Política puede modificarse en cualquier momento sin previo aviso. Los términos con mayúscula inicial utilizados en esta Política, que no estén definidos aquí, tendrán los significados respectivos que se les atribuyan en el [Acuerdo del Desarrollador](/developer-terms/agreement) o en el Acuerdo Maestro de Licencia (Master License Agreement).
## Uso de esta política
Hemos estructurado esta política para que sea lo más fácil de seguir posible. Ten presente la información de las siguientes secciones de la política mientras utilizas la API de X y el Contenido de X:
1. **Sigue las Directrices de Uso de la Plataforma** - Obtener la aprobación para acceder a la API de X y al Contenido de X es solo el primer paso. Nuestras Directrices de Uso de la Plataforma deberían ser tu primera parada cada vez que tengas preguntas sobre cómo asegurar el cumplimiento de la política para tu uso planeado de la plataforma X.
2. **Prepárate para el éxito** - Eres responsable de cumplir con todas las políticas de X. Es importante que revises y comprendas esta Política, así como las políticas que enlazamos en este documento, antes de acceder a la API de X y al Contenido de X. El tiempo dedicado a revisar nuestras políticas puede ahorrarte horas de retrabajo en el futuro.
3. **La privacidad y el control son esenciales** - Proteger y defender la privacidad de las personas en X está incorporado en el ADN central de nuestra empresa. Por lo tanto, prohibimos el uso de los datos de X de cualquier manera que sea incompatible con las expectativas razonables de privacidad de las personas. Al construir sobre la API de X o acceder al Contenido de X, tienes un papel especial que desempeñar en la salvaguarda de este compromiso, sobre todo respetando la privacidad de las personas y proporcionándoles transparencia y control sobre cómo se utilizan sus datos.
A continuación, hemos proporcionado muchos más detalles sobre lo que significa cada una de estas tres secciones clave. Revísalas cuidadosamente para asegurarte de que tu uso de la API de X y del Contenido de X sea coherente con nuestras políticas.
Si creemos que estás en violación de esta Política (o de cualquier otra política de X), podemos suspender o revocar permanentemente tu acceso a la API de X y al Contenido de X.
Finalmente, ten en cuenta que X puede monitorear tu uso de la API de X para mejorar las aplicaciones de X, examinar cualquier uso comercial y asegurar tu cumplimiento con tu caso de uso aprobado y con esta Política.
¡Gracias por leer, y gracias por construir con nosotros! ¡Esperamos ver lo que crearás!
## Directrices de uso de la plataforma
¿Te has tomado el tiempo para revisar las políticas de X y configurar tu acceso a la API de la manera correcta? ¿Tu servicio sigue las directrices de privacidad y control de X? Si puedes responder que sí a estas dos preguntas, entonces estás listo para comenzar a usar la API de X y el Contenido de X. Las Directrices de Uso de la Plataforma de X proporcionan la asistencia necesaria para asegurar que tu uso del Contenido de X cumpla con las políticas desde el día 1 y durante todo el ciclo de vida de tu servicio. Sugerimos revisar estas reglas regularmente para asegurarte de que tu integración funcione de manera segura y beneficiosa para las personas en X y para la plataforma de X en su conjunto.
## Spam, bots y automatización
**El uso de la API de X y de los productos para desarrolladores para crear spam o participar en cualquier forma de manipulación de la plataforma está prohibido.** Debes revisar las Reglas de X sobre [manipulación de la plataforma y spam](https://help.x.com/rules-and-policies/platform-manipulation) y asegurarte de que tu servicio no viole nuestras políticas ni permita que las personas lo hagan.
[**Los servicios que realizan acciones de escritura, incluidas publicar publicaciones, seguir cuentas o enviar mensajes directos, deben seguir las Reglas de Automatización.**](https://help.x.com/rules-and-policies/x-automation) En particular, debes:
* Obtener siempre el consentimiento explícito antes de enviar a las personas [respuestas o mensajes directos automatizados](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444)
* Respetar de inmediato las solicitudes de darse de baja de ser contactado por ti
* No realizar nunca acciones masivas, agresivas o de tipo spam, incluida la [seguidura masiva (bulk following)](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769)
* No publicar nunca contenido idéntico o sustancialmente similar en [múltiples cuentas](https://blog.twitter.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html)
**Si operas una cuenta de bot basada en API, debes indicar claramente qué es la cuenta y quién es responsable de ella.** Nunca debes engañar ni confundir a las personas sobre si tu cuenta es o no un bot. Una buena manera de hacerlo es incluyendo una declaración en la bio del perfil que indique que la cuenta es un bot.
## Benchmarking del rendimiento de X
**No puedes utilizar la API de X para medir la disponibilidad, el rendimiento, la funcionalidad o el uso de X con fines de benchmarking, competitivos o comerciales.** Por ejemplo, nunca debes usar la API de X para:
* Calcular métricas agregadas de X, como el número total de Usuarios Activos Mensuales (MAs) o Usuarios Activos Diarios (DAs)
* Calcular métricas agregadas de publicaciones de X, como el número total de publicaciones publicadas por día, o el número de interacciones de cuenta
* Medir o analizar la capacidad de respuesta de X
* Medir o analizar el spam o la seguridad en X, excepto según lo permitido a continuación
**Apoyamos la investigación que ayude a mejorar la salud de las conversaciones en X.** No puedes divulgar públicamente ninguna investigación o hallazgo relacionados con, ni desarrollar, crear u ofrecer servicios que utilicen, la API de X o el Contenido de X, que midan, analicen o intenten identificar comportamientos o contenido que violen las políticas de X sin el permiso expreso por escrito de X.
**Investigadores DSA:** Si necesitas contactar a X en relación con el acceso conforme al Art. 40 de la Ley de Servicios Digitales, contacta a [**EU-Questions@X.com**](mailto:EU-Questions@X.com). Si deseas solicitar acceso de investigador, envía una [solicitud](https://forms.gle/btDwenPF7M3hgSvw7).
## Visualización pública de publicaciones
**Debes mantener la integridad de todo el Contenido de X que muestres públicamente o a las personas que utilicen tu servicio.** Si no usas [X for Websites](https://developer.x.com/docs/twitter-for-websites/overview) para mostrar contenido, entonces debes usar la API de X para recuperar la versión más actual disponible para mostrarla. Si el contenido mostrado deja de estar disponible a través de la API de X, debes eliminarlo de tu servicio tan pronto como sea razonablemente posible, o dentro de las 24 horas siguientes a la recepción de una solicitud de eliminación por parte de X, o del propietario de la cuenta de X aplicable, o según lo requiera la ley aplicable.
**Hay reglas específicas que debes seguir si muestras Contenido de X sin conexión.** Sigue las [directrices](https://developer.x.com/developer-terms/display-requirements) para usar publicaciones en transmisión si muestras publicaciones sin conexión.
**Si incrustas o muestras publicaciones, debes contactarnos sobre tu acceso a la API de X si tu sitio supera los 10 millones de impresiones diarias.** X se reserva el derecho de exigir términos adicionales como condición para tu uso de la API de X. Las restricciones adicionales sobre el uso de X for Websites por parte de desarrolladores incluyen:
* **Publicaciones incrustadas y/o cronologías incrustadas**
* Debes proporcionar a las personas una notificación legalmente suficiente que revele completamente la recopilación y el uso por parte de X de los datos sobre las actividades de navegación en tu sitio web, incluida la publicidad basada en intereses y la personalización. También debes obtener el consentimiento legalmente suficiente de las personas para dicha recopilación y uso
* Debes proporcionar instrucciones legalmente suficientes sobre cómo las personas pueden optar por no participar en la publicidad basada en intereses y la personalización de X, como se describe [aquí](https://help.x.com/x-for-websites-ads-info-and-privacy)
* **Widgets de X for Websites**
* Debes asegurarte de que las personas reciban información clara y completa sobre, y consientan, el almacenamiento y acceso a cookies u otra información en sus dispositivos, tal como se describe en la [política de uso de cookies](https://help.x.com/rules-and-policies/x-cookies) de X, siempre que la ley exija proporcionar dicha información y obtener dicho consentimiento
* **Servicios dirigidos a niños menores de 13 años**
* Los servicios dirigidos a niños menores de 13 años deben optar por no personalizar X en cualquier publicación incrustada y/o cronologías incrustadas estableciendo el parámetro opt-out en “true”, como se describe [aquí](https://developer.x.com/docs/twitter-for-websites/privacy)
## Redistribución de contenido
**El mejor lugar para obtener Contenido de X es directamente de X. En consecuencia, restringimos la redistribución del Contenido de X a terceros.** Si proporcionas Contenido de X a terceros, incluyendo conjuntos de datos descargables o a través de una API, solo puedes distribuir IDs de publicación, IDs de mensajes directos y/o IDs de usuario (salvo lo descrito a continuación).
En total, no puedes distribuir más de 1.500.000 IDs de publicación a ninguna entidad (incluidos varios individuos asociados con una sola entidad) dentro de un período de 30 días a menos que hayas recibido permiso por escrito de X. Además, los desarrolladores pueden proporcionar hasta 500 objetos de publicaciones públicas y/u objetos de usuario a cada persona que utilice tu servicio diariamente, siempre que se haga por medios no automatizados (por ejemplo, descarga de hojas de cálculo o PDFs).
Los investigadores académicos pueden distribuir IDs de publicación y/o IDs de usuario únicamente con fines de investigación no comercial en nombre de una institución académica y que haya sido aprobada por escrito por X, o para revisión por pares o validación de dicha investigación. Solo se pueden utilizar tantos IDs de publicación o IDs de usuario como sean necesarios para tal investigación y hayan sido aprobados por X.
Todo Contenido de X proporcionado a terceros sigue estando sujeto a esta Política, y esos terceros deben aceptar los [Términos de Servicio](https://x.com/tos), la [Política de Privacidad](https://x.com/privacy), el [Acuerdo del Desarrollador](/developer-terms/agreement) y la [Política del Desarrollador](/developer-terms/policy) de X antes de recibir dichas descargas. No puedes permitir que ninguna entidad eluda otras limitaciones o restricciones sobre la distribución del Contenido de X contenidas en esta [Política](/developer-terms/policy), el [Acuerdo del Desarrollador](/developer-terms/agreement) o cualquier otro acuerdo con X.
**Nota:** Esta sección no se aplica a los investigadores con acceso a la API de X conforme al Art. 40 de la Ley de Servicios Digitales de la UE (2022) (“**DSA**”), quienes en su lugar están sujetos a los procedimientos y restricciones establecidos en la DSA y en el Acuerdo del Desarrollador.
## Pagar por interactuar
**Tu servicio no debería compensar a las personas por realizar acciones en X, ya que eso genera interacciones no auténticas que degradan la salud de la plataforma.** Al utilizar la API de X, no puedes vender ni recibir compensación monetaria o virtual por ninguna acción en X. Esto incluye, entre otros, publicaciones, seguir cuentas, dejar de seguir cuentas, republicaciones, me gusta, comentarios y respuestas.
## Autenticidad del servicio
**Debes identificar claramente tu servicio para que las personas puedan comprender su fuente y propósito.** No uses nombres, logotipos o URLs que oculten la identidad y las funciones de tu servicio, o que impliquen falsamente una afiliación con X o con terceros. Ten en cuenta que crear aplicaciones con el propósito de vender nombres, o de impedir que otros usen nombres, está prohibido.
**No puedes utilizar ninguna URL (incluidas URLs acortadas) para tu servicio que dirija a las personas a:**
* Un sitio no relacionado con tu servicio
* Un sitio de spam o malware
* Un sitio que aliente a las personas a violar la política de X
## Nombre, logotipo e imagen de X
**Solo puedes utilizar y mostrar el nombre y el logotipo de X para identificar a X como la fuente del Contenido de X.** Nunca debes usar el nombre y el logotipo de X, la insignia del X Official Partner Program u otras marcas o nombres similares de una manera que cree un falso sentido de respaldo, patrocinio o asociación con X. Los [Recursos de Marca](https://about.x.com/who-we-are/brand-toolkit) de X contienen información detallada para ayudarte a usar la marca X de la manera correcta.
**Solo puedes utilizar la insignia de Cuenta Verificada de X y cualquier otra categorización mejorada de cuenta tal como te sea reportada por X a través de la API.** Esto ayuda a que las personas sepan que el contenido que muestra tu servicio es equivalente al que se muestra en X.
## Publicidad en X
**Existen restricciones sobre cómo y dónde se te permite anunciarte alrededor del Contenido de X.** Para empezar, tus anuncios no pueden parecerse a una publicación ni ser confundidos razonablemente con una por las personas. Otras reglas sobre publicidad incluyen:
* **Debe haber una separación clara entre el Contenido de X y tus anuncios.** No puedes colocar anuncios dentro de la cronología de X que no sean X Ads.
* **X se reserva el derecho de servir publicidad a través de la API de X.** Si decides mostrar X Ads una vez que comencemos a entregarlos a través de la API, compartiremos contigo una parte de los ingresos publicitarios de acuerdo con los términos y condiciones pertinentes.
* **No puedes utilizar Contenido de X ni información obtenida de la API de X para dirigir anuncios a personas fuera de la plataforma X.**
Las siguientes reglas adicionales se aplican a cualquier uso de los servicios o funciones de X que se enumeran a continuación:
## X Login
**Debes presentar a las personas opciones fáciles de encontrar para iniciar y cerrar sesión en X, por ejemplo, a través del protocolo OAuth.** La opción *Iniciar sesión con X* debe mostrarse al menos con la misma prominencia que cualquier otra función de registro o inicio de sesión en tu servicio. También debes proporcionar a las personas sin una cuenta de X la oportunidad de crear una a través de X.
***Una vez que alguien en tu servicio se autentique mediante Iniciar sesión con X, debes mostrar claramente su identidad de X.*** La identidad de X incluye el @handle actual de la persona en X, el avatar y el logotipo de X. Cualquier visualización de los seguidores de alguien en X en tu servicio debe mostrar claramente que la relación está asociada con X.
X se reserva el derecho de monitorear el número total de usuarios únicos que se han autenticado o iniciado sesión mediante Iniciar Sesión con X (u otros métodos de autenticación de X) en tus productos, servicios, o aquellos hechos disponibles por o para ti o tus afiliados y, en caso de que ese número total supere ampliamente los niveles normales de otros desarrolladores suscritos a un nivel de servicio similar, debes solicitar (o ya estar suscrito) a un plan Enterprise mediante notificación por escrito de X.
Aceptas que X pueda, de vez en cuando, revisar tu opción de *Iniciar sesión con X* y, a su entera discreción, eliminar esta función de X de tu servicio.
## X Cards
**Para garantizar una experiencia de calidad, debes desarrollar tu Card para que se renderice en todas las plataformas donde se muestren Cards.** Las reglas adicionales que debes seguir al usar Cards incluyen:
* Debes marcar tu publicación como “true” para contenido multimedia sensible si planeas mostrar dicho contenido dentro de una Card
* Debes usar HTTPS para alojar todos los recursos dentro de tu Card. Tu Card nunca debe generar advertencias activas de contenido mixto en el navegador
* El contenido de audio y video debe incluir controles de detener o pausar y, por defecto, tener el “sonido apagado” para los videos que reproducen contenido automáticamente
**No puedes exceder ni eludir las limitaciones que X impone a cualquier Card, incluido el uso previsto de la Card.** Las restricciones adicionales sobre el uso de Cards incluyen:
* No puedes colocar contenido patrocinado por terceros dentro de las Cards sin la aprobación de X
* No puedes adjuntar incentivos monetarios (incluidas monedas virtuales) dentro de tu Card o en X desde tu Card
* No puedes incluir contenido o acciones dentro de tu Card que sean engañosos o no relevantes contextualmente, como URLs y contenido multimedia.
* Solo puedes adjuntar una App Card a una publicación cuando alguien esté promoviendo o refiriéndose explícitamente a la aplicación en la publicación.
## Prepárate para el éxito
Puedes evitar muchos posibles inconvenientes al usar la API de X asegurándote de que tu servicio se haya construido de la manera correcta desde el día 1. Esta sección de la Política del Desarrollador contiene reglas que todos los desarrolladores deben seguir antes de usar la API de X o el Contenido de X.
Los planes Free, Basic y Pro (como se describe en [developer.x.com](http://developer.x.com)) están diseñados para aficionados, prototipos comerciales, integraciones tempranas de productos X y aplicaciones de soporte con usuarios finales limitados. Si utilizas la API de X y el Contenido de X más allá de este alcance, debes solicitar (o ya estar suscrito) un plan Enterprise (como se describe en [developer.x.com](http://developer.x.com)).
**Revisamos todos los usos propuestos de la plataforma para desarrolladores de X para verificar el cumplimiento de la política; por lo tanto, se te exige divulgar (y actualizar, según corresponda) tu uso planeado de la API de X y del Contenido de X para que se te conceda y mantenga el acceso.** Todos los nuevos desarrolladores deben [solicitar una cuenta de desarrollador](https://developer.x.com/portal/petition/essential/basic-info) para acceder a la API de X. Los desarrolladores actuales sin una cuenta de desarrollador aprobada deben solicitar una cuando X les indique hacerlo. Como parte de este proceso, deberás proporcionarnos una descripción escrita de tus usos previstos de la API de X y del Contenido de X.
La descripción de tu caso de uso es vinculante para ti, y cualquier desviación sustancial del mismo puede constituir una violación de nuestras reglas y dar lugar a acciones de cumplimiento. Debes notificarnos cualquier modificación sustancial de tu caso de uso y recibir aprobación antes de comenzar a usar el Contenido de X para ese nuevo propósito. No hacerlo puede resultar en la suspensión y terminación de tu acceso a la API y a los datos.
**Al construir sobre la API de X o acceder al Contenido de X, debes cumplir con TODAS las políticas de X.** Estas incluyen esta [Política del Desarrollador](/developer-terms/policy), las [Reglas de Automatización](https://help.x.com/rules-and-policies/x-automation), los [Requisitos de Visualización](https://developer.x.com/developer-terms/display-requirements.html), las [Reglas de Uso Restringido de la API](/developer-terms/restricted-use-cases), las [Reglas de X](https://help.x.com/rules-and-policies/x-rules) y los [Recursos de Marca de X](https://about.x.com/who-we-are/brand-toolkit), así como cualquier otro acuerdo en el que participes con X en relación con tu uso de la API de X o del Contenido de X, incluidos, entre otros, el [Acuerdo del Desarrollador](/developer-terms/agreement) o un Acuerdo Maestro de Licencia u Orden (según corresponda). También debes cumplir con cualquier modificación a estas políticas y con cualquier nueva política lanzada por X. Es tu responsabilidad monitorear el uso de tu servicio y diseñarlo para prevenir violaciones de la política de X por parte de las personas que lo usan. No hacerlo puede resultar en la suspensión o terminación del acceso a la API y al Contenido de X.
**No puedes registrar múltiples aplicaciones para un solo caso de uso o para casos de uso sustancialmente similares o superpuestos.** En este contexto, un “caso de uso” es un conjunto consistente de análisis, visualizaciones o acciones realizadas a través de una aplicación. Las versiones “White label” (marca blanca) de una herramienta o servicio no están permitidas. Si planeas “white label” versiones de tu aplicación, debes notificarnos y recibir una aprobación separada.
*Como única excepción a estas reglas,* puedes crear y utilizar un máximo de 3 aplicaciones para instancias de desarrollo, staging y producción del mismo servicio. Estas aplicaciones deben estar registradas bajo una sola cuenta y deben identificarse claramente (en el nombre y la descripción) como instancias dev, staging y prod de un único servicio. **No puedes usar aplicaciones de desarrollo o staging para fines de producción.**
**Debes mantener privadas todas las claves de API u otras credenciales de acceso.** No puedes usar, ni alentar o facilitar que otros usen, claves de API u otras credenciales de acceso pertenecientes a terceros.
**Tu acuerdo de licencia con X limita tu uso de la API de X y del Contenido de X. Entre otras cosas, la API de X tiene límites de tasa (rate limits) que ayudan a asegurar un uso justo de los datos y a combatir el spam en la plataforma.** No puedes exceder ni eludir los límites de tasa ni ninguna otra limitación o restricción descrita en esta Política o en tu acuerdo con X, listada en el [sitio para desarrolladores](https://developer.x.com/) o comunicada a ti por X.
**No puedes eliminar ni alterar ningún aviso o marca de propiedad en el Contenido de X recibido a través de la API de X.** Esto ayuda a garantizar que las personas sepan de dónde proviene el Contenido de X y a quién pertenece.
**Por razones de integridad de los datos y salud de la plataforma, no puedes interferir, interceptar, interrumpir ni deshabilitar ninguna función de la API de X ni del servicio X.** En otras palabras, usa las APIs tal como están previstas y documentadas en [developer.x.com](https://developer.x.com/). Consulta nuestras [directrices de HackerOne](https://hackerone.com/x) para obtener más detalles sobre el uso aceptable.
## La privacidad y el control son esenciales
X se toma la privacidad en serio, y esperamos que todos los que usen el Contenido de X y la API de X hagan lo mismo. Cualquier uso de la plataforma para desarrolladores de X, la API de X o el Contenido de X de manera incompatible con las expectativas razonables de privacidad de las personas puede estar sujeto a acciones de cumplimiento, que pueden incluir la suspensión y terminación del acceso a la API y al Contenido de X.
Tu compromiso con la privacidad y el control debe extenderse a todos los usos del Contenido de X y a todos los aspectos del servicio que construyas utilizando nuestra API. Con ese fin, las personas que utilicen tu servicio deben comprender y consentir cómo usas sus datos y cómo accedes a X en su nombre. Esto puede lograrse proporcionando a las personas una política de privacidad clara, completa y transparente, así como asegurándote de obtener el consentimiento expreso e informado de cada persona que use tu servicio antes de realizar cualquier acción en su nombre. **Ten en cuenta que el hecho de que una persona se autentique en tu servicio no constituye por sí solo un consentimiento.**
## Consentimiento y permisos
**En particular, debes obtener el consentimiento expreso e informado de las personas antes de realizar cualquiera de las siguientes acciones:**
* Realizar *cualquier* acción en su nombre. Esto incluye (entre otros):
* Publicar contenido en X
* Seguir/dejar de seguir cuentas
* Modificar la información del perfil o de la cuenta
* Añadir hashtags o cualquier otro contenido a las publicaciones
* Republicar contenido al que se accedió por medios distintos a la API de X u otras herramientas de X
* Utilizar el Contenido de X de alguien para promocionar un producto o servicio
* Almacenar contenido no público, como mensajes directos (DMs), o cualquier otra información privada o confidencial
* Compartir o publicar contenido protegido, o cualquier otra información privada o confidencial
**Si tu servicio permite a las personas publicar contenido en X, debes hacer lo siguiente antes de publicar:**
* Mostrar exactamente qué se publicará
* Dejar claro a las personas que utilizan tu servicio qué información geográfica (si la hay) se añadirá al contenido
**Si tu servicio permite a las personas publicar contenido tanto en tu servicio como en X, debes hacer lo siguiente antes de publicar:**
* Obtener permiso para publicar el contenido
* Explicar dónde publicarás el contenido
**Debes respetar el estado protegido y bloqueado de todo el Contenido de X. No puedes servir contenido obtenido usando el token de autenticación de una persona a otra persona que no esté autorizada a ver ese contenido.**
* **Cuentas protegidas:** El contenido de una [cuenta protegida](https://help.x.com/safety-and-security/public-and-protected-posts) solo está disponible para las personas que hayan sido aprobadas por el propietario para seguir esa cuenta. Por lo tanto, si ejecutas un servicio que accede a cuentas protegidas, solo puedes hacerlo para servir ese contenido a las personas específicas con permiso para verlo.
* **Cuentas bloqueadas:** Las personas en X pueden [bloquear](https://help.x.com/using-x/blocking-and-unblocking-accounts) el acceso a sus cuentas por cualquier razón que elijan. No está permitido mezclar información obtenida de tokens (o cualquier otra acción basada en la API) para eludir esta elección.
**Dado que los mensajes directos (DMs) son de naturaleza no pública, los servicios que ofrezcan funciones de DM deben tomar medidas adicionales para salvaguardar la privacidad personal. No puedes servir contenido de DM a personas que no estén autorizadas a verlo. Si tu servicio proporciona funcionalidad de DM, también debes:**
* Notificar a las personas si envías eventos de confirmación de lectura para los DMs. Puedes hacerlo proporcionando un aviso directamente en tu servicio o mostrando las confirmaciones de lectura de otros participantes en una conversación.
* Obtener consentimiento antes de configurar contenido multimedia que se envíe en un DM como “compartido” (es decir, reutilizable en múltiples DMs). Si permites que un archivo multimedia en un DM sea “compartido”, debes proporcionar un aviso claro de que este contenido será accesible para cualquiera que tenga la URL del archivo multimedia.
## Cumplimiento del contenido
**Si almacenas Contenido de X sin conexión, debes mantenerlo actualizado con el estado actual de ese contenido en X.** Específicamente, debes eliminar o modificar cualquier contenido que tengas si se elimina o modifica en X. Esto debe hacerse tan pronto como sea razonablemente posible, o dentro de las 24 horas después de recibir una solicitud para hacerlo por parte de X o del propietario de la cuenta de X correspondiente, o según lo requiera tu acuerdo con X o la ley aplicable. Esto debe hacerse salvo que la ley lo prohíba, y solo entonces con el permiso expreso y por escrito de X.
El contenido modificado puede tomar varias formas. Esto incluye (entre otras):
* Contenido que se haya hecho privado o haya obtenido estado protegido
* Contenido que haya sido suspendido de la plataforma
* Contenido al que se le hayan eliminado los geotags
* Contenido que haya sido retenido o eliminado de X
## Emparejamiento fuera de X (Off-X matching)
**Limitamos las circunstancias bajo las cuales puedes emparejar a una persona en X con información obtenida o almacenada fuera de X.** El emparejamiento fuera de X implica asociar Contenido de X, incluidos un @handle o ID de usuario de X, con una persona, hogar, dispositivo, navegador u otro identificador fuera de X. Solo puedes hacer esto si tienes el consentimiento expreso opt-in de la persona antes de hacer la asociación, o como se describe a continuación.
En situaciones en las que no tienes el consentimiento expreso opt-in de una persona para vincular su identidad de X con un identificador fuera de X, requerimos que cualquier conexión que hagas se base únicamente en información que alguien razonablemente esperaría que se utilizara para ese propósito. Además, en ausencia del consentimiento expreso opt-in de la persona, solo puedes intentar emparejar tus registros sobre alguien con una identidad de X en función de:
* **Información proporcionada directamente a ti por la persona.** Ten en cuenta que los registros sobre personas con las que no tienes una relación previa, incluidos los datos sobre individuos obtenidos de terceros, no cumplen este estándar; y/o
* **Datos públicos.** “Datos públicos” en este contexto se refiere a:
* Información sobre una persona que obtuviste de un recurso público y generalmente disponible (como un directorio de miembros de una asociación profesional)
* Información en X sobre una persona que está disponible públicamente, incluyendo:
* Publicaciones
* Información de perfil, incluyendo la bio de la cuenta y la ubicación declarada públicamente
* Nombre para mostrar y @handle
## Tu política de privacidad
**Debes mostrar la política de privacidad de tu servicio a las personas antes de que se les permita descargar, instalar o registrarse en tu servicio.** Debe divulgar al menos la siguiente información:
* La información que recopilas de las personas que utilizan tu servicio
* Cómo utilizas y compartes esa información (incluyendo con X)
* Cómo las personas pueden contactarte con consultas y solicitudes relacionadas con su información
Tu política de privacidad debe ser coherente con todas las leyes aplicables y no ser menos protectora de las personas que la [Política de Privacidad de X](https://x.com/privacy) y la [política de privacidad de nuestros otros servicios y afiliados corporativos](https://help.x.com/rules-and-policies/x-services-and-corporate-affiliates). Debes cesar tu acceso a la API de X y el uso de todo el Contenido de X si no puedes cumplir con tu política de privacidad y/o la de X.
## Uso de datos geográficos
**El uso de datos geográficos conlleva restricciones adicionales debido a la naturaleza sensible de esta información.** Si tu servicio agrega información de ubicación a las publicaciones, debes divulgar a las personas:
* Cuándo añades información de ubicación
* Si añades información de ubicación como geotag o como datos de anotaciones
* Si tu información de ubicación aparece como un lugar o como coordenadas geográficas
Si tu aplicación permite a las personas publicar con su ubicación, debes cumplir con las [directrices geográficas](/developer-terms/geo-guidelines) de X en su totalidad.
**Cualquier uso de los datos de ubicación o de la información geográfica de forma independiente está prohibido.** No puedes (ni puedes permitir a otros) almacenar, agregar o cachear datos de ubicación y otra información geográfica contenida en el Contenido de X, excepto como parte de una publicación. Por ejemplo, no puedes separar los datos de ubicación o la información geográfica de las publicaciones para mostrar dónde han estado las personas a lo largo del tiempo. Se permiten los mapas de calor y las herramientas relacionadas que muestran la actividad geográfica agregada (por ejemplo, el número de personas en una ciudad que utilizan un hashtag).
## Contraseñas de X
**No puedes almacenar contraseñas de X, ni solicitar que las personas te proporcionen directamente su contraseña de X, credenciales de cuenta o información de aplicación de desarrollador (incluida la consumer key).** Sugerimos el uso de [Iniciar sesión con X](/fundamentals/authentication/guides/log-in-with-x) como herramienta de autenticación para vincular tu servicio y las personas en X.
# Acuerdo de X Developer PPU
Source: https://docs.x.com/es/developer-terms/ppu-agreement
El Acuerdo de Pago por Uso (Pay-Per-Use) del Desarrollador de X cubre los términos para la compra y el uso de créditos en los servicios de pago de la API de X, incluidas las reglas de facturación y uso.
Al hacer clic en “Pagar” y comprar créditos para su uso en los Servicios de Pago, o al acceder o utilizar de cualquier otra manera cualquier Material Licenciado, aceptas los términos de nuestro Acuerdo. Los Créditos no caducan salvo que se especifique lo contrario, y no son transferibles ni reembolsables excepto en los casos requeridos por la ley. Se requiere un número de teléfono verificado para comprar Créditos.
Este Acuerdo de X Developer PPU (“**Acuerdo**”) es un acuerdo legal vinculante entre tú (referido en este Acuerdo como “**tú**”) y X, y rige tu acceso y uso del Material Licenciado (definido a continuación), incluidos los Servicios de Pago (definidos a continuación).
Al acceder o utilizar cualquier Material Licenciado (definido a continuación), o al hacer clic en un botón para aceptar los términos de este Acuerdo o comprar créditos para los Servicios de Pago, aceptas quedar vinculado por los términos de este Acuerdo. Si no comprendes los términos aquí incluidos o no aceptas alguna parte de ellos, entonces no puedes usar ni acceder a ningún Material Licenciado. No puedes utilizar el Material Licenciado ni aceptar este Acuerdo si no tienes la edad legal para celebrar un contrato vinculante con X o si tienes prohibido usar o recibir el Material Licenciado bajo la ley aplicable. Para comprar y usar un Servicio de Pago debes: (i) tener al menos 18 años o la mayoría de edad según las leyes de la jurisdicción en la que vivas, o (ii) contar con el consentimiento expreso de tu padre, madre o tutor para comprar y usar ese Servicio de Pago. Si eres padre, madre o tutor legal y permites que tu hijo/a (o un/a menor del que seas tutor) compre o use un Servicio de Pago, aceptas que los términos de este Acuerdo se apliquen a ti, que cumplirás con este Acuerdo, y que eres responsable de la actividad del menor en los Servicios de Pago y de asegurar que el menor también cumpla con los términos de este Acuerdo. En cualquier caso, tal como se indica en la sección Quién puede usar los Servicios de los [**Términos de Servicio de X**](https://x.com/tos), debes tener al menos 13 años para usar los “Servicios” tal como se definen en los Términos de Servicio de X. Si aceptas este Acuerdo o utilizas el Material Licenciado en nombre de una empresa, organización, gobierno u otra entidad legal, declaras y garantizas que tienes la autoridad para vincular a dicha empresa, organización, gobierno u otra entidad legal a este Acuerdo, en cuyo caso las palabras “tú” y “tu/tus” tal como se utilizan en este Acuerdo se referirán a dicha entidad. Si no estás de acuerdo con los términos de este Acuerdo, no puedes (y no puedes permitir a ninguno de tu personal) acceder o utilizar el Material Licenciado.
I. **Definiciones**.
En este Acuerdo, se aplican las siguientes definiciones:
1. **“Créditos”** significa las unidades virtuales adquiridas por ti para habilitar el uso de los Servicios de Pago, y cada llamada o acción a la API deduce un número específico de Créditos según el Programa de Precios. Los Créditos no son reembolsables salvo que la ley lo exija, no son transferibles y no caducan salvo que se especifique lo contrario.
2\. **“Sitio para Desarrolladores”** significa el sitio para desarrolladores de X ubicado en [**https://developer.x.com**](https://developer.x.com/)
3\. **“Mensaje Directo”** significa un mensaje privado que se envía en las Aplicaciones de X por un usuario a uno o más usuarios específicos utilizando la función de mensajería directa de X.
4\. **“Derechos de Propiedad Intelectual”** significa todos los derechos de autor, derechos morales, derechos de patente, marcas comerciales y cualquier otra propiedad intelectual o derechos similares (registrados o no) en todo el mundo.
5\. **“Material Licenciado”** significa, individual o colectivamente, la API de X y el Contenido de X.
6\. **"Servicio(s) de Pago”** significa características o funcionalidades del Material Licenciado a las que accedes a cambio de la deducción de créditos comprados a X y descontados de tu cuenta en función de tu uso de llamadas y funciones, tal como se detalla en nuestra página de precios. Salvo que se establezca lo contrario en este Acuerdo, todas las referencias a “Material Licenciado” incluyen los Servicios de Pago.
7\. **“Portal de Pago”** significa el portal en línea que se pone a tu disposición para aceptar (opt-in) tu uso del Material Licenciado, gestionar las compras de créditos para los Servicios de Pago, gestionar los métodos de pago para los Servicios de Pago, habilitar la “Recarga Automática” (véase la Sección VII.F) y actualizar la información de la cuenta.
8\. **“Servicios”** significa tus servicios, sitios web, aplicaciones y otras ofertas (incluidas las de investigación) que muestren Contenido de X o que utilicen de otro modo el Material Licenciado.
9\. **“Publicación”** significa un mensaje corto basado en texto y multimedia distribuido a través de las Aplicaciones de X.
10\. **“Programa de Precios”** significa la lista actual de precios por llamada a la API o acción, disponible en [https://developer.x.com/#pricing](https://developer.x.com/#pricing).
11\. **“X”** significa (a) X Corp. (865 FM 1209, Building 2, Bastrop, TX 78602, USA) si tu principal lugar de negocios está fuera de la Unión Europea, los Estados de la AELC (EFTA) y el Reino Unido; o (b) X Internet Unlimited Company (One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland) si tu principal lugar de negocios está en la Unión Europea, los Estados de la AELC (EFTA) o el Reino Unido.
12\. **“API de X”** significa las Interfaces de Programación de Aplicaciones (cada una, una “API”) de X, los Kits de Desarrollo de Software (cada uno, un “SDK”), y las herramientas, documentación, datos, tecnología, código y otros materiales relacionados proporcionados por X a través del Sitio para Desarrolladores.
13\. **“Aplicaciones de X”** significa el servicio de información en tiempo real de X, comúnmente conocido como “X”, que incluye los servicios actualmente proporcionados por X en sus sitios web y aplicaciones móviles propiedad, operadas o controladas por X, complementos sociales e interfaces de programación de aplicaciones.
14\. **“Contenido de X”** significa las Publicaciones, el número de identificación único generado para cada Publicación, la información de perfil de los usuarios finales de X y cualquier otro dato e información puesta a tu disposición a través de la API de X o por cualquier otro medio autorizado por X, así como cualquier copia y obra derivada de los mismos.
15\. **“Marcas de X”** significa el nombre, las marcas comerciales y los logotipos de X que X pone a tu disposición, incluso a través del Sitio para Desarrolladores, únicamente para su uso de acuerdo con este Acuerdo.
16\. **“Usuarios”** significa los visitantes, usuarios o clientes de tus Servicios.
**II. API de X y Contenido de X.**
**A. Licencia de X.** Sujeto a tu cumplimiento con los términos de este Acuerdo y los Términos para Desarrolladores Incorporados aplicables (como se define a continuación), X te otorga por la presente una licencia no exclusiva, libre de regalías, no transferible, no sublicenciable y revocable únicamente para:
1\. Utilizar la API de X para integrar Contenido de X en tus Servicios o realizar análisis del Contenido de X, tal como haya sido aprobado explícitamente por X;
2\. Copiar una cantidad razonable de y mostrar el Contenido de X en y a través de tus Servicios a los Usuarios, según lo permita este Acuerdo;
3\. Modificar el Contenido de X únicamente para darle formato para su visualización en tus Servicios; y
4\. Utilizar y mostrar las Marcas de X para atribuir a las Aplicaciones de X como fuente del Contenido de X, según lo establecido en este Acuerdo.
**B. Licencia a X.** Por la presente otorgas a X una licencia no exclusiva, libre de regalías, no transferible y no sublicenciable revocable para acceder, indexar y almacenar en caché por cualquier medio, incluidos web spiders y/o crawlers, cualquier página web o aplicación en la que muestres Contenido de X utilizando [**Publicaciones incrustadas** o **cronologías incrustadas**](https://publish.x.com).
**C. Términos Incorporados.** Tu acceso y uso del Material Licenciado también está sujeto, y deberás cumplir, con los siguientes términos y políticas adicionales (colectivamente, “**Términos para Desarrolladores Incorporados**”):
1\. la [**Política del Desarrollador de X**](https://docs.x.com/developer-terms/policy);
2\. las [**Reglas de Uso Restringido de la API**](https://docs.x.com/developer-terms/restricted-use-cases);
3\. las [**Reglas de X**](https://help.x.com/rules-and-policies/x-rules);
4\. en lo que se refiere a tu visualización de cualquier Contenido de X, los [**Requisitos de Visualización**](https://docs.x.com/developer-terms/display-requirements);
5\. en lo que se refiere a tu uso y visualización de las Marcas de X, las [**Directrices de Marca de X**](https://about.x.com/who-we-are/brand-toolkit); y
6\. en lo que se refiere a la realización de acciones automatizadas en tu cuenta, las [**Reglas de Automatización**](https://help.x.com/rules-and-policies/x-automation).
**III. Restricciones de Uso.**
**A. Ingeniería Inversa y otras Restricciones.** No deberás, ni intentarás (ni permitirás a otros): (a) realizar ingeniería inversa, descompilar, desensamblar o traducir la API de X ni intentar de otro modo derivar el código fuente, secretos comerciales o conocimientos técnicos (know-how) subyacentes a cualquier API de X o cualquier parte de la misma; (b) interferir, modificar, interrumpir o deshabilitar funciones o funcionalidades de la API de X o los mecanismos de monitoreo de la API de X; (c) usar o acceder al Material Licenciado para crear o intentar crear un servicio o producto sustituto o similar a las Aplicaciones de X; (d) vender, alquilar, arrendar, sublicenciar, distribuir, redistribuir, sindicar, crear obras derivadas de, asignar o transferir o proporcionar acceso de otro modo, total o parcialmente, al Material Licenciado a un tercero, excepto según lo expresamente permitido en este Acuerdo; (e) proporcionar el uso de la API de X en base a service bureau, alquiler o servicios administrados, o permitir a otras personas o entidades crear enlaces a la API de X, o hacer "frame" o "mirror" de la API de X en cualquier otro servidor, o dispositivo inalámbrico o basado en Internet, o poner a disposición de un tercero cualquier token, clave, contraseña u otras credenciales de inicio de sesión de la API de X; (f) utilizar el Material Licenciado para cualquier fin ilegal, no autorizado o cualquier otro fin indebido; (g) utilizar el Material Licenciado para derivar u obtener información no pública de usuarios individuales de X; (h) interferir o interrumpir la integridad o el rendimiento de las Aplicaciones de X, la API de X o el Contenido de X contenido en las mismas; (i) eliminar o alterar cualquier aviso o marca de propiedad en el Contenido de X; (j) intentar obtener acceso no autorizado a las Aplicaciones de X, la API de X, el Contenido de X o sistemas o redes relacionados; (k) utilizar la API de X o el Contenido de X para hacer fine-tuning o entrenar un modelo fundacional o de frontera; o (l) utilizar el Contenido de X, por sí solo o combinado con datos de terceros, o análisis derivados del mismo, para dirigirse a los usuarios con publicidad fuera de las Aplicaciones de X.
**B. Restricciones de Uso Comercial.** Si tus Servicios están designados como "no comerciales", no deberás hacer Uso Comercial (como se define a continuación) del Material Licenciado. Las restricciones de Uso Comercial pueden no aplicarse a organizaciones sin fines de lucro registradas oficialmente u ONG. "Uso Comercial" significa cualquier uso del Material Licenciado o acceso a la API de X: (a) por parte de o para un negocio (es decir, una entidad cuyo propósito principal es obtener ingresos a través de un producto o servicio), o (b) como parte de un producto o servicio que se monetiza (por ejemplo, publicidad en el sitio web, tarifas de licencia, promociones dentro de la aplicación y patrocinios).
**C. Sin Monitoreo ni Medición.** No obstante cualquier disposición en contrario, puedes utilizar la siguiente información únicamente con fines internos y no comerciales (por ejemplo, para mejorar la funcionalidad de los Servicios): (a) métricas agregadas de usuarios de las Aplicaciones de X, como el número de usuarios o cuentas activos en las Aplicaciones de X; (b) la capacidad de respuesta de las Aplicaciones de X; y (c) resultados, estadísticas de uso, datos u otra información (agregada o de otro modo) derivada del análisis, uso o rendimiento de la API de X. Toda esta información constituye Información Confidencial (como se define a continuación).
**D. Límites de Tasa.** No intentarás exceder ni eludir las limitaciones sobre el acceso, las llamadas y el uso de la API de X ("Límites de Tasa") ni utilizarás la API de X de otro modo que exceda un volumen razonable de solicitudes, constituya un uso excesivo o abusivo, o que de otro modo no cumpla con este Acuerdo. Las llamadas y solicitudes a la API deducirán créditos de tu saldo según lo especificado en el Programa de Precios disponible en [https://developer.x.com/#pricing](https://developer.x.com/#pricing). Si tu saldo de créditos es insuficiente para una llamada, las solicitudes serán rechazadas hasta que tu saldo de créditos sea suficiente para permitir la deducción de esa solicitud. Si excedes o X cree razonablemente que has intentado eludir los Límites de Tasa, los controles para limitar el uso de las APIs de X, o que estás utilizando de otro modo el Material Licenciado en incumplimiento de este Acuerdo, entonces tu capacidad para usar el Material Licenciado podrá ser suspendida temporalmente o bloqueada permanentemente. X puede monitorear tu uso de la API de X para mejorar el Material Licenciado y las Aplicaciones de X, y para asegurar tu cumplimiento con este Acuerdo y los Términos para Desarrolladores Incorporados. Aceptas cumplir con las solicitudes de X de información adicional en relación con tu uso. X puede revisar tu uso del Material Licenciado en cualquier momento. La concesión por parte de X de acceso a la API de X o el permiso para usar el Material Licenciado no se considerará una aprobación de tu uso ni una renuncia o limitación de su derecho a exigir un uso conforme con este Acuerdo y las políticas de X. Ninguno de los pagos realizados es reembolsable; no obstante, X podrá, a su discreción, permitir que los Créditos no utilizados se apliquen a un uso conforme con este Acuerdo.
**E. Datos de Ubicación.** No deberás, ni permitirás a otros, agregar, almacenar en caché o almacenar datos de ubicación y otra información geográfica contenida en el Contenido de X excepto en conjunción con el Contenido de X al que se adjuntan. Solo puedes usar los datos de ubicación y la información geográfica para identificar la ubicación etiquetada por el Contenido de X.
**F. Uso de las Marcas de X.** No deberás incluir ninguna de las Marcas de X en tu(s) nombre(s) corporativo(s) registrado(s), tus logotipos ni tus nombres de servicio o producto. No deberás crear obras derivadas de las Marcas de X ni utilizar las Marcas de X de manera que cree o razonablemente implique un respaldo, patrocinio o asociación con X. Todo uso de las Marcas de X y toda buena voluntad (goodwill) que surja del uso redundarán en beneficio de X. No eliminarás ni alterarás ningún aviso de propiedad o Marca de X en el Material Licenciado.
**G. Seguridad.** Mantendrás la seguridad de la API de X y no pondrás a disposición de ningún tercero ningún token, clave, contraseña u otras credenciales de inicio de sesión de la API de X. Utilizarás medidas de seguridad estándar del sector para prevenir el acceso o uso no autorizado de cualquier función y funcionalidad de la API de X, incluido el acceso por virus, gusanos o cualquier otro código o material dañino. Mantendrás el Contenido de X confidencial y seguro contra el acceso no autorizado utilizando salvaguardas organizativas y técnicas estándar del sector para dichos datos, y con no menos cuidado del que utilizas al asegurar datos similares que almacenas. Notificarás inmediatamente a X, consultarás y cooperarás con las investigaciones, asistirás con cualquier notificación requerida y proporcionarás cualquier información razonablemente solicitada por X si tienes conocimiento o sospechas de cualquier violación de seguridad o posible vulnerabilidad relacionada con el Material Licenciado. Remediarás con prontitud cualquier violación o posible vulnerabilidad resultante de tu acceso al Material Licenciado.
**H. Ley de Servicios Digitales.** No obstante cualquier disposición en contrario en este Acuerdo, en la medida en que se te proporcione acceso al Material Licenciado conforme a los procedimientos descritos en el Artículo 40 de la Ley de Servicios Digitales (Reglamento (UE) 2022/2065) (“DSA”), tu acceso y uso del Material Licenciado se limita únicamente a realizar investigaciones que contribuyan a la detección, identificación y comprensión de los riesgos sistémicos en la Unión Europea y solo en la medida necesaria para que X cumpla sus obligaciones bajo la DSA. Cualquier uso del Material Licenciado es no comercial, tal como se describe en la Sección III(B) de este Acuerdo. No puedes divulgar, reproducir, licenciar ni distribuir de otro modo el Material Licenciado (incluidas obras derivadas del mismo) que recuperes a través de la API de X a ninguna persona o entidad fuera de las personas especificadas en tu solicitud aprobada, a menos que (i) la información se divulgue al Coordinador de Servicios Digitales u otra parte permitida específicamente por la DSA conforme al estado y procedimientos de “investigador acreditado” descritos en el Artículo 40, o (ii) la divulgación sea requerida por la ley.
**I. Tokens.** X puede limitar el número de tokens que te proporciona, incluidos, entre otros, los tokens que permiten el acceso y uso de funcionalidades o características en las Aplicaciones de X.
**J. Niveles de Uso Bajo el Acuerdo.** X puede, en cualquier momento, revisar tu uso de sus Materiales Licenciados bajo este Acuerdo, y suspender o terminar tu uso y exigirte que presentes una solicitud de acceso Enterprise (como se describe en [**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction)) para que X considere tu uso continuado propuesto de los Materiales Licenciados.
**K. Prohibición del uso de I-Frames:** Bajo ninguna circunstancia deberás incrustar, mostrar o incorporar de otro modo cualquier Material Licenciado, Contenido de X, API de X o elementos de las Aplicaciones de X dentro de un iframe, inline frame o cualquier mecanismo de incrustación similar en tus Servicios o cualquier otra plataforma. Esta prohibición es absoluta e incluye, entre otras cosas, los intentos de frame de Contenido de X con fines de visualización, integración o redistribución. La violación de esta cláusula puede resultar en la terminación inmediata de tu Acuerdo del Desarrollador y tu acceso al Material Licenciado (por ejemplo, la API de X, la Licencia de Datos de X, la Consola de Desarrollador), como se describe en la Sección VII.I.
**L. Uso Autoservicio (Self-Serve).** Los planes Pay-Per-Use, Basic y Pro (como se describe en [developer.x.com](https://developer.x.com)) están diseñados para aficionados, prototipos comerciales, desarrollo inicial, integraciones tempranas de productos X y aplicaciones de soporte con un número limitado de usuarios finales. Si utilizas la API de X más allá de este alcance, entonces debes solicitar (o ya estar suscrito) un plan Enterprise (como se describe en [developer.x.com](https://developer.x.com)).
**M. Uso Comercial:** Si utilizas la API de X más allá del alcance de proyectos de aficionados, prototipos comerciales, desarrollo inicial, integraciones tempranas de productos X, o para aplicaciones con un número limitado de usuarios finales, entonces debes solicitar (o ya estar suscrito) un plan Enterprise (como se describe en developer.x.com).
**IV. Actualizaciones y Eliminaciones.**
**A. Actualizaciones.** X puede actualizar, modificar o discontinuar cualquier característica o función del Material Licenciado, total o parcialmente, de vez en cuando (en cada caso, una “Actualización”). Implementarás y utilizarás la versión más actual del Material Licenciado y realizarás cualquier cambio en tus Servicios que sea requerido como resultado de la Actualización, a tu único costo. Las Actualizaciones pueden afectar adversamente la forma en que tus Servicios acceden o se comunican con la API de X o muestran el Contenido de X. X no será responsable de ningún tipo de daño resultante de cualquier Actualización.
**B. Eliminaciones.** Si el Contenido de X se elimina, obtiene estado protegido o es suspendido, retenido, modificado o eliminado de las Aplicaciones de X (incluida la eliminación de la información de ubicación), harás todos los esfuerzos razonables para eliminar o modificar ese Contenido de X (según corresponda) tan pronto como sea posible, y en cualquier caso dentro de las veinticuatro (24) horas después de una solicitud por escrito de X o de un usuario de X con respecto a su Contenido de X, salvo que esté prohibido por ley o regulación y con el permiso expreso por escrito de X.
**V. Propiedad, Betas y Comentarios.**
**A. Propiedad.** Excepto en la medida expresamente indicada en este Acuerdo, ninguna de las partes adquirirá ningún derecho, título o interés sobre los Derechos de Propiedad Intelectual propiedad o licenciados por la otra parte. El Material Licenciado se licencia, no se vende, y X (o sus licenciantes o los usuarios de las Aplicaciones de X, según corresponda) retiene y se reserva todos los derechos, incluidos todos los Derechos de Propiedad Intelectual, no otorgados expresamente en este Acuerdo. No harás nada incompatible con la propiedad de X, incluido sin limitación, cuestionar la propiedad de X sobre las Marcas de X, cuestionar la validez de las licencias otorgadas en este Acuerdo, o copiar o explotar de otro modo las Marcas de X excepto según lo específicamente autorizado en este Acuerdo. Si adquieres algún derecho sobre las Marcas de X o cualquier marca confusamente similar, por operación de la ley o de otro modo, deberás, sin costo alguno para X, asignar inmediatamente esos derechos a X.
**B. Betas.** X puede proporcionarte acceso anticipado a alfas, betas, estudios de investigación, pilotos, servicios de marketing u otros programas no generalmente disponibles de vez en cuando (cada uno, una “Beta”). Las Betas se considerarán Información Confidencial. Tu participación en cualquier Beta es a tu propio riesgo, puede estar sujeta a requisitos adicionales, y puede ayudar a X en la investigación, el análisis y la validación de programas, productos y/o herramientas existentes o potenciales.
**C. Comentarios.** X será libre de usar cualquier comentario, retroalimentación o sugerencia que le proporciones relacionados con X, el Material Licenciado, las Betas u otros productos o servicios de X (“Comentarios”) de cualquier manera sin compensación u obligación alguna hacia ti o cualquier tercero, y los Comentarios se considerarán Información Confidencial. Por la presente asignas irrevocablemente a X todo derecho, título e interés sobre los Comentarios.
**VI. Confidencialidad.**
Puedes tener acceso a información, software y especificaciones no públicas relacionadas con el Material Licenciado (“Información Confidencial”). Solo puedes usar la Información Confidencial según sea necesario para ejercer tus derechos bajo este Acuerdo. No deberás divulgar Información Confidencial a ningún tercero sin el consentimiento previo por escrito de X. Protegerás la Información Confidencial del uso, acceso o divulgación no autorizados de la misma manera que utilizarías para proteger tu propia información confidencial de naturaleza similar y en ningún caso con menos de un grado razonable de cuidado.
**VII. Plazo; Términos de Compra de Créditos; Deducción de Créditos; Suspensión y Terminación.**
**A. Plazo.** El plazo de este Acuerdo comenzará en la fecha en que (i) aceptes los términos aquí incluidos o (ii) comiences a acceder o usar cualquier Material Licenciado, lo que ocurra primero, y continuará hasta que dejes de acceder y usar el Material Licenciado, salvo que se termine antes según se describe a continuación.
**B. Términos de Compra de Créditos.** Los Servicios de Pago proporcionados como parte del Material Licenciado se ponen a disposición mediante la compra de Créditos que se deducen en función de tu uso de características, beneficios o servicios, incluido el uso de la API de X, según se describe en [https://developer.x.com/#pricing](https://developer.x.com/#pricing), el Sitio para Desarrolladores y el Portal de Pago. Si compras un Servicio de Pago, lo haces primero comprando Créditos por adelantado, pagando la tarifa aplicable por adelantado a través del Portal de Pago. Tu saldo de créditos se actualizará tras la compra y se deducirá a medida que uses los Servicios de Pago. Debes comprar créditos adicionales según sea necesario para permitir el acceso a los Servicios de Pago. Las compras de créditos no son recurrentes a menos que habilites las funciones opcionales de “Recarga Automática” detalladas en la Sección VII.D. Cuando compras créditos a través del Portal de Pago, aceptas expresamente los términos aquí incluidos y autorizas el cargo. X puede proporcionar notificaciones sobre saldos bajos. Los precios de los créditos y las tasas de deducción están sujetos a cambios de vez en cuando, según lo establecido en el Programa de Precios. X proporcionará un aviso previo razonable de cualquier cambio material en los precios, aviso que puede darse a través del Sitio para Desarrolladores o del Portal de Pago. Los cambios de precio se aplicarán a compras y deducciones futuras. Si no estás de acuerdo con un cambio de precio, puedes dejar de comprar créditos y de usar los Servicios de Pago. Los créditos no caducan a menos que se especifique lo contrario, y no son transferibles ni reembolsables salvo que la ley lo exija.
**C. Deducción de Créditos:** El acceso a los Servicios de Pago requiere créditos suficientes en tu cuenta. Cada llamada o solicitud a la API o uso de otra característica o servicio especificado en el Programa de Precios deducirá créditos de tu saldo según las tasas especificadas en el Programa de Precios. Las tasas de deducción pueden variar, y el Programa de Precios está sujeto a cambios. X pretende deducir créditos en el momento de cada llamada, solicitud o uso de otra característica o servicio especificado en el Programa de Precios, y denegar los Servicios de Pago para los que tengas un saldo insuficiente. En ese caso, deberás comprar créditos adicionales para habilitar el Servicio de Pago. No puedes mantener un saldo de créditos negativo. Es tu responsabilidad supervisar tu saldo de créditos para ayudar a mantener el acceso a los Servicios de Pago.
**D. Disputas de Uso**: Si crees que ha habido un error en las deducciones de créditos, debes notificarlo a X dentro de los treinta (30) días siguientes a la deducción en disputa a través del [soporte de facturación](https://docs.x.com/forms/billing-support). X investigará y, si se confirma un error, ajustará tu saldo de créditos en consecuencia. Los ajustes quedan a la entera discreción de X y están sujetos a este Acuerdo.
**E. Términos de Pago.** X puede ofrecer opciones de pago que varían según el Servicio de Pago, el dispositivo, el sistema operativo, la ubicación geográfica u otros factores, que pueden actualizarse de vez en cuando. Estas opciones de pago pueden incluir pagos web utilizando un procesador de pagos de terceros (“Procesador de Pagos”). Cuando accedes a un Servicio de Pago, aceptas: (i) pagar el precio indicado por los Créditos, junto con cualquier cantidad adicional relativa a impuestos aplicables, recargos, comisiones de tarjeta de crédito, comisiones bancarias, comisiones por transacciones en el extranjero, comisiones por cambio de divisas y fluctuaciones cambiarias; y (ii) cumplir con cualquier término de servicio, política de privacidad u otros acuerdos legales o restricciones aplicables (incluidas las restricciones de edad adicionales) impuestas por el Procesador de Pagos en relación con tu uso de un método de pago determinado. La tarifa se cobrará en el momento de la compra de Créditos. Es tu responsabilidad supervisar tu saldo de Créditos y asegurarte de que tu información bancaria, de tarjeta de crédito, de tarjeta de débito y/o de otra información de pago esté actualizada, completa y sea precisa en todo momento. Si realizas un pago por un Servicio de Pago a través de un Procesador de Pagos, X puede recibir información sobre tu transacción, como cuándo se realizó, en qué plataforma realizaste la compra y otra información. X no será responsable de errores cometidos o retrasos causados por el Procesador de Pagos, tu banco, tu compañía de tarjeta de crédito o cualquier red de pagos. Todos los pagos a X son no reembolsables excepto según se disponga expresamente lo contrario en este Acuerdo o según lo requiera la ley.
**F. Función Opcional de Recarga Automática.** Puedes optar por una función de “recarga automática” a través de la Consola de Desarrollador, autorizando a X a cobrar automáticamente a tu método de pago guardado una cantidad seleccionada por el usuario cuando tu saldo de créditos caiga por debajo del umbral establecido en la herramienta de recarga automática, con cargos que incluyen los impuestos y tarifas aplicables para esa cantidad según la Sección VII.E; puedes modificar o deshabilitar esta función en cualquier momento a través del Portal de Pago, y al habilitarla, das tu consentimiento a X, a través de su Procesador de Pagos externo, para cobrar la cantidad seleccionada cada vez que se alcance el umbral, aunque los cargos fallidos (por ejemplo, debido a un método de pago no válido) impedirán las adiciones de créditos. Habilitar la recarga automática no garantiza el acceso ininterrumpido a los Servicios de Pago. Sigues siendo responsable de supervisar tu saldo de créditos, independientemente de las notificaciones que X pueda proporcionar por saldos bajos o eventos de recarga automática, y los cargos por recarga automática no son reembolsables salvo que la ley lo exija.
**D. Impuestos y tarifas.** Todas las tarifas excluyen todo tipo de impuestos y tarifas similares en vigor, promulgados o impuestos en el futuro sobre la transacción, la entrega del Material Licenciado o la entrega del Contenido de X, incluidos cualquier impuesto sobre ventas, uso o valor añadido, impuesto sobre bienes y servicios, impuesto al consumo, derechos aduaneros, aranceles o cargos similares. Estos impuestos pueden incluir, entre otros, IVA, GST, impuesto sobre las ventas, retención en la fuente y cualquier otro impuesto aplicable, pero excluyen los impuestos basados únicamente en la renta neta de X. Eres responsable del pago de todos esos impuestos, derechos y cargos, así como de cualquier sanción e interés relacionados que surja del pago de tales cantidades. Además, se puede cobrar un recargo para recuperar los costos asociados con el Impuesto sobre Servicios Digitales ("DST") o impuestos similares específicos de la jurisdicción o tarifas regulatorias incurridas por X en determinadas jurisdicciones. Este recargo aparecerá como una partida separada en tu factura, cuando corresponda, y se calculará como un porcentaje de los cargos aplicables determinados por X a su entera discreción. X puede ajustar este recargo en cualquier momento, sin previo aviso, en respuesta a aumentos en las tasas fiscales o de tarifas o los costos administrativos relacionados. Dependiendo de tu ubicación, X puede ser responsable de recopilar y reportar información relacionada con los impuestos sobre transacciones que surjan de tu compra de Servicios de Pago. Otorgas a X permiso para proporcionar tu información de cuenta y personal a las autoridades fiscales pertinentes para cumplir con nuestras obligaciones de recaudación y reporte fiscal.
**E. Reembolsos y Cese de los Servicios de Pago.** Puedes dejar de utilizar los Servicios de Pago en cualquier momento no haciendo más llamadas a la API. Los créditos no utilizados no son reembolsables ni transferibles, sin reembolsos por créditos comprados o utilizados, salvo que la ley lo exija. LAS COMPRAS DE CRÉDITOS SON PREPAGADAS, NO REEMBOLSABLES (SALVO QUE LA LEY LO EXIJA). Solo puedes solicitar el reembolso de los créditos no utilizados de acuerdo con la ley aplicable (por ejemplo, los derechos de desistimiento indicados a continuación). Todas las transacciones son finales a menos que tengas derecho a desistir conforme a la ley, como se establece a continuación.
**1. Derecho de Desistimiento y Reembolsos para Usuarios que Vivan en la UE o el Reino Unido.** Tienes el derecho legal de desistir de tu compra de créditos sin dar ningún motivo dentro de los 14 días siguientes a la fecha de compra (“Plazo de Desistimiento”). Para ejercer este derecho, debes informar a X de tu decisión de desistir antes de que expire el Plazo de Desistimiento presentando una declaración clara de desistimiento al [soporte de facturación](https://docs.x.com/forms/billing-support). Si desistes dentro del Plazo de Desistimiento y no has utilizado ningún crédito, X reembolsará la cantidad total pagada por la compra de créditos, incluidos los impuestos o tarifas aplicables, dentro de los catorce (14) días siguientes a la recepción de tu aviso de desistimiento, utilizando el mismo método de pago utilizado para la compra, salvo que acuerdes expresamente lo contrario.
Sin embargo, reconoces y aceptas expresamente que si utilizas cualquier crédito durante el Plazo de Desistimiento (por ejemplo, realizando llamadas o solicitudes a la API), renuncias a tu derecho de desistimiento, ya que los Servicios de Pago habrán comenzado con tu consentimiento expreso previo y reconocimiento de que tu derecho de desistimiento se pierde con dicho uso. Si utilizas solo una parte de tus créditos comprados durante el Plazo de Desistimiento y luego ejerces tu derecho de desistimiento, X reembolsará la cantidad correspondiente a los créditos no utilizados, calculada según el Programa de Precios disponible en [https://developer.x.com/#pricing](https://developer.x.com/#pricing).
**2. Sin Derecho de Desistimiento para Usuarios que Vivan en Taiwán.** Si eres un consumidor residente en Taiwán, puedes tener derecho a un plazo de desistimiento de siete (7) días para las compras de créditos conforme a la Ley de Protección al Consumidor, salvo que hayas utilizado cualquier crédito, en cuyo caso el derecho de desistimiento se pierde. Para ejercer este derecho, debes notificarlo a X dentro de los siete (7) días siguientes a la fecha de compra en [soporte de facturación](https://docs.x.com/forms/billing-support). Los reembolsos por créditos no utilizados se procesarán de acuerdo con la ley aplicable.
**F. Los Créditos No Son Transferibles entre Cuentas de X.** Cada compra de Créditos se aplica a una única cuenta de X, lo que significa que tu compra se aplicará únicamente a la cuenta que estabas utilizando cuando compraste los Créditos y no se aplicará a otras cuentas a las que puedas tener acceso o control. Si tienes o controlas varias cuentas y deseas acceder a los Servicios de Pago en cada cuenta, debes comprar los Créditos necesarios en cada cuenta individualmente. No puedes permitir que otros usen tu cuenta de X para acceder a cualquier Material Licenciado que dicha persona no haya ordenado. No puedes comprar Créditos ni utilizar ningún Material Licenciado si eres una persona con la que las personas de EE. UU. no pueden tener tratos conforme a sanciones económicas, incluidas, entre otras, las sanciones administradas por la Oficina de Control de Activos Extranjeros del Departamento del Tesoro de los Estados Unidos o cualquier otra autoridad de sanciones aplicable ("Persona Prohibida"). Esto incluye, entre otras, personas ubicadas en, ciudadanas de o residentes habituales en los siguientes países y regiones: Cuba, Irán, la Región de Crimea de Ucrania, Corea del Norte y Siria. Declaras y garantizas que no eres una Persona Prohibida.
**G. Restricciones y Obligaciones.** Solo puedes comprar y utilizar Créditos y utilizar el Material Licenciado si tienes permitido legalmente utilizar el Material Licenciado en tu país y vives en un país compatible con X para la compra de Créditos, Servicio de Pago o Material Licenciado aplicable. X puede, a su discreción, restringir la capacidad de acceder al Material Licenciado o comprar Créditos en determinados países. X se reserva el derecho de modificar la lista de países admitidos de vez en cuando. X se reserva el derecho de rechazar la venta de Créditos o el acceso a los Servicios de Pago, o de cancelar o discontinuar la venta o uso de un Servicio de Pago o el uso de cualquier Material Licenciado a su entera discreción.
**H. Suspensión.** X puede suspender tu uso y acceso al Material Licenciado inmediatamente sin previo aviso (a) si X cree razonablemente que (i) tu uso del Material Licenciado causaría daños o una carga desmesurada sobre el Material Licenciado, (ii) has violado este Acuerdo, (iii) generas riesgo o posible exposición legal para X, (iv) la prestación del Material Licenciado por parte de X a ti ya no es comercialmente viable; (b) por inactividad prolongada; (c) si X es solicitado o instruido para hacerlo por cualquier tribunal competente, autoridad reguladora o agencia de aplicación de la ley; o (d) por incumplimiento del pago de los Servicios de Pago. X no será responsable por daños de ningún tipo resultantes de dicha suspensión.
**I. Terminación.** X puede terminar este Acuerdo por cualquier motivo a su entera discreción. Dicha terminación anticipada por parte de X será efectiva inmediatamente. Si violas los términos de este Acuerdo, X puede terminar este Acuerdo por causa inmediatamente tras notificarte y no recibirás un reembolso por ningún Crédito. Puedes cancelar tu acceso a los Servicios de Pago o tu uso del Material Licenciado en el Sitio para Desarrolladores. No tendrás derecho a un reembolso de ningún Crédito, ni tendrás derecho al uso de cualquier Crédito no utilizado. Al terminar este Acuerdo: (a) todas las licencias otorgadas en este Acuerdo expiran inmediatamente y debes cesar el uso de cualquier Material Licenciado; y (b) deberás eliminar permanentemente todo el Material Licenciado en todas las formas y tipos de medios, y las copias del mismo, en tu posesión. A petición de X por cualquier motivo, proporcionarás con prontitud (y en cualquier caso dentro de los diez (10) días hábiles a partir de dicha solicitud) evidencia (por ejemplo, capturas de pantalla de la confirmación de eliminación) del cumplimiento de las disposiciones del subapartado (b) mencionado en esta Sección. Las partes de este Acuerdo no serán responsables entre sí de ningún daño resultante únicamente de la terminación de este Acuerdo según lo permitido en este Acuerdo.
**VIII. Auditoría de Cumplimiento.**
X o un agente tercero mutuamente acordado sujeto a obligaciones de confidencialidad tendrá derecho a inspeccionar y auditar cualquier registro relacionado con la ejecución de este Acuerdo bajo tu control o posesión previo aviso razonable, y en un momento razonable durante el horario comercial normal, con el fin de verificar el cumplimiento de este Acuerdo y las tarifas pagaderas a X para el período de dos (2) años anterior a la auditoría. X puede ejercer su derecho de auditoría no más de una vez cada doce (12) meses a menos que tenga causa razonable de incumplimiento, y dicha auditoría no interferirá irrazonablemente con tus actividades comerciales. Prestarás plena cooperación y asistencia con dicha auditoría y proporcionarás acceso a todo el Material Licenciado en tu posesión, los acuerdos aplicables y los registros. Sin limitar la generalidad de lo anterior, como parte de la auditoría, X puede solicitar, y aceptas proporcionar, un informe escrito, firmado por un representante autorizado, que enumere tu despliegue actual del Material Licenciado. Pagarás a X dentro de los treinta (30) días hábiles siguientes a la finalización de la auditoría el monto de cualquier pago insuficiente revelado por dicha auditoría. Además, si dicha auditoría revela un pago insuficiente por tu parte del cinco por ciento (5%) o más, también reembolsarás a X los costos y gastos razonables de dicha auditoría. Los requisitos de esta Sección sobrevivirán durante un (1) año después de la terminación de este Acuerdo.
**IX. Descargo de Responsabilidad.**
EN LA MÁXIMA MEDIDA PERMITIDA POR LA LEY APLICABLE, EL MATERIAL LICENCIADO SE TE PROPORCIONA "TAL CUAL", "EN EL LUGAR DONDE ESTÁ", CON TODOS LOS DEFECTOS, Y X RENUNCIA A TODAS LAS GARANTÍAS, YA SEAN EXPRESAS, IMPLÍCITAS, ESTATUTARIAS O DE OTRO TIPO, INCLUIDAS, SIN LIMITACIÓN, LAS GARANTÍAS DE COMERCIABILIDAD, NO INFRACCIÓN, IDONEIDAD PARA UN PROPÓSITO PARTICULAR, Y CUALESQUIERA GARANTÍAS O CONDICIONES QUE SURJAN DE ESTE ACUERDO, DEL CURSO DE LOS NEGOCIOS O DE LOS USOS DEL COMERCIO. X NO GARANTIZA QUE EL MATERIAL LICENCIADO O CUALQUIER OTRO PRODUCTO O SERVICIO DE X PROPORCIONADO EN VIRTUD DEL PRESENTE CUMPLIRÁ CON ALGUNO DE TUS REQUISITOS O QUE EL USO DE DICHO MATERIAL LICENCIADO U OTROS PRODUCTOS O SERVICIOS ESTARÁ LIBRE DE ERRORES, ININTERRUMPIDO, LIBRE DE VIRUS O SEGURO. ERES RESPONSABLE DE TU USO DEL MATERIAL LICENCIADO Y DE CUALQUIER CONTENIDO QUE PROPORCIONES. ESTE DESCARGO DE GARANTÍAS PUEDE NO SER VÁLIDO EN ALGUNAS JURISDICCIONES Y PUEDES TENER DERECHOS DE GARANTÍA CONFORME A LA LEY QUE NO PUEDEN RENUNCIARSE NI DESCARGARSE.
**ADEMÁS, ENTIENDES Y ACEPTAS QUE LOS SERVICIOS DE PAGO SE TE PROPORCIONAN SOBRE UNA BASE "TAL CUAL" Y "SEGÚN DISPONIBILIDAD".**
**X. Indemnización.**
Deberás defender a X contra cualquier procedimiento, demanda, reclamación y acción judicial (incluidas, sin limitación, reclamaciones por responsabilidad de producto) e indemnizar a X de todas las responsabilidades, daños y costos (incluidos, sin limitación, los honorarios razonables de abogados) en la medida en que surjan de (a) tu uso del Material Licenciado de cualquier manera incompatible con este Acuerdo o (b) el desempeño, la promoción, la venta o distribución de tus Servicios. Si X busca indemnización o defensa por tu parte bajo esta Sección, X te notificará con prontitud por escrito de las reclamaciones presentadas contra X para las que solicita indemnización o defensa. X puede asumir el control total de la defensa de las reclamaciones con asesores legales de su elección. No celebrarás ningún acuerdo con terceros que afecte los derechos de X, constituya una admisión de culpa por parte de X, o vincule a X de alguna manera sin el consentimiento previo por escrito de X. Si X asume el control de la defensa de dicha reclamación, X no llegará a un acuerdo respecto de cualquier reclamación que requiera pago por tu parte sin tu aprobación previa por escrito.
**XI. Limitación de Responsabilidad.**
EN NINGÚN CASO X SERÁ RESPONSABLE ANTE TI O CUALQUIER USUARIO POR DAÑOS INDIRECTOS, ESPECIALES, INCIDENTALES, EJEMPLARES, PUNITIVOS O CONSECUENCIALES, NI POR PÉRDIDA DE USO, DATOS, NEGOCIO, BUENA VOLUNTAD (GOODWILL) O BENEFICIOS QUE SURJAN DE O EN RELACIÓN CON ESTE ACUERDO. EN CUALQUIER CASO, LA RESPONSABILIDAD AGREGADA DE X POR TODAS Y CADA UNA DE LAS RECLAMACIONES BAJO ESTE ACUERDO NO SUPERARÁ LOS CINCUENTA DÓLARES (\$50.00). LAS LIMITACIONES, EXCLUSIONES Y DESCARGOS ANTERIORES SE APLICARÁN INDEPENDIENTEMENTE DE QUE DICHA RESPONSABILIDAD SURJA DE CUALQUIER RECLAMACIÓN BASADA EN CONTRATO, GARANTÍA, RESPONSABILIDAD EXTRACONTRACTUAL, RESPONSABILIDAD ESTRICTA O DE OTRO MODO, Y CON INDEPENDENCIA DE QUE X HAYA SIDO INFORMADO O NO DE LA POSIBILIDAD DE DICHA PÉRDIDA O DAÑO. SI LA LEY APLICABLE PROHÍBE ALGUNA LIMITACIÓN DE RESPONSABILIDAD AQUÍ ESTABLECIDA, LAS PARTES ACUERDAN QUE LA LIMITACIÓN SE ENTENDERÁ MODIFICADA PARA AJUSTARSE A LA LEY APLICABLE. LAS PARTES ACUERDAN QUE LAS LIMITACIONES DE RESPONSABILIDAD AQUÍ ESTABLECIDAS SON ASIGNACIONES DE RIESGO ACORDADAS Y DICHAS LIMITACIONES SE APLICARÁN NO OBSTANTE EL FALLO DEL PROPÓSITO ESENCIAL DE CUALQUIER RECURSO LIMITADO.
**XII. Actualizaciones del Acuerdo.**
X puede actualizar o modificar este Acuerdo o cualquiera de los Términos para Desarrolladores Incorporados de vez en cuando. Deberás consultar regularmente el Sitio para Desarrolladores para conocer las actualizaciones. X te alertará de revisiones materiales a estos términos publicando los términos actualizados en estos sitios, mediante una notificación de servicio o por otros medios adecuados (por ejemplo, por correo electrónico a una dirección de correo asociada con tu cuenta). Los cambios no serán retroactivos y la versión más actual de este Acuerdo, disponible en el Sitio para Desarrolladores, regirá tu acceso y uso del Material Licenciado y cualquier transacción correspondiente. Tu acceso o uso continuado del Material Licenciado constituirá la aceptación vinculante de dichas actualizaciones y modificaciones.
**XIII. Resolución de Disputas y Renuncia a la Acción Colectiva.**
**A. ESTA SECCIÓN SE APLICA A TI SOLO SI VIVES FUERA DE LA UNIÓN EUROPEA, LOS ESTADOS DE LA AELC (EFTA) O EL REINO UNIDO, INCLUYENDO SI VIVES EN LOS ESTADOS UNIDOS. LEE ESTA SECCIÓN CUIDADOSAMENTE — PUEDE AFECTAR SIGNIFICATIVAMENTE TUS DERECHOS LEGALES, INCLUIDO TU DERECHO A PRESENTAR UNA DEMANDA EN UN TRIBUNAL.**
**1. Elección de Ley y Selección de Foro.** Las leyes del Estado de Texas, excluyendo sus disposiciones sobre elección de ley, regirán este Acuerdo y cualquier disputa que surja entre tú y X, no obstante cualquier otro acuerdo entre las partes en contrario. Todas las disputas relacionadas con este Acuerdo, incluidas cualesquiera disputas, reclamaciones o controversias que surjan de o se relacionen con este Acuerdo, la comercialización del Material Licenciado y/o tu participación en el Material Licenciado, se someterán exclusivamente al Tribunal de Distrito de los Estados Unidos para el Distrito Norte de Texas o a los tribunales estatales ubicados en el Condado de Tarrant, Texas, Estados Unidos, y consientes la jurisdicción personal en dichos foros y renuncias a cualquier objeción en cuanto al foro inconveniente. Sin perjuicio de lo anterior, aceptas que, a su entera discreción, X pueda presentar cualquier reclamación, causa de acción o disputa que tenga contra ti en cualquier tribunal competente del país en el que residas que tenga jurisdicción y competencia sobre la reclamación.
Si eres una entidad gubernamental federal, estatal o local en los Estados Unidos que utiliza el Material Licenciado en su capacidad oficial y legalmente no puede aceptar las cláusulas de ley aplicable, jurisdicción o sede antes mencionadas, entonces esas cláusulas no se te aplican. Para tales entidades gubernamentales federales de EE. UU., este Acuerdo y cualquier acción relacionada se regirán por las leyes de los Estados Unidos de América (sin referencia a conflicto de leyes) y, en ausencia de ley federal y en la medida permitida bajo la ley federal, por las leyes del Estado de Texas (excluyendo la elección de ley).
**2. TIENES UN AÑO PARA PRESENTAR UNA RECLAMACIÓN CONTRA X.** Debes presentar cualquier reclamación contra X que surja de o se relacione con este Acuerdo dentro de un (1) año después de la fecha de ocurrencia del evento o los hechos que dieron origen a la disputa, salvo que la ley aplicable disponga que el plazo normal de prescripción para esa reclamación no puede reducirse por acuerdo. Si no presentas una reclamación dentro de este período, renuncias para siempre al derecho de perseguir cualquier reclamación o causa de acción, de cualquier tipo o carácter, basada en tales eventos o hechos, y dichas reclamaciones o causas de acción quedan prohibidas permanentemente y X no tendrá ninguna responsabilidad respecto de dicha reclamación.
**3. Renuncia a la Acción Colectiva.** En la medida permitida por la ley, también renuncias al derecho de participar como demandante o miembro de la clase en cualquier supuesto procedimiento de acción de clase, acción colectiva o acción representativa.
**4. Cambios a esta Sección.** Esta Sección de Resolución de Disputas sobrevive al final de la relación entre tú y X, incluida la cancelación o cancelación de la suscripción a cualquier servicio o comunicación proporcionada por X.
**5. Medidas Cautelares.** No obstante lo anterior, aceptas que los daños monetarios serían un recurso inadecuado para X en caso de una violación o amenaza de violación de este Acuerdo que proteja la propiedad intelectual de X o la Información Confidencial, y que en caso de tal violación o amenaza, X, además de cualquier otro recurso al que tenga derecho, tiene derecho a medidas cautelares o preliminares (incluida una orden que te prohíba realizar acciones en violación de tales disposiciones), sin la necesidad de constituir fianza, y a la ejecución específica según sea apropiado. Las partes acuerdan que ni la Convención de las Naciones Unidas sobre los Contratos de Compraventa Internacional de Mercaderías ni la Uniform Computer Information Transaction Act se aplicarán a este Acuerdo, independientemente de los estados en los que las partes hagan negocios o estén incorporadas. Ninguna renuncia por parte de X a cualquier pacto o derecho bajo este Acuerdo será efectiva a menos que se plasme en un escrito autorizado por X.
**B. ESTA SECCIÓN SE APLICA A TI SOLO SI VIVES EN LA UNIÓN EUROPEA, LOS ESTADOS DE LA AELC (EFTA) O EL REINO UNIDO. LEE ESTA SECCIÓN CUIDADOSAMENTE — PUEDE AFECTAR SIGNIFICATIVAMENTE TUS DERECHOS LEGALES, INCLUIDO TU DERECHO A PRESENTAR UNA DEMANDA EN UN TRIBUNAL.**
**1. Elección de Ley y Selección de Foro.** En la medida permitida por la ley, todas las disputas relacionadas con este Acuerdo, incluidas cualesquiera disputas, reclamaciones o controversias que surjan de o se relacionen con este Acuerdo, la comercialización del Material Licenciado y/o tu participación en el Material Licenciado, se presentarán exclusivamente ante un tribunal competente en Irlanda, sin tener en cuenta las disposiciones sobre conflicto de leyes, y se regirán por la ley irlandesa, no obstante cualquier acuerdo entre las partes en contrario. Sin perjuicio de lo anterior, aceptas que, a su entera discreción, X pueda presentar cualquier reclamación, causa de acción o disputa que tenga contra ti en cualquier tribunal competente del país en el que residas que tenga jurisdicción y competencia sobre la reclamación.
**2. TIENES UN AÑO PARA PRESENTAR UNA RECLAMACIÓN CONTRA X.** Debes presentar cualquier reclamación contra X que surja de o se relacione con este Acuerdo dentro de un (1) año después de la fecha de ocurrencia del evento o los hechos que dieron origen a la disputa, salvo que la ley aplicable disponga que el plazo normal de prescripción para esa reclamación no puede reducirse por acuerdo. Si no presentas una reclamación dentro de este período, renuncias para siempre al derecho de perseguir cualquier reclamación o causa de acción, de cualquier tipo o carácter, basada en tales eventos o hechos, y dichas reclamaciones o causas de acción quedan prohibidas permanentemente, y X no tendrá ninguna responsabilidad respecto de dicha reclamación.
**3. Renuncia a la Acción Colectiva.** En la medida permitida por la ley, también renuncias al derecho de participar como demandante o miembro de la clase en cualquier supuesto procedimiento de acción de clase, acción colectiva o acción representativa.
**4. Cambios a esta Sección.** Esta sección de Resolución de Disputas sobrevive al final de la relación entre tú y X, incluida la cancelación o cancelación de la suscripción a cualquier servicio o comunicación proporcionada por X.
**5. Medidas Cautelares.** No obstante lo anterior, aceptas que los daños monetarios serían un recurso inadecuado para X en caso de una violación o amenaza de violación de este Acuerdo que proteja la propiedad intelectual de X o la Información Confidencial, y que en caso de tal violación o amenaza, X, además de cualquier otro recurso al que tenga derecho (incluidos daños monetarios), tiene derecho a tales medidas cautelares preliminares o de inhibición (incluida una orden que te prohíba realizar acciones en violación de tales disposiciones), sin la necesidad de constituir fianza, y a la ejecución específica según sea apropiado. Las partes acuerdan que ni la Convención de las Naciones Unidas sobre los Contratos de Compraventa Internacional de Mercaderías ni la Uniform Computer Information Transaction Act se aplicarán a este Acuerdo, independientemente de los estados en los que las partes hagan negocios o estén incorporadas. Ninguna renuncia por parte de X a cualquier pacto o derecho bajo este Acuerdo será efectiva a menos que se plasme en un escrito autorizado por X.
**XIV. Varios.**
**A. Cesión.** No cederás ninguno de los derechos u obligaciones otorgados en virtud del presente, total o parcialmente, ya sea voluntariamente o por operación de la ley, contrato, fusión (ya seas la entidad superviviente o la absorbida), venta de acciones o activos, consolidación, disolución, por acción gubernamental, o de otro modo, excepto con el consentimiento previo por escrito de X. X está autorizado a firmar modificaciones y consentimientos para X Internet Unlimited Company, una empresa irlandesa responsable de la información de los usuarios de X que viven fuera de los Estados Unidos. Cualquier intento de cesión en violación de esta Sección será nulo y sin efecto, y X podrá terminar este Acuerdo.
**B. Protección del Usuario.** A menos que sea explícitamente aprobado por X por escrito, no deberás usar, ni mostrar, distribuir o poner a disposición a sabiendas Contenido de X, o información derivada del Contenido de X, con el propósito de: (a) realizar o proporcionar vigilancia o recopilación de inteligencia, incluida, entre otras cosas, la investigación o el seguimiento de usuarios de X o Contenido de X; (b) realizar o proporcionar análisis o investigación para cualquier propósito ilegal o discriminatorio o de una manera que sea incompatible con las expectativas razonables de privacidad de los usuarios de X; (c) monitorear eventos sensibles (incluidos, entre otros, protestas, mítines o reuniones de organización comunitaria); o (d) dirigirse a, segmentar o perfilar a individuos en función de información personal sensible, incluida su salud (por ejemplo, el embarazo), situación o condición financiera negativa, afiliación o creencias políticas, origen racial o étnico, afiliación o creencias religiosas o filosóficas, vida sexual u orientación sexual, afiliación sindical, Contenido de X relacionado con la comisión presunta o real de un delito, o cualquier otra categoría sensible de información personal prohibida por la ley.
**C. Uso Gubernamental.** Si muestras, distribuyes o pones a disposición de otro modo cualquier Contenido de X a Usuarios que sean, o que actúen en nombre de, cualquier entidad relacionada con el gobierno (cada uno, un “**Usuario Final Gubernamental**”); (a) debes solicitar (o ya estar suscrito) un plan Enterprise (como se describe en [**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction)); (b) deberás identificar a todos esos Usuarios Finales Gubernamentales al enviar tu caso de uso para revisión a X; y (c) deberás notificar posteriormente a X por escrito sobre cualquier nuevo Usuario Final Gubernamental o cualquier nuevo caso de uso con Usuarios Finales Gubernamentales existentes antes de que los Servicios muestren, distribuyan o pongan a disposición de otro modo cualquier Contenido de X a un Usuario Final Gubernamental o para cualquier nuevo caso de uso. X puede prohibirte que pongas Contenido de X a disposición de cualquier Usuario Final Gubernamental. No deberás usar, ni mostrar, distribuir o poner a disposición a sabiendas Contenido de X, o información derivada del Contenido de X, a ningún Usuario Final Gubernamental cuya función o misión principal incluya realizar vigilancia o recopilación de inteligencia. Si las fuerzas del orden solicitan información sobre X o sus usuarios con fines de una investigación en curso, puedes remitirlas a las Directrices para las Fuerzas del Orden de X ubicadas en [**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support). La API de X y el Contenido de X son "artículos comerciales" según se define dicho término en 48 C.F.R. 2.101, consistentes en "software informático comercial" y "documentación de software informático comercial" según se utilizan dichos términos en 48 C.F.R. 12.212. Cualquier uso, modificación, derivación, reproducción, publicación, ejecución, exhibición, divulgación o distribución de la API de X o del Contenido de X por parte de cualquier entidad gubernamental está prohibido, salvo lo expresamente permitido por los términos de este Acuerdo. Además, cualquier uso por parte de entidades gubernamentales de EE. UU. debe estar de acuerdo con 48 C.F.R. 12.212 y 48 C.F.R. 227.7202-1 a 227.7202-4. Si utilizas la API de X o el Contenido de X en tu capacidad oficial como empleado o representante de una entidad gubernamental estatal o local de EE. UU. y no puedes aceptar legalmente las cláusulas de indemnización, jurisdicción, sede u otras aquí incluidas, entonces esas cláusulas no se aplican a dicha entidad en la medida requerida por la ley. Contratista/fabricante es X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
**D. Cumplimiento de las Leyes; Exportación e Importación.** Cada parte cumplirá con todas las leyes, reglas y regulaciones extranjeras, federales, estatales y locales aplicables, incluidas, sin limitación, todas las leyes relativas al soborno y/o la corrupción. El Material Licenciado está sujeto a las leyes de exportación de EE. UU. y puede estar sujeto a las leyes de importación y uso del país donde se entrega o utiliza. Deberás cumplir con estas leyes. Bajo estas leyes, el Material Licenciado no puede venderse, arrendarse, descargarse, moverse, exportarse, reexportarse o transferirse a través de fronteras sin una licencia o aprobación de la autoridad gubernamental pertinente, a ningún país o a ningún nacional extranjero restringido por estas leyes, incluidos los países embargados por el Gobierno de EE. UU. (actualmente Cuba, Irán, Corea del Norte, el norte de Sudán y Siria), a ningún usuario final restringido o denegado, incluidas, entre otras, cualquier persona o entidad prohibida por la Oficina de Control de Activos Extranjeros de EE. UU., o para ningún uso final restringido. Mantendrás todos los derechos y licencias que se requieran para tus Servicios.
**E. Adenda de Protección de Datos.** Cada parte cumplirá con la Adenda de Protección de Datos de Controlador a Controlador de X ubicada en [**https://gdpr.x.com/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html), que puede ser actualizada por X de vez en cuando.
**F. Supervivencia.** Las Secciones III (Restricciones de Uso), V (Propiedad y Comentarios), VI (Confidencialidad), VII(I) (Terminación), VIII (Auditoría de Cumplimiento), IX (Descargo de Garantías), X (Indemnización), XI (Limitación de Responsabilidad), XIII (Resolución de Disputas y Renuncia a la Acción Colectiva); y XIV (Varios) de este Acuerdo sobrevivirán a la terminación de este Acuerdo.
**G. Acuerdo Completo.** Este Acuerdo constituye el entendimiento completo de las partes con respecto al objeto de este Acuerdo y sustituye a todos los demás acuerdos entre las partes relacionados con el objeto, ya sean escritos u orales. Si alguna disposición de este Acuerdo es declarada inaplicable por un tribunal, las disposiciones restantes del Acuerdo permanecerán en vigor. Ninguna renuncia bajo este Acuerdo será efectiva a menos que sea por escrito y esté firmada por la parte que otorga la renuncia. Una renuncia otorgada en una ocasión no operará como renuncia en otras ocasiones. Este Acuerdo no crea ni implica ninguna sociedad, agencia o joint venture.
[**POLÍTICA Y TÉRMINOS PARA DESARROLLADORES**](https://docs.x.com/developer-terms)
SIGUE A [**@XDEVELOPERS**](https://x.com/XDevelopers)
[**Suscríbete a las noticias para desarrolladores**](https://developer.x.com/twitterdev-news-subscription)
# Requisitos de visualización: Respuestas
Source: https://docs.x.com/es/developer-terms/reply-requirements
Requisitos de visualización para mostrar respuestas a publicaciones en aplicaciones que utilizan la API de X, incluyendo la estructura de hilos, la atribución y las reglas del contexto de la respuesta.
## Respuesta
Sigue las siguientes directrices para mostrar respuestas.
### Para una respuesta por defecto:
### Para una respuesta con contexto social:
### Para una Cita:
# Usos restringidos de la API de X
Source: https://docs.x.com/es/developer-terms/restricted-use-cases
Detalles sobre casos de uso restringidos para la API de X, incluyendo el seguimiento fuera de la plataforma, la vigilancia gubernamental, el manejo de datos sensibles y las herramientas prohibidas.
El uso de nuestra plataforma para desarrolladores requiere que revises y aceptes nuestro [Acuerdo y Política del Desarrollador](/developer-terms/agreement), así como nuestras políticas relacionadas, incluidos los [Requisitos de visualización](https://docs.x.com/developer-terms/display-requirements) y las [Reglas de automatización](https://help.x.com/en/rules-and-policies/twitter-automation). Entre otras cosas, nuestros acuerdos y políticas proporcionan orientación sobre varios casos de uso restringidos. A continuación, ofrecemos información adicional sobre algunas de estas restricciones.
## Automatización, spam y respuestas automáticas
El uso de las APIs y productos para desarrolladores de X para crear spam, o participar en comportamientos de tipo spam, está prohibido. Debes revisar las [Reglas de X](https://t.co/rules) sobre spam y asegurarte de que tu aplicación no viola nuestras políticas ni permite que los usuarios lo hagan.
Si tu aplicación se utilizará para realizar acciones de escritura en el servicio de X, incluidas la publicación de publicaciones, seguir cuentas o enviar mensajes directos, debes revisar cuidadosamente las [Reglas de automatización](https://support.x.com/articles/76915) para asegurarte de que tu servicio cumpla con nuestras directrices. En particular, debes:
* Obtener siempre el consentimiento explícito del usuario antes de enviarle [respuestas o mensajes automáticos](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444)
* Respetar de inmediato las solicitudes de los usuarios de darse de baja de ser contactados por ti
* No realizar nunca acciones masivas, agresivas o de tipo spam, incluida la [seguidura masiva (bulk following)](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769)
* No publicar nunca contenido idéntico o sustancialmente similar en [múltiples cuentas](https://blog.x.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html)
## Información sensible
Debes tener cuidado al usar los datos de X para derivar o inferir características potencialmente sensibles sobre los usuarios de X. Nunca derives ni infieras, ni almacenes información derivada o inferida sobre lo siguiente de un usuario de X:
* Salud (incluido el embarazo)
* Situación o condición financiera negativa
* Afiliación o creencias políticas
* Origen racial o étnico
* Afiliación o creencias religiosas o filosóficas
* Vida sexual u orientación sexual
* Afiliación sindical
* Comisión presunta o real de un delito
Se permite el análisis agregado de contenido de X que no almacene datos personales (por ejemplo, IDs de usuario, nombres de usuario y otros identificadores), siempre que el análisis también cumpla con las leyes aplicables y con todas las partes del Acuerdo y la Política del Desarrollador.
## Emparejamiento fuera de X (Off-X matching)
El emparejamiento fuera de X implica asociar contenido de X, incluyendo un nombre de usuario o ID de usuario de X, con una persona, hogar, dispositivo, navegador u otro identificador fuera de X. Un ejemplo sería asociar un nombre de usuario de X con los registros de clientes de una empresa (es decir, “John Doe” en tu registro de clientes está emparejado con @johndoe en X).
Queremos que las personas se sientan cómodas de crear una identidad separada y, si así lo eligen, seudónima en X. Si tienes la intención de asociar cualquier información sobre un usuario de X con un identificador fuera de X, requerimos que obtengas el consentimiento expreso y de tipo opt-in del usuario antes de hacer la asociación. Por ejemplo, podrías obtener este consentimiento si el usuario comparte su @handle de X directamente contigo como parte de un proceso de registro en tu servicio.
En situaciones en las que no tienes el consentimiento expreso y de tipo opt-in del usuario para vincular su identidad de X con un identificador fuera de X, requerimos que cualquier conexión que hagas se base únicamente en información que un usuario razonablemente esperaría que se utilizara para ese fin. Si un usuario se sorprendería al saber que estás usando información que él o ella proporcionó para vincular su cuenta de X con una identidad fuera de X, no lo hagas. Además, en ausencia del consentimiento expreso opt-in de la persona, solo puedes intentar emparejar tus registros sobre alguien con una identidad de X en función de:
* **La información proporcionada directamente por el usuario.** Los registros sobre personas con las que no tienes una relación previa, incluidos los datos sobre individuos obtenidos de terceros, no cumplen este estándar; y/o
* **Datos públicos.** “Datos públicos” en este contexto se refiere a:
* Información sobre un usuario que obtuviste de un recurso público y generalmente disponible (como un directorio de miembros de una asociación profesional)
* Información en X sobre un usuario que está disponible públicamente, incluyendo:
* Publicaciones
* Información de perfil, incluida la bio del usuario y la ubicación declarada públicamente
* Nombre para mostrar y nombre de usuario
## Redistribución de contenido de X
Si necesitas compartir contenido de X que obtuviste a través de las APIs de X con otra parte, la mejor manera de hacerlo es compartiendo IDs de publicación, IDs de mensajes directos y/o IDs de usuario, que el usuario final del contenido puede luego rehidratar (es decir, solicitar el contenido completo de la publicación, usuario o mensaje directo) utilizando las APIs de X. Esto ayuda a garantizar que los usuarios finales del contenido de X siempre obtengan la información más actualizada directamente de nosotros.
Permitimos una redistribución limitada de contenido de X hidratado por medios no automatizados. Si eliges compartir contenido de X hidratado con otra parte de esta manera, solo puedes compartir hasta 50.000 objetos de publicación pública y/u objetos de usuario hidratados por destinatario, por día, y no deberías hacer que estos datos estén disponibles públicamente (por ejemplo, como archivo adjunto de una entrada de blog o en un repositorio público de GitHub).
Hay algunos otros puntos que deben tenerse en cuenta al redistribuir contenido de X:
* Solo puedes distribuir un total de hasta 1.500.000 IDs de publicación a una sola entidad dentro de un período de 30 días a menos que hayas recibido previamente permiso expreso por escrito de X.
* Las personas que redistribuyan IDs de publicación y/o IDs de usuario en nombre de una institución académica con el único propósito de investigación no comercial pueden redistribuir un número ilimitado de IDs de publicación y/o IDs de usuario.
* Para solicitar permiso para compartir contenido de X como se describe arriba, utiliza el formulario de soporte de Política de la API.
En la medida en que se te permita distribuir contenido de X a un tercero, ten en cuenta que dicho contenido sigue estando sujeto al Acuerdo y a la Política del Desarrollador, y esos terceros deben aceptar los [Términos de Servicio](https://x.com/en/tos), la [Política de Privacidad](https://x.com/en/privacy), el [Acuerdo del Desarrollador](/developer-terms/agreement) y la [Política del Desarrollador](/developer-terms/policy) de X antes de recibir el contenido de X.
## Múltiples aplicaciones
No se te permite registrar múltiples aplicaciones para un solo caso de uso, o casos de uso sustancialmente similares o superpuestos. Obtén más información sobre estas políticas [aquí](https://twittercommunity.com/t/policy-clarification-multiple-applications-for-the-same-use-case/92080).
En este contexto, definimos “caso de uso” como un conjunto consistente de análisis, visualizaciones o acciones realizadas a través de una aplicación. Proporcionar el mismo servicio o aplicación a diferentes usuarios finales cuenta como un solo caso de uso: sin embargo, las versiones “white label” (marca blanca) de una herramienta o servicio no se incluyen. Si planeas ofrecer versiones “white label” de tu aplicación, debes notificarnos y recibir una aprobación separada por nuestra parte. Estas reglas se aplican tanto a las aplicaciones que registras tú, como a las aplicaciones registradas por los usuarios finales de tu herramienta o servicio; requerir que tus usuarios finales registren aplicaciones con el propósito de utilizar tu herramienta o servicio podría dar lugar a acciones de cumplimiento contra ti, tus aplicaciones, tus clientes y/o los usuarios finales de tu herramienta o servicio.
La única excepción a esta regla es crear instancias de desarrollo (“dev”), staging y producción (“prod”) del mismo servicio. Asegúrate de que estas aplicaciones estén claramente etiquetadas (por ejemplo, en el nombre o descripción de la aplicación), y de no usar aplicaciones de desarrollo o staging para fines de producción.
## Medición del servicio de X
No utilices las APIs de X para medir la disponibilidad, el rendimiento, la funcionalidad o el uso de X con fines de benchmarking o competitivos. Por ejemplo, nunca debes usar las APIs de X para:
* Calcular métricas agregadas de usuarios de X, como el número total de usuarios activos o cuentas
* Calcular métricas agregadas de publicaciones de X, como el número total de publicaciones por día, o el número de interacciones de usuario o de cuenta
* Medir o analizar el spam o la seguridad en X, excepto según lo permitido en las [Reglas de X](https://help.x.com/en/rules-and-policies/twitter-rules)
## Vigilancia, privacidad y protección del usuario
En X, proteger y defender la privacidad de nuestros usuarios está incorporado en el ADN central de nuestra empresa, y nuestros productos para desarrolladores y de datos reflejan ese compromiso. Creemos que los datos de X pueden ser una poderosa fuerza para el bien en el mundo, desde salvar vidas durante inundaciones en Yakarta hasta ayudar al USGS a rastrear terremotos, o trabajar con la ONU para alcanzar los Objetivos de Desarrollo Sostenible. Sin embargo, prohibimos el uso de los datos de X y de las APIs de X por parte de cualquier entidad con fines de vigilancia, o de cualquier otra forma que sea incompatible con las expectativas razonables de privacidad de nuestros usuarios. Y punto.
Describimos los usos prohibidos de nuestros datos y productos para desarrolladores en el [Acuerdo del Desarrollador](/developer-terms/agreement), incluidas las prohibiciones de investigar o rastrear a los usuarios de X o su contenido, así como rastrear, alertar o monitorear eventos sensibles (como protestas, mítines o reuniones de organización comunitaria).
Otras categorías de actividades prohibidas bajo estos términos incluyen (pero no se limitan a):
* Investigar o rastrear grupos y organizaciones sensibles, como sindicatos o grupos activistas
* Verificaciones de antecedentes o cualquier forma de investigación extrema (extreme vetting)
* Análisis de riesgo crediticio o de seguros
* Perfilado individual o segmentación psicográfica
* Reconocimiento facial
Estas políticas se aplican a todos los usuarios de nuestras APIs. Cualquier uso indebido de las APIs de X para estos fines estará sujeto a acciones de cumplimiento, que pueden incluir la suspensión y terminación del acceso.
Para obtener información adicional para las autoridades de aplicación de la ley que busquen información sobre cuentas de X, visita [https://t.co/le](https://t.co/le).
Además, en este momento, X prohíbe cualquier uso de las APIs de X y/o del Contenido de X para hacer fine-tuning o entrenar un modelo fundacional o frontera, con la excepción de [Grok](https://help.x.com/en/using-x/about-grok).
# Acerca de la Enterprise API — firehose, streams y webhooks
Source: https://docs.x.com/es/enterprise-api/getting-started/about-x-api
Descripción general de la Enterprise API de X: firehose completo, volume y likes streams, webhooks de account activity, límites personalizados y soporte.
La Enterprise API proporciona el nivel más alto de acceso a los datos de X. Incluye todo lo disponible en la X API estándar, además de endpoints exclusivos de alto volumen, operadores de embedding semántico para Filtered Stream, límites de tasa personalizados y gestión de cuenta dedicada para organizaciones que necesitan datos de X a escala.
***
## Qué puedes hacer
Todo lo de la X API estándar, además de:
| Capacidad | Descripción |
| :---------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Hacer streaming del firehose completo** | Acceso al 100% de los posts públicos en tiempo real con volume streams |
| **Hacer streaming de todos los likes** | Streams de likes completos y muestreados en tiempo real |
| **Streaming filtrado avanzado** | Powerstream (filtrado por palabras clave con baja latencia) |
| **Operadores de embedding semántico** | Empareja posts por significado (no solo por palabras clave) usando `embedding:` en Filtered Stream (Enterprise + nivel Embedding) |
| **Analítica profunda de interacción** | Métricas de interacción de posts y medios a escala |
| **Eventos de actividad de cuenta** | Suscripciones en tiempo real para eventos de usuarios (posts, DMs, likes, follows) |
| **Entrega vía webhook** | Recibe datos de filtered stream a través de webhooks |
| **Límites de tasa personalizados** | Límites elevados adaptados a tus necesidades de rendimiento |
| **Soporte dedicado** | Gestor de cuenta nominado y resolución prioritaria de incidencias |
***
## Endpoints exclusivos de Enterprise
Estos endpoints solo están disponibles con acceso Enterprise:
Firehose completo y streams específicos por idioma para una cobertura total en tiempo real.
Transmite todos los likes o likes muestreados en toda la plataforma.
Streaming filtrado de alto rendimiento con operadores avanzados.
Analítica de posts y medios para insights profundos de interacción.
Suscripciones en tiempo real a eventos de actividad de usuarios.
Entrega de filtered stream a través de webhooks.
***
## Todos los recursos disponibles
El acceso Enterprise incluye el conjunto completo de recursos de la X API:
Busca, recupera, crea y elimina posts. Accede a timelines, hilos y quote posts.
Consulta perfiles, administra relaciones y accede a datos de seguidores.
Descubre conversaciones de audio en vivo y sus participantes.
Envía y recibe mensajes privados entre usuarios.
Crea y administra listas curadas de cuentas.
Accede a temas en tendencia por ubicación.
***
## Aspectos destacados de la API
Solicita únicamente los datos que necesitas. Usa los parámetros `fields` para seleccionar atributos específicos y `expansions` para incluir objetos relacionados.
```bash theme={null}
curl "https://api.x.com/2/tweets/123?tweet.fields=created_at,public_metrics&expansions=author_id&user.fields=username" \
-H "Authorization: Bearer $TOKEN"
```
[Más información sobre fields →](/x-api/fundamentals/fields)
Los posts incluyen anotaciones semánticas que identifican personas, lugares, productos y temas. Filtra streams y búsquedas por tema.
[Más información sobre anotaciones →](/x-api/fundamentals/post-annotations)
Los clientes Enterprise obtienen acceso a endpoints dedicados de métricas de interacción tanto para posts como para medios, ofreciendo analítica profunda a escala más allá de lo que proporcionan las métricas públicas estándar.
[Más información sobre métricas →](/x-api/fundamentals/metrics)
Reconstruye hilos completos de conversación usando `conversation_id`. Sigue las respuestas a lo largo de todo el hilo.
[Más información sobre seguimiento de conversaciones →](/x-api/fundamentals/conversation-id)
Accede al historial de ediciones de los posts, incluyendo todas las versiones anteriores y los metadatos de edición.
[Más información sobre edición de posts →](/x-api/fundamentals/edit-posts)
***
## Precios
Los planes Enterprise están personalizados según las necesidades de tu organización. Los precios se basan en tu volumen de datos, uso de endpoints y requisitos de soporte.
| Característica | Detalles |
| :-------------------------------- | :------------------------------------------------------------- |
| **Paquetes personalizados** | Adaptados a tus necesidades específicas de datos y rendimiento |
| **Contratos a más largo plazo** | Precios predecibles con acuerdos de uso comprometido |
| **Sin tope de lecturas de posts** | Volúmenes de lectura de posts personalizados o ilimitados |
| **Soporte dedicado** | Incluido con todos los planes Enterprise |
[Contacta a ventas para conocer los precios](/forms/enterprise-api-interest)
***
## Próximos pasos
Contacta a nuestro equipo de ventas para discutir tus necesidades.
Explora todos los endpoints disponibles, incluidos los exclusivos de Enterprise.
# Obtener acceso Enterprise
Source: https://docs.x.com/es/enterprise-api/getting-started/getting-access
Solicita acceso a la X Enterprise API, trabaja con tu equipo dedicado durante la incorporación y configura credenciales para tu volumen de datos.
El acceso Enterprise requiere un proceso de solicitud e incorporación. Tu equipo de cuenta dedicado te ayudará a configurar las credenciales y tu acceso.
***
## Paso 1: Solicita el acceso Enterprise
[Completa el formulario de interés Enterprise](/forms/enterprise-api-interest) con detalles sobre tu organización y caso de uso.
Nuestro equipo de ventas se pondrá en contacto contigo para conocer tu volumen de datos, los requisitos de endpoint y las necesidades de soporte.
Recibe un plan a medida con precios, límites de tasa y niveles de acceso diseñados para tu caso de uso.
***
## Paso 2: Realiza la incorporación
Una vez que tu plan Enterprise esté listo, tu gerente de cuenta dedicado te ayudará a configurar:
Configura tu App en la [Developer Console](https://console.x.com) con acceso de nivel Enterprise.
Tu gerente de cuenta te ayudará a configurar los límites de tasa, el acceso a los endpoints y cualquier ajuste personalizado.
Genera tus API keys y tokens para la autenticación.
***
## Paso 3: Guarda tus credenciales
Recibirás varias credenciales según tus necesidades de autenticación:
| Credencial | Propósito |
| :------------------------ | :------------------------------------------------------------------------------- |
| **API Key & Secret** | Identifican tu App. Se usan para generar tokens y firmar solicitudes OAuth 1.0a. |
| **Bearer Token** | Autenticación solo de App para leer datos públicos. |
| **Access Token & Secret** | Realiza solicitudes en nombre de tu propia cuenta (OAuth 1.0a). |
| **Client ID & Secret** | Autenticación OAuth 2.0 para solicitudes en contexto de usuario. |
**Guárdalas de inmediato.** Las credenciales solo se muestran una vez. Almacénalas en un gestor de contraseñas o en una bóveda segura. Si las pierdes, tendrás que regenerarlas (lo que invalidará las anteriores).
***
## ¿Qué credenciales necesitas?
Usa el **Bearer Token** para un acceso simple y de solo lectura a datos públicos.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Ideal para: buscar publicaciones, consultar usuarios, leer tendencias.
Usa **OAuth 2.0** (recomendado) o **OAuth 1.0a** para actuar en nombre de los usuarios.
OAuth 2.0 ofrece scopes detallados: solicita solo los permisos que necesites.
Ideal para: publicar, dar like, seguir, acceder a DMs.
[Guía de OAuth 2.0 →](/resources/fundamentals/authentication/oauth-2-0/overview)
Usa tu **Access Token & Secret** para realizar solicitudes como tu propia cuenta.
Estos tokens representan a la cuenta propietaria de la App.
Ideal para: pruebas, bots personales, tu propia automatización.
***
## Buenas prácticas de seguridad de credenciales
Nunca incluyas credenciales en el código fuente.
Añade los archivos de credenciales a `.gitignore`.
Regenera las credenciales periódicamente como medida de seguridad.
Solicita solo los permisos OAuth que tu App necesite.
***
## Próximos pasos
Llama a la API con tus nuevas credenciales.
Comprende OAuth 1.0a y OAuth 2.0.
# Recursos importantes
Source: https://docs.x.com/es/enterprise-api/getting-started/important-resources
Recursos esenciales para clientes de la Enterprise API de X, incluidas guías de onboarding, gestores de cuenta, contactos de soporte, páginas de estado y SDKs.
Guarda en marcadores estos recursos esenciales para el desarrollo con la X API.
***
## Documentación
Documentación completa de endpoints con parámetros y ejemplos.
Esquemas de objetos para posts, usuarios, medios y más.
Guías de implementación de OAuth 1.0a y OAuth 2.0.
Límites por endpoint y mejores prácticas.
***
## Herramientas
| Herramienta | Descripción |
| :--------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------- |
| [Developer Console](https://console.x.com) | Administra apps, credenciales y facturación |
| [Colección de Postman](https://www.postman.com/xapidevelopers/x-api-public-workspace/collection/34902927-2efc5689-99c6-4ab6-8091-996f35c2fd80) | Pruebas interactivas de la API |
| [Python SDK](/xdks/python/overview) | Biblioteca oficial de Python |
| [TypeScript SDK](/xdks/typescript/overview) | Biblioteca oficial de TypeScript |
| [OpenAPI Spec](https://api.x.com/2/openapi.json) | Especificación de la API legible por máquina |
***
## Aprendizaje
Guías paso a paso para casos de uso comunes.
Apps de ejemplo y código de muestra.
Ideas e inspiración para proyectos.
Actualiza de v1.1 a v2.
***
## Comunidad y soporte
Haz preguntas y comparte soluciones con la comunidad.
Preguntas frecuentes, solución de problemas y opciones de contacto.
Actualizaciones y anuncios oficiales.
Noticias y consejos específicos de la API.
***
## Mantente al día
| Recurso | Qué obtendrás |
| :----------------------------------------------------------------- | :--------------------------------------------------- |
| [Changelog](/changelog) | Todos los cambios y actualizaciones de la plataforma |
| [Boletín](/newsletter) | Resumen mensual de noticias y funciones |
| [Anuncios del foro](https://devcommunity.x.com/c/announcements/22) | Avisos importantes de la plataforma |
| [Estado de la API](/status) | Disponibilidad del servicio en tiempo real |
Sigue a [@XDevelopers](https://x.com/XDevelopers) y activa las notificaciones para enterarte de cambios disruptivos y nuevas funciones.
***
## Referencia rápida
### Estructura de respuesta
Todas las respuestas de v2 siguen esta estructura:
```json theme={null}
{
"data": { ... }, // Objeto(s) principal(es)
"includes": { ... }, // Objetos expandidos (si se solicitan)
"meta": { ... }, // Información de paginación
"errors": [ ... ] // Errores parciales (si los hay)
}
```
### Parámetros comunes
| Parámetro | Uso |
| :----------------- | :-------------------------------------- |
| `tweet.fields` | Solicita campos específicos del post |
| `user.fields` | Solicita campos específicos del usuario |
| `expansions` | Incluye objetos relacionados |
| `max_results` | Limita los resultados por página |
| `pagination_token` | Obtener página siguiente/anterior |
### Métodos de autenticación
| Método | Caso de uso |
| :----------- | :----------------------------------------------- |
| Bearer Token | Datos públicos de solo lectura |
| OAuth 2.0 | Acciones de usuario con scopes detallados |
| OAuth 1.0a | Acciones de usuario (legado, permisos completos) |
[Guía completa de autenticación →](/resources/fundamentals/authentication/overview)
# Realiza tu primera solicitud
Source: https://docs.x.com/es/enterprise-api/getting-started/make-your-first-request
Realiza tu primera solicitud a la Enterprise API de X: configura autenticación, elige endpoint, ejecuta cURL de ejemplo y maneja la respuesta.
Esta guía te lleva paso a paso a realizar tu primera solicitud a la X API. Necesitarás una [cuenta de desarrollador con credenciales de app](/x-api/getting-started/getting-access) antes de comenzar.
***
## Inicio rápido con cURL
La forma más rápida de probar la API es con cURL. Vamos a buscar un usuario:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Reemplaza `$BEARER_TOKEN` con tu Bearer Token real. Obtendrás una respuesta como esta:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Guía paso a paso
En la [Developer Console](https://console.x.com), navega a tu app y copia el Bearer Token.
Comienza con alguno de estos endpoints aptos para principiantes:
| Endpoint | Qué hace |
| :------------------------------------------------ | :---------------------------------------------------- |
| [User lookup](/x-api/users/lookup/introduction) | Obtén el perfil de usuario por nombre de usuario o ID |
| [Post lookup](/x-api/posts/lookup/introduction) | Obtén un post por ID |
| [Recent search](/x-api/posts/search/introduction) | Busca posts de los últimos 7 días |
Usa cURL, Postman o tu cliente HTTP preferido:
```bash theme={null}
# Buscar un usuario por nombre de usuario
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Las respuestas son JSON. Los datos principales están en el campo `data`:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Solicita más datos con fields
Por defecto, los endpoints devuelven campos mínimos. Usa el parámetro `fields` para solicitar datos adicionales:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers?user.fields=created_at,description,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Respuesta:
```json 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 Platform",
"public_metrics": {
"followers_count": 570842,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
[Más información sobre fields →](/x-api/fundamentals/fields)
***
## Más ejemplos
```bash theme={null}
curl "https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=from:xdevelopers&tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/tweets?max_results=5" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Usar código en lugar de cURL
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/users/by/username/xdevelopers"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers)
print(response.json())
```
```javascript theme={null}
const bearerToken = "YOUR_BEARER_TOKEN";
const url = "https://api.x.com/2/users/by/username/xdevelopers";
fetch(url, {
headers: { Authorization: `Bearer ${bearerToken}` }
})
.then(res => res.json())
.then(data => console.log(data));
```
Para uso en producción, recomendamos los SDKs oficiales:
* [Python SDK](/xdks/python/overview)
* [TypeScript SDK](/xdks/typescript/overview)
Se encargan automáticamente de la autenticación, la paginación y los límites de tasa.
***
## Herramientas para pruebas
Pruebas visuales de la API con nuestra colección.
Ejemplos en múltiples lenguajes.
Documentación completa de los endpoints.
***
## Solución de problemas
* Verifica que tu Bearer Token sea correcto
* Asegúrate de que el token no haya sido regenerado
* Verifica el formato del encabezado `Authorization`: `Bearer YOUR_TOKEN`
* Es posible que tu app no tenga acceso a este endpoint
* Algunos endpoints requieren autenticación de contexto de usuario (OAuth 1.0a o 2.0)
* Verifica los permisos de tu app en la Developer Console
* Alcanzaste un límite de tasa
* Consulta el encabezado `x-rate-limit-reset` para saber cuándo reintentar
* Implementa retroceso exponencial en tu código
[Referencia completa de errores →](/x-api/fundamentals/response-codes-and-errors)
***
## Próximos pasos
Comprende OAuth para solicitudes con contexto de usuario.
Descubre lo que puedes construir.
Desarrollo más rápido con bibliotecas oficiales.
Ideas de qué crear.
# Precios de la Enterprise API y planes personalizados
Source: https://docs.x.com/es/enterprise-api/getting-started/pricing
Los planes de la X Enterprise API se personalizan según el volumen de datos, los endpoints y el soporte de tu organización. Contacta a ventas para precios.
Los planes Enterprise se personalizan según las necesidades de tu organización. Trabaja con un equipo de cuenta dedicado para crear un paquete que se ajuste a tu volumen de datos, uso de endpoints y requisitos de soporte.
***
## Cómo funcionan los precios Enterprise
Los precios se adaptan a tu volumen de datos específico, necesidades de endpoints y requisitos de rendimiento.
Costos predecibles con acuerdos a más largo plazo y niveles de uso comprometidos.
Volúmenes de lectura de posts personalizados o ilimitados, muy por encima del tope de 2 millones mensuales de los planes de pago por uso.
Un account manager designado y soporte técnico prioritario están incluidos en cada plan Enterprise.
***
## Qué se incluye
Cada plan Enterprise incluye acceso a la X API completa más endpoints exclusivos de Enterprise:
| Función | Detalles |
| :------------------------------------ | :------------------------------------------------------------------------------------------------------------ |
| **Todos los endpoints estándar** | Todo lo disponible en la X API de pago por uso |
| **Volume streams** | Firehose completo y streams específicos por idioma |
| **Likes streams** | Likes completos y muestreados en tiempo real |
| **Powerstream** | Streaming filtrado avanzado |
| **Operadores de embedding semántico** | Operador `embedding:` para coincidencia semántica solo en Filtered Stream (requiere acceso al tier Embedding) |
| **Métricas de engagement** | Endpoints de analítica de posts y media |
| **Account Activity** | Suscripciones a eventos de usuario en tiempo real |
| **Stream webhooks** | Entrega de streams filtrados a través de webhooks |
| **Rate limits personalizados** | Límites elevados ajustados a tus necesidades |
| **Soporte dedicado** | Account manager designado y resolución prioritaria |
***
## Enterprise vs. pago por uso
| | Pago por uso | Enterprise |
| :------------------------------------ | :------------------------------------- | :---------------------------------------------------------------------------------- |
| **Modelo de precios** | Basado en créditos, pago según consumo | Contrato personalizado |
| **Tope mensual de posts** | 2 millones de lecturas | Personalizado / ilimitado |
| **Volume streams** | No disponible | Firehose completo y streams por idioma |
| **Likes streams** | No disponible | Likes completos y muestreados |
| **Operadores de embedding semántico** | No disponible | Operador `embedding:` solo para Filtered Stream (requiere acceso al tier Embedding) |
| **Métricas de engagement** | No disponible | Analítica de posts y media |
| **Rate limits** | Estándar | Personalizados / elevados |
| **Soporte** | Foro comunitario | Account manager dedicado |
| **Compromiso** | Ninguno | Basado en contrato |
***
## Monitoreo del uso
Rastrea el uso de tu API de forma programática con el [endpoint de Usage](/x-api/usage/introduction):
```bash theme={null}
curl "https://api.x.com/2/usage/tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Esto devuelve los conteos diarios de consumo de Posts, ayudándote a:
* Rastrear el consumo en relación con los límites de tu contrato
* Generar informes de uso para los stakeholders
* Identificar los endpoints con mayor consumo
* Planificar la capacidad con tu equipo de cuenta
***
## Empezar
[Solicita acceso Enterprise](/forms/enterprise-api-interest) y cuéntanos sobre tu caso de uso y tus necesidades de datos.
Nuestro equipo de ventas trabajará contigo para crear un paquete que se ajuste a tus requisitos y presupuesto.
Tu account manager dedicado te ayudará a configurar las credenciales, definir el acceso y comenzar a desarrollar.
***
## Próximos pasos
Contacta a nuestro equipo de ventas para empezar.
Monitorea el uso de forma programática.
# Enterprise API
Source: https://docs.x.com/es/enterprise-api/introduction
Acceso de nivel enterprise al firehose de X, volume streams, búsqueda en archivo completo y PowerTrack con soporte técnico dedicado y precios personalizados.
El plan Enterprise de la X API proporciona el más alto nivel de acceso a los datos de X. Obtén cobertura completa del firehose, volume streams, operadores de embedding semántico para Filtered Stream, gestión de cuenta dedicada y límites de tasa personalizados, diseñados para organizaciones que dependen de los datos de X a escala.
Solicita el acceso Enterprise con un equipo de cuenta dedicado.
Explora todos los endpoints disponibles, incluidos los exclusivos de Enterprise.
Bibliotecas oficiales de Python y TypeScript.
***
## ¿Por qué Enterprise?
El acceso Enterprise incluye todo lo del plan pago por uso de la X API, además de endpoints exclusivos de alto volumen, soporte dedicado y paquetes personalizados adaptados a tus necesidades.
Recibe en streaming el 100% de los posts públicos en tiempo real. Sin muestreo ni límites. Obtén cada post a medida que ocurre.
Accede a streams de volumen completo y específicos por idioma, incluidos los firehose en inglés, japonés, coreano y portugués.
Obtén un gestor de cuenta dedicado, soporte técnico personalizado y resolución prioritaria de incidencias.
Límites de tasa más altos y paquetes a medida para ajustarse a tus requisitos de rendimiento.
Accede a endpoints de analítica de posts y medios para obtener insights profundos de interacción en grandes conjuntos de datos.
Mantente en cumplimiento con streams en tiempo real de eventos de compliance para posts, usuarios y likes.
Empareja posts por significado conceptual, no solo por palabras clave, usando el operador `embedding:` en Filtered Stream (requiere el nivel Embedding).
***
## Endpoints exclusivos de Enterprise
Estos endpoints solo están disponibles en los planes Enterprise:
Firehose completo, streams específicos por idioma y streams muestreados.
Transmite todos los likes o likes muestreados en tiempo real.
Streaming filtrado de alto rendimiento con baja latencia (operadores de palabras clave).
Analítica profunda para la interacción con posts y medios.
Suscríbete a eventos de actividad del usuario en tiempo real, incluidos posts, DMs, likes y follows.
Recibe datos de filtered stream a través de webhooks en lugar de conexiones persistentes.
***
## Qué puedes construir
El acceso Enterprise impulsa los casos de uso más exigentes en X.
Busca, recupera y publica posts. Accede a timelines, hilos y quote posts.
Busca usuarios, administra follows, bloqueos y silencios.
Encuentra conversaciones de audio en vivo y sus participantes.
Envía y recibe mensajes privados.
Crea y administra listas curadas de cuentas.
Accede a temas en tendencia por ubicación.
***
## Funciones clave
### Cobertura total en tiempo real
Recibe en streaming el 100% de los posts públicos a medida que ocurren. Sin muestreo ni huecos. El acceso al firehose Enterprise te ofrece el panorama completo de la conversación pública en X.
Streams disponibles:
* **Todos los posts** - Cada post público en tiempo real
* **Posts en inglés** - Todos los posts en idioma inglés
* **Posts en japonés** - Todos los posts en idioma japonés
* **Posts en coreano** - Todos los posts en idioma coreano
* **Posts en portugués** - Todos los posts en idioma portugués
* **Streams muestreados** - Muestras aleatorias del 1% y del 10%
[Más información sobre volume streams](/x-api/posts/volume-streams/introduction)
### Objetos de datos enriquecidos
Accede a datos detallados y estructurados para posts, usuarios, medios y más:
* **Posts**: Texto completo, métricas, entidades, anotaciones, hilos de conversación
* **Usuarios**: Perfiles, conteo de seguidores, estado de verificación
* **Medios**: Imágenes, videos, GIFs con metadatos
* **Encuestas**: Opciones y conteo de votos
Personaliza las respuestas con [fields](/x-api/fundamentals/fields) y [expansions](/x-api/fundamentals/expansions) para obtener exactamente los datos que necesitas.
### Filtered stream
Recibe los posts en tiempo real a medida que se publican. Enterprise añade límites de reglas más altos y el operador semántico `embedding:` (solo en Filtered Stream) para hacer match de posts por significado (no solo por palabras clave).
```bash theme={null}
# Agregar una regla
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $TOKEN" \
-d '{"add": [{"value": "from:xdevelopers"}]}'
# Conectarse al stream
curl "https://api.x.com/2/tweets/search/stream" \
-H "Authorization: Bearer $TOKEN"
```
[Más información sobre filtered stream](/x-api/posts/filtered-stream/introduction)
### Búsqueda en archivo completo
Busca el historial completo de posts públicos desde 2006. Crea consultas con operadores para usuarios, palabras clave, fechas y más.
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?query=AI%20lang:en" \
-H "Authorization: Bearer $TOKEN"
```
### Métricas de interacción
Accede a analítica profunda de interacción, incluidas impresiones, likes, reposts, respuestas, vistas de video y métricas a nivel de medios.
[Más información sobre búsqueda](/x-api/posts/search/introduction)
***
## Enterprise vs. pago por uso
| Característica | Pago por uso | Enterprise |
| :-------------------------- | :--------------------------- | :--------------------------------------------------------------------------- |
| **Post search** | Recientes y archivo completo | Recientes y archivo completo |
| **Filtered stream** | Hasta 1,000 reglas | 5,000+ reglas + operadores semánticos `embedding:` (solo en Filtered Stream) |
| **Volume streams** | - | Firehose completo y streams por idioma |
| **Likes streams** | - | Likes completos y muestreados |
| **Powerstream** | - | Streaming filtrado avanzado |
| **Métricas de interacción** | - | Analítica de posts y medios |
| **Account Activity** | - | Suscripciones en tiempo real a eventos de usuario |
| **Tope mensual de posts** | 2 millones de lecturas | Personalizado / ilimitado |
| **Límites de tasa** | Estándar | Personalizado / elevado |
| **Soporte** | Foro de la comunidad | Gestor de cuenta dedicado |
***
## Primeros pasos
[Contacta a nuestro equipo de ventas](/forms/enterprise-api-interest) para discutir tus necesidades y obtener un paquete personalizado.
Tu gestor de cuenta dedicado te ayudará a configurar las credenciales y tu acceso.
Usa los mismos endpoints modernos de la API v2, además de los endpoints exclusivos de Enterprise para tu integración.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Herramientas y bibliotecas
Biblioteca oficial de Python con soporte async.
Biblioteca oficial de TypeScript/JavaScript.
Explorador interactivo de la API.
[Explora todas las bibliotecas](/tools-and-libraries)
***
## Soporte
Los clientes Enterprise obtienen un punto de contacto dedicado para soporte técnico y de cuenta.
Obtén ayuda de la comunidad y del equipo de X.
# Formulario de acceso a la Ads API
Source: https://docs.x.com/es/forms/ads-api-access
Solicita acceso a la X Ads API enviando tus datos, incluido el caso de uso previsto y la información de la app, para su revisión y aprobación.
# Formulario de soporte de facturación
Source: https://docs.x.com/es/forms/billing-support
Ponte en contacto con el soporte de facturación de la X API para obtener ayuda con facturas, métodos de pago, cambios de suscripción, reembolsos, actualizaciones de plan y problemas de facturación relacionados con la cuenta.
Obtén soporte de facturación para suscripciones Self-serve y de Enterprise API.
# Formulario de acceso a Enterprise
Source: https://docs.x.com/es/forms/enterprise-api-interest
Solicita acceso a la X Enterprise API enviando los datos de la empresa, el caso de uso previsto, el volumen de datos esperado y la información de contacto para su revisión.
# Formulario de solicitud para usuarios finales gubernamentales
Source: https://docs.x.com/es/forms/government-end-user-request
Formulario para el sector público y gubernamental para solicitar acceso a la X API, proporcionando los datos de la agencia, el caso de uso previsto y la información de cumplimiento para su revisión.
# Índice de la referencia de la API de OAuth
Source: https://docs.x.com/es/fundamentals/authentication/api-reference
Índice de referencia de los endpoints de autenticación de X en OAuth 1.0a y OAuth 2.0, incluidos request tokens, authorize, access tokens y revocación de tokens.
### OAuth 1.0a
| | |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------- |
| **Propósito** | Método |
| Paso 1 del flujo OAuth de 3 patas e Iniciar sesión con X Permite que una aplicación Consumer obtenga un OAuth Request Token para solicitar la autorización del usuario. | [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) |
| Paso 2 del flujo OAuth de 3 patas e Iniciar sesión con X Permite que una aplicación Consumer use un OAuth Request Token para solicitar la autorización del usuario. | [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) |
| Paso 2 del flujo OAuth de 3 patas e Iniciar sesión con X Permite que una aplicación Consumer use un OAuth Request Token para solicitar la autorización del usuario. | [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) |
| Paso 3 del flujo OAuth de 3 patas e Iniciar sesión con X Permite que una aplicación Consumer intercambie el OAuth Request Token por un OAuth Access Token. | [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) |
| Permite que una aplicación registrada revoque un OAuth Access Token emitido. | [POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth-invalidate-token) |
### OAuth 2.0 Bearer Token
| | |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
| **Propósito** | Método |
| Permite que una App registrada genere un OAuth 2 app-only Bearer Token, que se puede usar para realizar solicitudes a la API en nombre de una App, sin contexto de usuario. | [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) |
| Permite que una App registrada revoque un OAuth 2 app-only Bearer Token emitido. | [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) |
### POST oauth/request\_token
Permite que una aplicación Consumer obtenga un OAuth Request Token para solicitar la autorización del usuario. Este método cumple con la [Sección 6.1](https://oauth.net/core/1.0/#auth_step1) del [flujo de autenticación OAuth 1.0](http://oauth.net/core/1.0/#anchor9).
**Requerimos que uses HTTPS en todos los pasos de autorización de OAuth.**
**Nota de uso:** Solo se aceptan valores ASCII para el `oauth_nonce`
**URL del recurso[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/request_token`
**Información del recurso[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Formatos de respuesta | JSON |
| ¿Requiere autenticación? | No |
| ¿Tiene límite de tasa? | Sí |
**Parámetros[](#parameters "Permalink to this headline")**
| Nombre | Requerido | Descripción | Ejemplo |
| :-------------------- | :-------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------- |
| oauth\_callback | requerido | Para el cumplimiento de OAuth 1.0a, este parámetro es **requerido**. El valor que especifiques aquí se usará como la URL a la que se redirigirá al usuario si aprueba el acceso de tu aplicación a su cuenta. Establécelo en `oob` para el modo pin fuera de banda. Así también se especifican callbacks personalizados para usar en aplicaciones de escritorio/móviles. Envía siempre un `oauth_callback` en este paso, independientemente de un callback preregistrado.
Requerimos que cualquier URL de callback usada con este endpoint deba estar configurada dentro de la configuración de la App en developer.x.com\* | `http://themattharris.local/auth.php` `twitterclient://callback` |
| x\_auth\_access\_type | opcional | Sobrescribe el nivel de acceso que una aplicación solicita a la cuenta de un usuario. Los valores admitidos son `read` o `write`. Este parámetro está pensado para permitir a un desarrollador registrar una aplicación de lectura/escritura pero también solicitar acceso de solo lectura cuando sea apropiado. | |
Aprende más sobre cómo aprobar tus URLs de callback en [esta página](/resources/fundamentals/developer-apps#callback-urls).
**Ten en cuenta** - Puedes ver y editar tus [X apps](/resources/fundamentals/developer-apps) existentes a través del [panel de X apps](https://developer.x.com/en/apps) si has iniciado sesión con tu cuenta de X en developer.x.com.
**Solicitud de ejemplo[](#example-request "Permalink to this headline")**
URL de la solicitud: `POST https://api.x.com/oauth/request_token`
Cuerpo POST de la solicitud: *N/A*
Encabezado de autorización: `OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw", oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1300228849", oauth_consumer_key="OqEqJeafRSF11jBMStrZz", oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", oauth_version="1.0"`
Respuesta: `oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik&oauth_token_secret=Kd75W4OQfb2oJTV0vzGzeXftVAwgMnEK9MumzYcM&oauth_callback_confirmed=true`
### GET oauth/authorize
Permite que una aplicación Consumer use un OAuth Request Token para solicitar la autorización del usuario. Este método cumple con la [Sección 6.2](http://oauth.net/core/1.0/#auth_step2) del [flujo de autenticación OAuth 1.0](http://oauth.net/core/1.0/#anchor9). Las aplicaciones de escritorio deben usar este método (y no pueden usar [GET oauth / authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate)).
**Nota de uso:** Nunca se envía un `oauth_callback` a este método; proporciónalo a [POST oauth / request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) en su lugar.
**URL del recurso[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authorize`
**Información del recurso[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Formatos de respuesta | JSON |
| ¿Requiere autenticación? | Sí |
| ¿Tiene límite de tasa? | Sí |
**Parámetros[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :-------- | :---------------------------------------------------------------------------------------------------------------- | :------------------- | :------ |
| Nombre | Requerido | Descripción | Valor predeterminado | Ejemplo |
| force\_login | opcional | Obliga al usuario a ingresar sus credenciales para asegurar que se autorice la cuenta correcta. | | |
| screen\_name | opcional | Rellena previamente el campo de nombre de usuario de la pantalla de inicio de sesión OAuth con el valor indicado. | | |
**Solicitud de ejemplo[](#example-request "Permalink to this headline")**
Envía al usuario al paso `oauth/authorize` en un navegador web, incluyendo un parámetro oauth\_token:
`https://api.x.com/oauth/authorize?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### GET oauth/authenticate
Permite que una aplicación Consumer use un `request_token` OAuth para solicitar la autorización del usuario.
Este método reemplaza la [Sección 6.2](http://oauth.net/core/1.0/#auth_step2) del [flujo de autenticación OAuth 1.0](http://oauth.net/core/1.0/#anchor9) para aplicaciones que utilizan el flujo de autenticación por callback. El método usará al usuario que actualmente ha iniciado sesión como la cuenta para la autorización de acceso, a menos que el parámetro `force_login` esté establecido en `true`.
Este método se diferencia de [GET oauth / authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) en que, si el usuario ya ha otorgado permiso a la aplicación, la redirección se producirá sin que el usuario tenga que volver a aprobar la aplicación. Para lograr este comportamiento, debes habilitar la opción *Use Sign in with X* en el [registro de tu aplicación](https://developer.x.com/apps).
**URL del recurso[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authenticate`
**Información del recurso[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Formatos de respuesta | JSON |
| ¿Requiere autenticación? | Sí |
| ¿Tiene límite de tasa? | Sí |
**Parámetros[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :-------- | :---------------------------------------------------------------------------------------------------------------- | :------------------- | :------ |
| Nombre | Requerido | Descripción | Valor predeterminado | Ejemplo |
| force\_login | opcional | Obliga al usuario a ingresar sus credenciales para asegurar que se autorice la cuenta correcta. | | *true* |
| screen\_name | opcional | Rellena previamente el campo de nombre de usuario de la pantalla de inicio de sesión OAuth con el valor indicado. | | |
**Solicitud de ejemplo[](#example-request "Permalink to this headline")**
Envía al usuario al paso `oauth/authenticate` en un navegador web, incluyendo un parámetro oauth\_token:
`https://api.x.com/oauth/authenticate?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### POST oauth/access\_token
Permite que una aplicación Consumer intercambie el OAuth Request Token por un OAuth Access Token. Este método cumple con la [Sección 6.3](http://oauth.net/core/1.0/#auth_step3) del [flujo de autenticación OAuth 1.0](http://oauth.net/core/1.0/#anchor9).
**URL del recurso[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/access_token`
**Información del recurso[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Formatos de respuesta | JSON |
| ¿Requiere autenticación? | Sí |
| ¿Tiene límite de tasa? | Sí |
**Parámetros[](#parameters "Permalink to this headline")**
| | | | | |
| :-------------- | :-------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------- | :------ |
| Nombre | Requerido | Descripción | Valor predeterminado | Ejemplo |
| oauth\_token | requerido | El oauth\_token aquí debe ser el mismo que el oauth\_token devuelto en el paso request\_token. | | |
| oauth\_verifier | requerido | Si utilizas el flujo OAuth web, establece este parámetro con el valor del *oauth\_verifier* devuelto en la URL de callback. Si estás utilizando OAuth fuera de banda, establece este valor en el pin-code. Para el cumplimiento de OAuth 1.0a, este parámetro es **requerido**. OAuth 1.0a se aplica estrictamente y las aplicaciones que no usen el *oauth\_verifier* no podrán completar el flujo OAuth. | | |
**Solicitud de ejemplo[](#example-request "Permalink to this headline")**
`POST https://api.x.com/oauth/access_token?oauth_token=qLBVyoAAAAAAx72QAAATZxQWU6P&oauth_verifier=ghLM8lYmAxDbaqL912RZSRjCCEXKDIzx`
Desde PIN-based `POST https://api.x.com/oauth/access_token?oauth_token=9Npq8AAAAAAAx72QBRABZ4DAfY9&oauth_verifier=4868795`
**Respuesta de ejemplo[](#example-response "Permalink to this headline")**
`oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG5ly3sR3XjE0IBSnlQu4ZrUzPiYTmrkVU&user_id=6253282&screen_name=xapi`
### POST oauth/invalidate\_token
Permite que una aplicación registrada revoque un access\_token OAuth emitido presentando sus credenciales de cliente. Una vez que se haya invalidado un access\_token, los nuevos intentos de creación producirán un Access Token diferente y ya no se permitirá el uso del token invalidado.
**URL del recurso[](#resource-url "Permalink to this headline")**
`https://api.x.com/1.1/oauth/invalidate_token`
**Información del recurso[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :------------------------------------------------------------------ |
| Formatos de respuesta | JSON |
| ¿Requiere autenticación? | Sí — Contexto de usuario con los access tokens que deseas invalidar |
| ¿Tiene límite de tasa? | Sí |
**Solicitud de ejemplo[](#example-request "Permalink to this headline")**
```bash theme={null}
curl --request POST
--url 'https://api.x.com/1.1/oauth/invalidate_token.json'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**Respuesta de ejemplo[](#example-response "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 127
...
{"access_token":"ACCESS_TOKEN"}
```
**Respuesta de error de ejemplo después de invalidar el token[](#example-error-response-after-token-has-been-invalidated "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 401 Authorization Required
...
{"errors": [{
"code": 89,
"message": "Invalid or expired token."}
]}
```
### POST oauth2/token
Permite que una aplicación registrada obtenga un OAuth 2 Bearer Token, que se puede usar para realizar solicitudes a la API en nombre de la propia aplicación, sin contexto de usuario. Esto se llama [Autenticación Application-only](/resources/fundamentals/authentication/oauth-2-0/application-only).
Un Bearer Token puede invalidarse usando oauth2/invalidate\_token. Una vez que se haya invalidado un Bearer Token, los nuevos intentos de creación producirán un Bearer Token diferente y ya no se permitirá el uso del token anterior.
Solo puede existir un bearer token pendiente para una aplicación, y las solicitudes repetidas a este método producirán el mismo token ya existente hasta que se invalide.
Las respuestas exitosas incluyen una estructura JSON que describe el Bearer Token concedido.
Los tokens recibidos por este método deben almacenarse en caché. Si se intenta con demasiada frecuencia, las solicitudes serán rechazadas con un HTTP 403 con código 99.
**URL del recurso[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/token`
**Información del recurso[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :---------------------------------------------------------------------------------------- |
| Formatos de respuesta | JSON |
| ¿Requiere autenticación? | Sí — Basic auth con tu API key como nombre de usuario y tu API key secret como contraseña |
| ¿Tiene límite de tasa? | Sí |
**Parámetros[](#parameters "Permalink to this headline")**
| | | | | |
| :---------- | :-------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------- | :-------------------- |
| Nombre | Requerido | Descripción | Valor predeterminado | Ejemplo |
| grant\_type | requerido | Especifica el tipo de concesión solicitada por la aplicación. En este momento, solo se permite *client\_credentials*. Consulta [Autenticación Application-Only](/resources/fundamentals/authentication/oauth-2-0/application-only) para más información. | | *client\_credentials* |
**Solicitud de ejemplo[](#example-request "Permalink to this headline")**
```bash theme={null}
POST /oauth2/token HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=client_credentials
```
**Respuesta de ejemplo:**
```bash theme={null}
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
```
### POST oauth2/invalidate\_token
Permite que una aplicación registrada revoque un oAuth 2.0 Bearer Token emitido presentando sus credenciales de cliente. Una vez que se haya invalidado un Bearer Token, los nuevos intentos de creación producirán un Bearer Token diferente y ya no se permitirá el uso del token invalidado.
Las respuestas exitosas incluyen una estructura JSON que describe el Bearer Token revocado.
**URL del recurso[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/invalidate_token`
**Información del recurso[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Formatos de respuesta | JSON |
| ¿Requiere autenticación? | Sí — [oAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a) con las API keys de consumer de la aplicación y el access token & access token secret del propietario de la aplicación |
| ¿Tiene límite de tasa? | Sí |
**Parámetros[](#parameters "Permalink to this headline")**
| Nombre | Requerido | Descripción |
| :------------ | :-------- | :--------------------------------------------- |
| access\_token | requerido | El valor del bearer token que deseas invalidar |
**Solicitud de ejemplo[](#example-request "Permalink to this headline")**
```
curl --request POST
--url 'https://api.x.com/oauth2/invalidate_token?access_token=AAAA%2FAAA%3DAAAAAAAA'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**Respuesta de ejemplo[](#example-response "Permalink to this headline")**
```
Status: 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 135
...
{
"access_token": "AAAA%2FAAA%3DAAAAAAAA"
}
```
# Autenticación básica
Source: https://docs.x.com/es/fundamentals/authentication/basic-auth
Usa HTTP Basic Authentication para acceder a las APIs enterprise de X como PowerTrack, Decahose y Search enviando tu correo electrónico y contraseña por HTTPS.
## Autenticación básica
Muchas de las APIs enterprise de X requieren el uso de HTTP Basic Authentication. Para realizar una solicitud exitosa a una API que requiere Basic Authentication, debes pasar una combinación válida de correo electrónico y contraseña como encabezado de autorización en cada solicitud. La combinación de correo electrónico y contraseña es la misma que utilizarás para acceder a la [consola de la API enterprise](https://console.gnip.com/), y se puede editar desde esta consola.
Al construir una solicitud usando Basic Authentication, asegúrate de agregar el encabezado HTTP Authentication: Basic con las credenciales codificadas sobre HTTPS.
En el siguiente ejemplo de solicitud cURL, reemplazarías `` y `` con tus credenciales antes de enviar la solicitud:
```bash theme={null}
curl -v --compressed -u:
"https://gnip-api.x.com/search/30day/accounts//prod/counts.json?query=from%3Axdevelopers"
```
**APIs que requieren autenticación básica:**
* [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) enterprise
* [Decahose stream API](http://localhost:3000/x-api/enterprise-gnip-2.0/fundamentals/decahose-api) enterprise
* [30-Day Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Full-Archive Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Usage API](/x-api/enterprise-gnip-2.0/fundamentals/usage) enterprise
# Preguntas frecuentes sobre OAuth
Source: https://docs.x.com/es/fundamentals/authentication/faq
Respuestas a preguntas comunes sobre OAuth 1.0a, OAuth 2.0, tokens de acceso, scopes y errores de autenticación al trabajar con la X API.
## General
OAuth es un protocolo de autenticación que permite a los usuarios aprobar una aplicación para que actúe en su nombre sin compartir su contraseña. Encontrarás más información en [oauth.net](http://oauth.net/).
Debes tener una [app de X](/resources/fundamentals/developer-apps) para generar tokens de acceso. Más información sobre tokens de acceso [aquí](/resources/fundamentals/authentication#oauth-1-0a-2).
Debes tener una [cuenta de desarrollador](/resources/fundamentals/developer-portal) para crear una [app de X](/resources/fundamentals/developer-apps). Puedes registrarte para obtener una [aquí](https://developer.x.com/en/portal/petition/essential/basic-info).
Puedes ver y editar tu app desde el [panel de apps de X](https://developer.x.com/content/developer-twitter/en/apps) si has iniciado sesión en tu cuenta de X en developer.x.com.
## Técnico
Los tokens de acceso no expiran explícitamente. Un token de acceso será invalidado si un usuario revoca explícitamente una aplicación en la configuración de su cuenta de X, o si X suspende una aplicación. Si una aplicación está suspendida, habrá una nota en el panel de la [app de X](/resources/fundamentals/developer-apps) indicando que ha sido suspendida.
Asume que el token de acceso de un usuario *puede* volverse inválido en cualquier momento. Si esto sucede, solicita al usuario que vuelva a autorizar la aplicación. Asegurarte de manejar esta situación con elegancia es importante para una buena experiencia de usuario.
Muchos usuarios confían en una aplicación para leer su información, pero no necesariamente para cambiar la información de su perfil de usuario o publicar nuevos estados. Actualizar información a través de la X API (ya sea el nombre, la ubicación o agregar un nuevo estado) requiere una solicitud HTTP POST. Cualquier método de la API que requiera una solicitud HTTP POST se considera un método de escritura y requiere acceso de lectura y escritura.
# Mejores prácticas
Source: https://docs.x.com/es/fundamentals/authentication/guides/authentication-best-practices
Debes proteger cuidadosamente tus API keys y tokens. Estas credenciales están directamente vinculadas a tu App de desarrollador y a las cuentas de X que te han autorizado.
Debes proteger cuidadosamente tus API keys y tokens.
Estas credenciales están directamente vinculadas a tu [App de desarrollador](/resources/fundamentals/developer-apps) y a las cuentas de X que te han autorizado a realizar solicitudes en su nombre. Si tus claves quedan comprometidas, actores malintencionados podrían usarlas para realizar solicitudes a los endpoints de X en nombre de tu App de desarrollador o de sus usuarios autorizados, lo que podría hacer que sus solicitudes te lleven a alcanzar límites de tasa inesperados, consumir tu asignación de acceso pagado o incluso hacer que tu App de desarrollador sea suspendida.
Las siguientes secciones incluyen las mejores prácticas que debes tener en cuenta al gestionar tus API keys y tokens.
## Regenera las API keys y tokens
En caso de que creas que tus API keys han sido expuestas, debes regenerar tus API keys siguiendo estos pasos:
1. Navega a la [página "Apps" de la Developer Console](https://developer.x.com/en/portal/projects-and-apps.html).
2. Haz clic en el icono "Keys and tokens" (🗝) junto a la App correspondiente.
3. Haz clic en el botón "Regenerate" junto al conjunto de claves y tokens que deseas regenerar.
Si prefieres regenerar tus Access Tokens o Bearer Tokens de forma programática, puedes hacerlo utilizando nuestros endpoints de autenticación.
* Si deseas regenerar tus Access Tokens, debes invalidar tus tokens usando el endpoint [POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token), y luego regenerar tus tokens usando el [flujo OAuth de 3 patas](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens).
* Si deseas regenerar tu Bearer Token, debes invalidar tu token usando el endpoint [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token), y luego regenerar tu token usando el endpoint [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token).
## Tener un archivo central para tus secretos
Tener un archivo como .ENV o cualquier otro tipo de archivo .yaml para contener tus secretos es una opción que puede ser útil, pero asegúrate de tener un archivo .gitignore robusto que pueda evitar que los confirmes accidentalmente en un repositorio git.
## Variables de entorno
Escribir código que utilice variables de entorno puede ser útil.
Un ejemplo de esto es el siguiente, escrito en Python:
```python theme={null}
import os
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")
```
Dentro de tu terminal, deberías escribir algo como esto:
```bash theme={null}
export CONSUMER_KEY='xxxxxxxxxxxxxxxxxxx'
export CONSUMER_SECRET='xxxxxxxxxxxxxxxxxxxxxxx'
```
## Código fuente y control de versiones
Los errores de seguridad más comunes que cometen los desarrolladores son tener API keys y tokens confirmados en el código fuente en sistemas de control de versiones accesibles como GitHub y BitBucket. Muchos de estos repositorios de código son de acceso público. Este error se comete tan a menudo en repositorios de código públicos que existen bots lucrativos que rastrean en busca de API keys.
* Usa variables de entorno del servidor. Al almacenar las API keys en variables de entorno, las mantienes fuera de tu código y del control de versiones. Esto también te permite usar diferentes claves para diferentes entornos con facilidad.
* Usa un archivo de configuración excluido del control de fuente. Añade el nombre del archivo a tu archivo [.gitignore](https://git-scm.com/docs/gitignore) para excluir el archivo del seguimiento del control de versiones.
* Si eliminas las API keys de tu código después de haber usado el control de versiones, las API keys probablemente sigan siendo accesibles al acceder a versiones anteriores de tu base de código. Regenera tus API keys, como se describe en la siguiente sección.
## Bases de datos
Si necesitas almacenar tus access tokens en una base de datos, ten en cuenta lo siguiente:
* Restringe el acceso a la base de datos de forma que los access tokens solo puedan ser leídos por el propietario del token.
* Restringe los privilegios de edición/escritura en la tabla de la base de datos para los access tokens; esto debe automatizarse con el sistema de gestión de claves.
* Cifra los access tokens antes de almacenarlos en cualquier data store.
## Herramientas de gestión de contraseñas
Herramientas de gestión de contraseñas como 1password o Last Pass pueden ser útiles para mantener tus claves y tokens en un lugar seguro. Es posible que quieras evitar compartir estos dentro de una herramienta de gestión de contraseñas compartida por el equipo.
## Almacenamiento web y cookies
Hay dos tipos de almacenamiento web: LocalStorage y SessionStorage. Estos se crearon como mejoras al uso de las Cookies, ya que la capacidad de almacenamiento del almacenamiento web es mucho mayor que la del almacenamiento de Cookies. Sin embargo, cada una de estas opciones de almacenamiento tiene diferentes pros y contras.
**Almacenamiento web: LocalStorage**
Cualquier cosa almacenada en el almacenamiento web local es persistente. Esto significa que los datos persistirán hasta que se eliminen explícitamente. Dependiendo de las necesidades de tu proyecto, puedes verlo como algo positivo. Sin embargo, debes tener cuidado al usar LocalStorage, ya que cualquier cambio/adición a los datos estará disponible en todas las visitas futuras a la página web en cuestión. Generalmente no recomendamos usar LocalStorage, aunque puede haber algunas excepciones. Si decides usar LocalStorage, es bueno saber que soporta la política del mismo origen, por lo que todos los datos almacenados aquí solo estarán disponibles a través del mismo origen. Un beneficio adicional de rendimiento al usar LocalStorage sería una disminución en el tráfico cliente-servidor, ya que los datos no tienen que enviarse de vuelta al servidor en cada solicitud HTTP.
**Almacenamiento web: SessionStorage**
SessionStorage es similar a LocalStorage, pero la diferencia clave es que SessionStorage no es persistente. Una vez que se cierra la ventana (o pestaña, dependiendo del navegador que estés usando) que se usó para escribir en SessionStorage, los datos se perderán. Esto es útil para restringir el acceso de lectura a tu token dentro de una sesión de usuario. Usar SessionStorage suele ser más preferible que LocalStorage cuando se piensa en términos de seguridad. Al igual que LocalStorage, las ventajas del soporte de la política del mismo origen y la disminución del tráfico cliente-servidor se aplican también a SessionStorage.
**Cookies**
Las cookies son la forma más tradicional de almacenar datos de sesión. Puedes establecer un tiempo de expiración para cada cookie, lo que permitiría la facilidad de revocación y restricción de acceso. Sin embargo, el tráfico cliente-servidor definitivamente aumentaría al usar cookies, ya que los datos se envían de vuelta al servidor en cada solicitud HTTP. Si decides usar cookies, debes protegerte contra el secuestro de sesión. Por defecto, las cookies se envían en texto plano sobre HTTP, lo que hace que su contenido sea vulnerable a la interceptación de paquetes y/o ataques man-in-the-middle donde los atacantes pueden modificar tu tráfico. Siempre debes hacer cumplir HTTPS para proteger tus datos en tránsito. Esto proporcionará confidencialidad, integridad (de los datos) y autenticación. Sin embargo, si tu aplicación o sitio web está disponible tanto a través de HTTP como de HTTPS, también deberás usar el flag 'Secure' en la cookie. Esto evitará que los atacantes puedan enviar enlaces a la versión HTTP de tu sitio a un usuario y escuchar la solicitud HTTP resultante generada.
Otra defensa secundaria contra el secuestro de sesión cuando se usan cookies sería validar la identidad del usuario de nuevo antes de que se realicen acciones de alto impacto. Otro flag a considerar para mejorar la seguridad de tus cookies sería el flag 'HttpOnly'. Este flag le dice al navegador que la cookie en cuestión solo será accesible desde el servidor especificado. Cualquier intento por parte de scripts del lado del cliente estaría prohibido por este flag, por lo tanto, ayudando a proteger contra la mayoría de los ataques de cross-site scripting (XSS).
# Iniciar sesión con X
Source: https://docs.x.com/es/fundamentals/authentication/guides/log-in-with-x
Implementa Iniciar sesión con X en sitios web y aplicaciones móviles utilizando el flujo de request token de OAuth 1.0a para autenticar usuarios y obtener access tokens.
Usa Iniciar sesión con X, también conocido como Sign in with X, para colocar un botón en tu sitio o aplicación que permita a los usuarios de X disfrutar de los beneficios de una cuenta de usuario registrada con tan solo un clic. Esto funciona en sitios web, iOS y aplicaciones móviles y de escritorio.
## Características
* Facilidad de uso — Un nuevo visitante a tu sitio solo tiene que hacer clic en dos botones para iniciar sesión por primera vez.
* Integración con X — El flujo de Iniciar sesión con X puede conceder autorización para usar las APIs de X en nombre de tus usuarios.
* Basado en OAuth — Existen numerosas bibliotecas cliente y códigos de ejemplo compatibles con la API de Iniciar sesión con X.
## Disponible para
* Navegadores — Si tus usuarios pueden acceder a un navegador, puedes integrar Iniciar sesión con X. Aprende sobre el flujo de inicio de sesión en el navegador.
* Dispositivos móviles — Cualquier dispositivo móvil con conexión web puede aprovechar Iniciar sesión con X. Aprende sobre el flujo de inicio de sesión móvil.
## Implementación de Iniciar sesión con X
Las implementaciones para navegador y web móvil de Iniciar sesión con X están basadas en OAuth. Esta página muestra las solicitudes necesarias para obtener un access token para el flujo de inicio de sesión.
Para usar el flujo "Iniciar sesión con X", ve a la [configuración de tu X app](/resources/fundamentals/developer-apps) y asegúrate de que la opción *"Allow this app to be used to Sign in with X?"* esté habilitada.
Esta página asume que el lector sabe cómo firmar solicitudes usando el protocolo OAuth 1.0a. Si quieres saber cómo firmar una solicitud, lee la página [Autorización de una solicitud](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request).
Si quieres comprobar la firma de las solicitudes en esta página, el consumer secret utilizado es: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg. Este valor es para propósitos de prueba y no funcionará para solicitudes reales.
Los tres pasos para implementar Iniciar sesión con X mediante la obtención de un request token, la redirección del usuario y la conversión de un request token en un access token se enumeran a continuación.
### Paso 1: Obtener un request token
Para iniciar un flujo de inicio de sesión, tu [X app](/resources/fundamentals/developer-apps) debe obtener un request token enviando un mensaje firmado a [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token). El único parámetro único en esta solicitud es oauth\_callback, que debe ser una versión codificada en URL de la URL a la que deseas que tu usuario sea redirigido cuando complete el paso 2. Los parámetros restantes son añadidos por el proceso de firma de OAuth.
**Nota:** Cualquier [URL de callback](/resources/fundamentals/developer-apps#callback-urls) que uses con el endpoint [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) deberá estar registrada dentro de la [configuración de la X app](/resources/fundamentals/developer-apps) en la [Developer Console](/resources/fundamentals/developer-portal).
**Solicitud de ejemplo (el encabezado Authorization ha sido dividido en varias líneas):**
```
POST /oauth/request_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization:
OAuth oauth_callback="http%3A%2F%2Flocalhost%2Fsign-in-with-twitter%2F",
oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="ea9ec8429b68d6b77cd5600adbbb0456",
oauth_signature="F1Li3tvehgcraF8DMJ7OyxO4w9Y%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_version="1.0"
```
Tu app debe examinar el estado HTTP de la respuesta. Cualquier valor distinto de 200 indica un error. El cuerpo de la respuesta contendrá los parámetros oauth\_token, oauth\_token\_secret y oauth\_callback\_confirmed. Tu app debe verificar que oauth\_callback\_confirmed sea true y almacenar los otros dos valores para los siguientes pasos.
**Respuesta de ejemplo (el cuerpo de la respuesta ha sido dividido en varias líneas):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:06 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 146
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI&
oauth_callback_confirmed=true
```
### Paso 2: Redirigir al usuario
El siguiente paso es dirigir al usuario a X para que pueda completar el flujo apropiado, como se describe en Flujo de inicio de sesión del navegador más abajo. Dirige al usuario a [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate), y el request token obtenido en el paso 1 debe pasarse como el parámetro oauth\_token.
La forma más fluida en que un sitio web puede implementar esto sería emitir una redirección HTTP 302 como respuesta a la solicitud original de "iniciar sesión". Las aplicaciones móviles y de escritorio deberían abrir una nueva ventana del navegador o dirigirse a la URL a través de una vista web incrustada.
**URL de ejemplo a la que redirigir:**
[https://api.x.com/oauth/authenticate?oauth\_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0](https://api.x.com/oauth/authenticate?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0)
El endpoint de inicio de sesión se comportará de una de tres maneras dependiendo del estado del usuario:
1. **Con sesión iniciada y aprobado**: Si el usuario ha iniciado sesión en x.com y ya ha aprobado la aplicación llamante, será autenticado inmediatamente y devuelto a la URL de callback con un OAuth request token válido. La redirección a x.com no es obvia para el usuario.
2. **Con sesión iniciada pero no aprobado**: Si el usuario ha iniciado sesión en x.com pero no ha aprobado la aplicación llamante, se mostrará una solicitud para compartir el acceso con la aplicación llamante. Después de aceptar la solicitud de autorización, el usuario será redirigido a la URL de callback con un OAuth request token válido.
3. **Sin sesión iniciada**: Si el usuario no ha iniciado sesión en x.com, se le pedirá que ingrese sus credenciales y otorgue acceso a la aplicación para acceder a su información en la misma pantalla. Una vez iniciada la sesión, el usuario será devuelto a la URL de callback con un OAuth request token válido.
Tras una autenticación exitosa, tu callback\_url recibirá una solicitud que contiene los parámetros oauth\_token y oauth\_verifier. Tu aplicación debe verificar que el token coincida con el request token recibido en el paso 1.
**Solicitud desde la redirección del cliente (parámetros de querystring divididos en varias líneas):**
```
GET /sign-in-with-twitter/?
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.5 (KHTML, like Gecko) Chrome/16.0.891.1 Safari/535.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://localhost/sign-in-with-twitter/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
```
### Paso 3: Convertir el request token en un access token
Para convertir el request token en un access token utilizable, tu aplicación debe realizar una solicitud al endpoint [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token), conteniendo el valor de oauth\_verifier obtenido en el paso 2. El request token también se pasa en la parte oauth\_token del encabezado, pero esto se habrá añadido durante el proceso de firma.
**Solicitud de ejemplo (encabezado Authorization dividido en varias líneas):**
```
POST /oauth/access_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
oauth_version="1.0"
Content-Length: 57
Content-Type: application/x-www-form-urlencoded
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
```
Una respuesta exitosa contiene los parámetros oauth\_token y oauth\_token\_secret. El token y el token secret deben almacenarse y usarse para futuras solicitudes autenticadas a la X API. Para determinar la identidad del usuario, usa [GET account/verify\_credentials](https://dev.x.com/rest/reference/get/account/verify_credentials).
**Respuesta de ejemplo (el cuerpo de la respuesta ha sido dividido en varias líneas):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:08 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 157
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4&
oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo
```
### Recursos de Iniciar sesión con X
#### Bibliotecas cliente
Las bibliotecas cliente listadas en [Bibliotecas de X](/resources/tools-and-libraries) te ayudarán a implementar Iniciar sesión con X. Usa el endpoint /oauth/authenticate, como se describe en los pasos anteriores.
#### Brand Toolkit
X preferiría que tu aplicación utilice el [Brand Toolkit oficial de X](https://about.x.com/en/who-we-are/brand-toolkit) para mantener una imagen de marca coherente. Guarda estos recursos y úsalos al crear un botón "Iniciar sesión con X".
El flujo de inicio de sesión en el navegador es apropiado para sitios web y aplicaciones que pueden abrir o incrustar un navegador web. En un nivel muy alto:
* La aplicación muestra un enlace o botón "Iniciar sesión con X".
* El usuario hace clic en el botón de iniciar sesión.
* El navegador web actual se redirige a X (o se abre un nuevo navegador y se dirige a X).
* El usuario completa un paso de inicio de sesión y autorización en X si es necesario.
* X redirige de vuelta a una URL bajo el control de la aplicación, pasando la información de autorización del usuario.
X realiza un seguimiento de las autorizaciones, por lo que para los usuarios que ya han iniciado sesión en X.com y que han autorizado la aplicación, no se muestra ninguna interfaz: en su lugar, se les redirige automáticamente de vuelta a la aplicación.
### Flujo de escritorio
Para demostrar los flujos, imagina que el sitio web que se muestra arriba ("The greatest website ever created") ha implementado esta API, como se muestra por el botón Iniciar sesión con X en la página de destino.
Cuando el usuario hace clic en el botón Iniciar sesión, la página que ve depende de si ha iniciado sesión y si ha permitido previamente que la aplicación acceda a su cuenta.
Cuando el usuario ha iniciado sesión en x.com pero no ha otorgado acceso, se muestra una lista de permisos solicitados, junto con los botones Iniciar sesión y Cancelar.
Cuando el usuario no ha iniciado sesión en x.com, se mostrarán campos de entrada para nombre de usuario y contraseña. Ten en cuenta que incluso si el usuario ya ha otorgado acceso a la aplicación, la lista de permisos aún se mostrará.
Después de que el usuario ingrese credenciales válidas (si es necesario) y haga clic en "Iniciar sesión", X redirigirá al usuario al sitio web que inició el flujo de inicio de sesión.
En el caso en que el usuario ya haya iniciado sesión en x.com y haya otorgado acceso al sitio web, esta redirección ocurre inmediatamente.
El flujo de la interfaz para navegadores web móviles funciona exactamente como el flujo de inicio de sesión del navegador, pero está optimizado para navegadores móviles.
A continuación se muestran capturas de pantalla de las pantallas con sesión iniciada, sin sesión iniciada y de redirección:
# Conexión a la X API mediante TLS
Source: https://docs.x.com/es/fundamentals/authentication/guides/tls
Conéctate de forma segura a la X API a través de TLS 1.2, con orientación sobre almacenes de raíz de confianza, comprobaciones de revocación de certificados y prácticas de verificación HTTPS.
Las conexiones TLS son necesarias para acceder a los endpoints de la X API. La comunicación a través de TLS preserva la privacidad y la seguridad del usuario al proteger la información entre el usuario y la X API mientras viaja a través de Internet público. Las conexiones a la X API requieren TLS versión 1.2.
## Verificación
### Usa un root store actualizado
Es importante que tu aplicación o biblioteca utilice un root store confiable y actualizado al verificar el certificado de X. Cuando sea posible, usar el root store proporcionado por tu sistema operativo puede ser el enfoque más simple. Alternativamente, el [root store de Mozilla (NSS)](https://www.mozilla.org/en-US/about/governance/policies/security-group/certs/) se mantiene de forma pública y transparente. Curl también proporciona [una versión de este store en formato PEM](https://curl.haxx.se/docs/caextract.html).
X actualmente emite la mayor parte de nuestros certificados desde el [DigiCert High Assurance EV Root CA](https://www.digicert.com/digicert-root-certificates.htm), pero esto no es cierto para el 100% de los certificados relacionados con X y puede no serlo para siempre, por lo que confiar solo en las raíces de Digicert utilizadas actualmente puede llevar a problemas con tu app en el futuro.
### Comprueba las CRLs y el estado OCSP[](#check-crls-and-the-ocsp-status "Permalink to this headline")
Muchas aplicaciones no comprueban la lista de revocación de certificados (Certificate Revocation List) para los certificados devueltos o dependen del sistema operativo para hacerlo. Asegúrate de que tu aplicación o biblioteca TLS esté configurada para forzar la verificación CRL y OCSP (Online Certificate Status Protocol) antes de aceptar el certificado de X.
### CDNs[](#cdns "Permalink to this headline")
Al mostrar Tweets que contienen medios, usa el atributo `media_url_https` para las URLs HTTPS que se utilizarán al mostrar imágenes. En el futuro, todas las URLs servidas desde los endpoints de la API proporcionarán rutas HTTPS.
## Proporciona una indicación del estado de seguridad
Si es posible, deberías mostrar una indicación del estado actual entre tu aplicación y X. Algunos navegadores web indican esto ofreciendo un icono de candado, mientras que otros indican el estado de la conexión actual con mensajes descriptivos.
# Mapeo de autenticación de X API v2
Source: https://docs.x.com/es/fundamentals/authentication/guides/v2-authentication-mapping
La siguiente tabla ilustra qué endpoints de v2 se corresponden con qué métodos de autenticación. Documentación para la plataforma de desarrolladores de X que cubre la autenticación v2.
La siguiente tabla ilustra qué endpoints de v2 se corresponden con qué métodos de autenticación.
| | | | |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **Endpoint** | **OAuth 1.0a User Context** | **OAuth 2.0** **App Only ** | **OAuth 2.0 Authorization Code con PKCE** |
| [Búsqueda de Tweets](/x-api/posts/lookup/introduction)
Scope |
# API Key y Secret
Source: https://docs.x.com/es/fundamentals/authentication/oauth-1-0a/api-key-and-secret
Aprende qué son la API Key y Secret de X (consumer key y secret), cómo crearlos en el Developer Portal y cómo regenerarlos o rotarlos.
### API Key y Secret
La API Key y Secret (también conocidas como Consumer Key y Secret) son las credenciales más fundamentales necesarias para acceder a la X API. Estas credenciales funcionan como el nombre de usuario y la contraseña de tu X App, y las utiliza la X API para saber desde qué App proceden las solicitudes.
Estas credenciales pueden ser utilizadas por los [endpoints de autenticación](/resources/fundamentals/authentication/api-reference) para generar credenciales adicionales, como [Access Tokens y Secrets de usuario](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret) y [Bearer Tokens](/resources/fundamentals/authentication/oauth-2-0/bearer-tokens). También necesitas usar estas credenciales junto con los Access Tokens y otros parámetros de autorización para [autorizar solicitudes](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request) que requieran autenticación de OAuth 1.0a User Context.
#### Cómo obtener una API Key y Secret
Para obtener una API Key y Secret de X, sigue estos pasos:
1. [Regístrate para una cuenta de desarrollador de X](https://developer.x.com/en/apply-for-access)
2. Crea una [X App](/resources/fundamentals/developer-apps) dentro de la [Developer Console](/resources/fundamentals/developer-portal). Ten en cuenta que si deseas usar la [X API v2](/x-api/introduction), debes usar claves y tokens de una App de desarrollador.
Cuando crees tu X App, se te presentarán tu API Key y Secret, junto con un Bearer Token. Ten en cuenta que solo mostramos estas credenciales una vez, así que asegúrate de guardarlas en tu gestor de contraseñas o en algún lugar seguro.
Tenemos más recomendaciones sobre cómo manejar tus claves y tokens en nuestra página de [mejores prácticas de autenticación](/resources/fundamentals/authentication/guides/authentication-best-practices), incluidos detalles sobre qué debes hacer si tus credenciales han quedado comprometidas.
#### Cómo encontrar y regenerar tu API Key y Secret después de crear la App
Si ya has creado una App y necesitas encontrar o regenerar tu API Key y Secret, sigue estos pasos:
1. Navega a la Developer Console
2. Expande el desplegable 'Apps' en el sidenav
3. Abre la App asociada con la API Key y Secret que deseas encontrar o regenerar
4. Navega a la pestaña Keys and tokens
Desde ahí, encontrarás todas las credenciales asociadas a tu App.
#### Cómo usar tu API Key y Secret
Si solo estás explorando la Plataforma de Desarrolladores de X, te recomendamos que utilices una [herramienta o biblioteca](/resources/tools-and-libraries) para ver qué está disponible en la plataforma. Estas herramientas manejan la autenticación de forma elegante y pueden ahorrarte mucho tiempo y frustración. Recomendamos específicamente [empezar con Postman](/tutorials/postman-getting-started) o [Insomnia](https://insomnia.rest/) para desarrolladores principiantes.
Si te interesa construir una solicitud desde cero, lee nuestra guía sobre [autorización de una solicitud OAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request).
# Autorización de una solicitud
Source: https://docs.x.com/es/fundamentals/authentication/oauth-1-0a/authorizing-a-request
Construye un encabezado Authorization de OAuth 1.0a para firmar solicitudes a la X API, incluyendo los campos consumer key, nonce, signature, timestamp, token y version.
### Autorización de una solicitud
El propósito de este documento es mostrarte cómo modificar las solicitudes HTTP con el fin de enviar solicitudes autorizadas a la X API.
Todas las APIs de X se basan en el protocolo HTTP. Esto significa que cualquier software que escribas que use las APIs de X envía una serie de mensajes estructurados a los servidores de X. Por ejemplo, una solicitud para publicar el texto "**Hello Ladies + Gentlemen, a signed OAuth request!**" como un Tweet se verá algo así:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
Cualquier biblioteca HTTP debería poder generar y emitir la solicitud anterior con una dificultad mínima. Sin embargo, la solicitud anterior se considera inválida, ya que no hay forma de saber:
1. Qué aplicación está haciendo la solicitud
2. En nombre de qué usuario se está publicando la solicitud
3. Si el usuario ha otorgado a la aplicación autorización para publicar en su nombre
4. Si la solicitud ha sido manipulada por un tercero durante el tránsito
Para permitir que las aplicaciones proporcionen esta información, la API de X se basa en el [protocolo OAuth 1.0a](http://tools.ietf.org/html/rfc5849). A un nivel muy simplificado, la implementación de X requiere que las solicitudes que necesitan autorización contengan un encabezado HTTP Authorization adicional con información suficiente para responder a las preguntas enumeradas anteriormente. Una versión de la solicitud HTTP mostrada arriba, modificada para incluir este encabezado, se ve así (normalmente el encabezado Authorization debería estar en una sola línea, pero se ha dividido aquí para mayor legibilidad):
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth\_consumer\_key="xvz1evFS4wEEPTGEFPHBog",
oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth\_signature\_method="HMAC-SHA1",
oauth_timestamp="1318622958",
oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
oauth_version="1.0"
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
Cuando se creó esta solicitud, habría sido aceptada por la X API como válida.
Si este proceso de firma parece estar fuera del alcance de tu integración, considera usar [Web Intents](https://dev.x.com/web/intents), que no necesitan usar OAuth para interactuar con la X API.
**Recopilando parámetros**
Deberías ver que el encabezado contiene 7 pares clave/valor, donde todas las claves comienzan con la cadena "oauth\_". Para cualquier solicitud a la X API, recopilar estos 7 valores y crear un encabezado similar te permitirá especificar la autorización para la solicitud. Cómo se generó cada valor se describe a continuación:
**Consumer key**
La oauth\_consumer\_key identifica qué aplicación está realizando la solicitud. Obtén este valor desde la página de configuración de tu [X app](/resources/fundamentals/developer-apps) en la [Developer Console](/resources/fundamentals/developer-portal).
| | |
| :------------------- | :--------------------- |
| oauth\_consumer\_key | xvz1evFS4wEEPTGEFPHBog |
**Nonce**
El parámetro oauth\_nonce es un token único que tu aplicación debe generar para cada solicitud única. X utilizará este valor para determinar si una solicitud se ha enviado varias veces. El valor para esta solicitud se generó codificando en base64 32 bytes de datos aleatorios y eliminando todos los caracteres que no fueran palabras, pero cualquier enfoque que produzca una cadena alfanumérica relativamente aleatoria debería estar bien aquí.
| | |
| :----------- | :----------------------------------------- |
| oauth\_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
**Signature**
El parámetro oauth\_signature contiene un valor que se genera ejecutando todos los demás parámetros de la solicitud y dos valores secretos a través de un algoritmo de firma. El propósito de la firma es que X pueda verificar que la solicitud no ha sido modificada durante el tránsito, verificar la aplicación que envía la solicitud y verificar que la aplicación tiene autorización para interactuar con la cuenta del usuario.
El proceso para calcular la oauth\_signature para esta solicitud se describe en [Creación de una firma](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature).
| | |
| :--------------- | :--------------------------- |
| oauth\_signature | tnnArxj06cWHq44gCs1OSKk/jLY= |
**Signature method**
El oauth\_signature\_method utilizado por X es HMAC-SHA1. Este valor debe usarse para cualquier solicitud autorizada enviada a la API de X.
| | |
| :----------------------- | :-------- |
| oauth\_signature\_method | HMAC-SHA1 |
**Timestamp**
El parámetro oauth\_timestamp indica cuándo se creó la solicitud. Este valor debe ser el número de segundos desde el epoch Unix en el momento en que se genera la solicitud, y debería ser fácil de generar en la mayoría de los lenguajes de programación. X rechazará las solicitudes creadas demasiado tiempo en el pasado, por lo que es importante mantener el reloj del ordenador que genera las solicitudes sincronizado con NTP.
| | |
| :--------------- | :--------- |
| oauth\_timestamp | 1318622958 |
**Token**
El parámetro oauth\_token normalmente representa el permiso de un usuario para compartir el acceso a su cuenta con tu aplicación. Hay algunas solicitudes de autenticación en las que este valor no se pasa o es una forma diferente de token, pero se cubren en detalle en [Obtención de access tokens](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens). Para la mayoría de las solicitudes de propósito general, usarás lo que se denomina un **access token**.
Puedes generar un [access token](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) válido para tu cuenta en la página de configuración de tu [X app](/resources/fundamentals/developer-apps) en la [Developer Console](/resources/fundamentals/developer-portal).
| | |
| :----------- | :------------------------------------------------- |
| oauth\_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
**Version**
El parámetro oauth\_version siempre debe ser 1.0 para cualquier solicitud enviada a la X API.
| | |
| :------------- | :-- |
| oauth\_version | 1.0 |
#### Construyendo la cadena del encabezado
Para construir la cadena del encabezado, imagina escribir a una cadena llamada DST.
1. Añade la cadena "OAuth " (incluyendo el espacio al final) a DST.
2. Para cada par clave/valor de los 7 parámetros listados anteriormente:
1. [Codifica por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) la clave y añádela a DST.
2. Añade el carácter igual '=' a DST.
3. Añade una comilla doble '"' a DST.
4. [Codifica por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) el valor y añádelo a DST.
5. Añade una comilla doble '"' a DST.
6. Si quedan pares clave/valor, añade una coma ',' y un espacio ' ' a DST.
Presta especial atención a la codificación por porcentaje de los valores al construir esta cadena. Por ejemplo, el valor oauth\_signature de tnnArxj06cWHq44gCs1OSKk/jLY= debe codificarse como tnnArxj06cWHq44gCs1OSKk%2FjLY%3D.
Al realizar estos pasos con los parámetros recopilados anteriormente, se obtiene la siguiente cadena:
```
OAuth oauth\_consumer\_key="xvz1evFS4wEEPTGEFPHBog", oauth\_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg", oauth\_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth\_signature\_method="HMAC-SHA1", oauth\_timestamp="1318622958", oauth\_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0"
```
Este valor debe establecerse como el encabezado Authorization de la solicitud.
# Creación de una firma
Source: https://docs.x.com/es/fundamentals/authentication/oauth-1-0a/creating-a-signature
Genera una firma HMAC-SHA1 de OAuth 1.0a para las solicitudes a la X API recopilando parámetros, construyendo la signature base string y firmando con tus claves.
### Creación de una firma
Esta página explica cómo generar una firma HMAC-SHA1 de OAuth 1.0a para una solicitud HTTP. Esta firma será adecuada para pasar a la X API como parte de una solicitud autorizada, como se describe en [autorización de una solicitud.](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request)
La solicitud utilizada para demostrar la firma es un POST a [https://api.x.com/1.1/statuses/update.json](https://api.x.com/1.1/statuses/update.json). La solicitud sin procesar se ve así:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
**Recopilación del método de solicitud y la URL**
Para producir una firma, comienza por determinar el método HTTP y la URL de la solicitud. Estos dos son conocidos al crear la solicitud, por lo que son fáciles de obtener.
El método de solicitud casi siempre será GET o POST para las solicitudes a la X API.
| | |
| :---------- | :--- |
| Método HTTP | POST |
La URL base es la URL a la que se dirige la solicitud, menos cualquier query string o parámetros hash. Es importante utilizar el protocolo correcto aquí, así que asegúrate de que la parte "https\://" de la URL coincida con la solicitud real enviada a la API.
| | |
| :------- | :--------------------------------------------------------------------------------------- |
| URL base | [https://api.x.com/1.1/statuses/update.json](https://api.x.com/1.1/statuses/update.json) |
#### Recopilación de parámetros
A continuación, reúne todos los parámetros incluidos en la solicitud. Existen dos ubicaciones para estos parámetros adicionales: la URL (como parte del query string) y el cuerpo de la solicitud. La solicitud de ejemplo incluye un único parámetro en ambas ubicaciones:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
Una solicitud HTTP tiene parámetros que están codificados en URL, pero debes recopilar los valores sin procesar. Además de los parámetros de la solicitud, cada parámetro oauth\_\* debe incluirse en la firma, así que recopila también esos. Aquí están los parámetros de [autorización de una solicitud](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request):
| | |
| :----------------------- | :------------------------------------------------- |
| status | Hello Ladies + Gentlemen, a signed OAuth request! |
| include\_entities | true |
| oauth\_consumer\_key | xvz1evFS4wEEPTGEFPHBog |
| oauth\_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
| oauth\_signature\_method | HMAC-SHA1 |
| oauth\_timestamp | 1318622958 |
| oauth\_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
| oauth\_version | 1.0 |
Estos valores deben codificarse en una única cadena, que se usará más adelante. El proceso para construir la cadena es muy específico:
1. [Codifica por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) cada clave y valor que se vaya a firmar.
2. Ordena la lista de parámetros alfabéticamente [\[1\]](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature) por clave codificada [\[2\]](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature).
3. Para cada par clave/valor:
4. Añade la clave codificada a la cadena de salida.
5. Añade el carácter '=' a la cadena de salida.
6. Añade el valor codificado a la cadena de salida.
7. Si quedan más pares clave/valor, añade un carácter '&' a la cadena de salida.
\[1] La especificación de OAuth indica ordenar lexicográficamente, que es el ordenamiento alfabético predeterminado para muchas bibliotecas.
\[2] En el caso de dos parámetros con la misma clave codificada, la especificación de OAuth indica continuar ordenando en función del valor. Sin embargo, X no acepta claves duplicadas en las solicitudes a la API
**Cadena de parámetros**
La siguiente *cadena de parámetros* se producirá al repetir estos pasos con los parámetros recopilados anteriormente:
| status | Hello Ladies + Gentlemen, a signed OAuth request! |
| :----------------------- | :------------------------------------------------- |
| `include_entities` | true |
| `oauth_consumer_key` | xvz1evFS4wEEPTGEFPHBog |
| `oauth_nonce` | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
| `oauth_signature_method` | HMAC-SHA1 |
| `oauth_timestamp` | 1318622958 |
| `oauth_token` | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
| `oauth_version` | 1.0 |
#### Creación de la signature base string
Los tres valores recopilados hasta ahora deben unirse para formar una sola cadena, a partir de la cual se generará la firma. Esto se llama la **signature base string** en la especificación de OAuth.
Para codificar el método HTTP, la URL base y la cadena de parámetros en una sola cadena:
1. Convierte el método HTTP a mayúsculas y establece la cadena de salida igual a este valor.
2. Añade el carácter '&' a la cadena de salida.
3. [Codifica por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) la URL y añádela a la cadena de salida.
4. Añade el carácter '&' a la cadena de salida.
5. [Codifica por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) la cadena de parámetros y añádela a la cadena de salida.
Esto producirá la siguiente *signature base string*:
```
POST&https%3A%2F%2Fapi.x.com%2F1.1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521
```
Asegúrate de codificar por porcentaje la cadena de parámetros. La signature base string debe contener exactamente 2 caracteres de ampersand '&'. Los caracteres de porcentaje '%' en la cadena de parámetros deben codificarse como %25 en la signature base string.
#### Obtención de una signing key
Las últimas piezas de datos a recopilar son secretos que identifican la [X app](/resources/fundamentals/developer-apps) que realiza la solicitud y el usuario en cuyo nombre se realiza la solicitud. Es muy importante tener en cuenta que estos valores son increíblemente sensibles y nunca deben compartirse con nadie.
El valor que identifica tu app ante X se llama **consumer secret** y se puede encontrar en la [Developer Console](/resources/fundamentals/developer-portal) viendo la [página de detalles de la app](/resources/fundamentals/developer-apps). Este será el mismo para cada solicitud que envíe tu X app.
| | |
| :-------------- | :------------------------------------------ |
| Consumer secret | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw |
El valor que identifica la cuenta en cuyo nombre actúa tu aplicación se llama **OAuth token secret**. Este valor puede obtenerse de varias maneras, todas descritas en [obtención de access tokens](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens).
| | |
| :----------------- | :---------------------------------------- |
| OAuth token secret | LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
Una vez más, es muy importante mantener estos valores privados de tu aplicación. Si crees que tus valores han quedado comprometidos, regenera tus tokens (los tokens en esta página se han marcado como no válidos para solicitudes reales).
Ambos valores deben combinarse para formar una **signing key** que se usará para generar la firma. La signing key es simplemente el token secret [codificado por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters):
Ten en cuenta que hay algunos flujos, como cuando se obtiene un [request token](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens), donde el token secret aún no se conoce. En este caso, la signing key debe consistir en el **consumer secret** [codificado por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) seguido de un carácter ampersand '&'.
| | |
| :---------- | :------------------------------------------------------------------------------------- |
| Signing key | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw\&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
#### Cálculo de la firma
Finalmente, la firma se calcula pasando la signature base string y la signing key al algoritmo de hash HMAC-SHA1. Los detalles del algoritmo se explican como la función hash\_hmac.
La salida de la función de firma HMAC es una cadena binaria. Esta debe codificarse en base64 para producir la cadena de firma. Por ejemplo, la salida dada la base string y la signing key proporcionadas en esta página es 2E CF 77 84 98 99 6D 0D DA 90 5D C7 17 7C 75 07 3F 3F CD 4E. Ese valor, cuando se convierte a base64, es la firma OAuth para esta solicitud:
| | |
| :---------- | :--------------------------- |
| Firma OAuth | Ls93hJiZbQ3akF3HF3x1Bz8/zU4= |
# OAuth Echo
Source: https://docs.x.com/es/fundamentals/authentication/oauth-1-0a/oauth-echo
Usa OAuth Echo para delegar de forma segura la autenticación de X a un proveedor de medios de terceros para las cargas, utilizando los encabezados x-auth-service-provider y verify-credentials.
### OAuth Echo
OAuth Echo es un medio para delegar de forma segura la autorización OAuth a un tercero mientras se interactúa con una API.
Hay cuatro partes involucradas en esta interacción:
* **el Usuario**, que está usando X a través de una aplicación de X particular y autorizada
* **el Consumer**, o la aplicación de X que está intentando interactuar con el proveedor de medios de terceros (por ejemplo, el sitio para compartir fotos)
* **el Delegator**, o el proveedor de medios de terceros
* **el Service Provider**, también conocido como el propio X
Esencialmente, prepara una solicitud para que el delegator la envíe a la X API en nombre de una aplicación y un usuario. Añade lo que de otro modo sería una solicitud OAuth firmada dentro de un encabezado HTTP y pide al delegator que envíe esa solicitud a X después de completar la operación intermedia.
Aquí hay un ejemplo: el usuario quiere subir una foto. El Consumer va a llamar a upload en el Delegator con un POST. El POST debe contener la imagen, pero también debe contener dos elementos adicionales como encabezados HTTP:
* `x-auth-service-provider` — efectivamente, este es el realm al que se debe enviar la delegación de identidad — en el caso de X, establécelo en [https://api.x.com/1.1/account/verify\_credentials.json](https://api.x.com/1.1/account/verify_credentials.json). Las integraciones de X basadas en iOS5 añadirán un parámetro application\_id adicional a esta URL que también se usará para calcular la oauth\_signature utilizada en x-verify-credentials-authorization.
* `x-verify-credentials-authorization` — El Consumer debe crear todos los parámetros OAuth necesarios para poder llamar a [https://api.x.com/1.1/account/verify\_credentials.json](https://api.x.com/1.1/account/verify_credentials.json) usando OAuth en el encabezado HTTP (por ejemplo, debería verse como OAuth oauth\_consumer\_key="...", oauth\_token="...", oauth\_signature\_method="...", oauth\_signature="...", oauth\_timestamp="...", oauth\_nonce="...", oauth\_version="..." ).
Ten en cuenta que todo el período de la transacción debe ocurrir dentro de un tiempo en el que el `oauth_timestamp` siga siendo válido.
Alternativamente, en lugar de enviar estos dos parámetros en el encabezado, podrían enviarse en el POST como x\_auth\_service\_provider y x\_verify\_credentials\_authorization — en este caso, recuerda escapar e incluir los parámetros en la signature base string de OAuth — similar a codificar parámetros en cualquier solicitud. Es mejor usar encabezados HTTP para mantener las operaciones lo más separadas posible.
El objetivo del Delegator, en este punto, es verificar que el usuario es quien dice ser antes de guardar el medio. Una vez que el Delegator reciba todos los datos anteriores a través de su método upload, debe almacenar temporalmente la imagen y luego construir una llamada al endpoint especificado en el encabezado x-auth-service-provider — en este caso, [https://api.x.com/1.1/account/verify\_credentials.json](https://api.x.com/1.1/account/verify_credentials.json), usando el mismo encabezado de autenticación OAuth proporcionado por el Consumer en el encabezado x-verify-credentials-authorization.
#### Mejores prácticas de OAuth Echo
Usa la URL proporcionada por `x-auth-service-provider` para realizar la búsqueda, *no* un valor codificado de forma fija. Apple iOS, por ejemplo, añade un parámetro application\_id adicional a todas las solicitudes OAuth, y su existencia debe mantenerse en cada etapa de OAuth Echo.
Para la parte de la autorización OAuth, toma el valor del encabezado en x-verify-credentials-authorization y colócalo en su propio encabezado Authorization para su llamada al service provider. Para mayor seguridad, confirma que el valor en `x-auth-service-provider` es el que debería ser.
* Si el Service Provider devuelve un HTTP 200, entonces bien. El Delegator debe almacenar permanentemente la imagen, generar una URL y devolverla.
* Si el Service Provider no devuelve un HTTP 200, entonces descarta la imagen y devuelve un error al Consumer.
# Obtención de Access Tokens usando el flujo OAuth de 3 patas
Source: https://docs.x.com/es/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens
Recorre el flujo OAuth 1.0a de 3 patas para obtener user access tokens para la X API usando los endpoints request_token, authorize y access_token.
### Obtención de access tokens usando el flujo OAuth de 3 patas
Para realizar acciones en nombre de otro usuario, necesitarás obtener sus access tokens. Los access tokens especifican la cuenta de X en cuyo nombre se realiza la solicitud, por lo que para obtenerlos, primero necesitarán concederte acceso. Estos tokens no caducan, pero pueden ser revocados por el usuario en cualquier momento.
X te permite obtener user access tokens a través del flujo OAuth de 3 patas, que permite a tu aplicación obtener un **access token** y un access token secret redirigiendo a un usuario a X y haciendo que autorice tu aplicación. Este flujo es casi idéntico al flujo descrito en [implementar Iniciar sesión con X](/resources/fundamentals/authentication/guides/log-in-with-x), con dos excepciones:
* Se usa el endpoint [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) en lugar de [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate).
* Al usuario **siempre** se le pedirá que autorice el acceso a tu aplicación, incluso si el acceso fue previamente otorgado.
Antes de empezar, deberás revisar los permisos de tu [aplicación](/resources/fundamentals/developer-apps) y conocer las consumer keys y la URL de callback. Si no tienes una URL de callback o una interfaz accesible públicamente, considera usar [autorización basada en PIN](/resources/fundamentals/authentication/oauth-1-0a/pin-based-oauth), que está pensada para aplicaciones que no pueden acceder o incrustar un navegador web para redirigir al usuario después de la autorización.
Los posibles estados para la interacción de inicio de sesión de 3 patas se ilustran en el siguiente diagrama de flujo:

#### Descripción general del proceso
A alto nivel, el proceso OAuth de 3 patas hará lo siguiente:
1. Crear una solicitud para que una aplicación consumer obtenga un request token.
2. Hacer que el usuario se autentique y enviar a la aplicación consumer un request token.
3. Convertir el request token en un user access token utilizable.
**Aclaración de terminología**
En la guía siguiente, es posible que veas diferentes términos que se refieren a lo mismo.
**Credenciales del cliente:**
* App Key === API Key === Consumer API Key === Consumer Key === Customer Key === `oauth_consumer_key`
* App Key Secret === API Secret Key === Consumer Secret === Consumer Key === Customer Key === `oauth_consumer_secret`
* Callback URL === `oauth_callback`
**Credenciales temporales:**
* Request Token === `oauth_token`
* Request Token Secret === `oauth_token_secret`
* oauth\_verifier
**Credenciales del token:**
* Access token === Token === `oauth_token` resultante
* Access token secret === Token Secret === `oauth_token_secret` resultante
#### Pasos detallados
**Paso 1: [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token)**
Crea una solicitud para que una aplicación consumer obtenga un request token.
El único parámetro único en esta solicitud es oauth\_callback, que debe ser una versión [codificada en URL](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) de la URL a la que deseas que tu usuario sea redirigido cuando complete el paso 2. Los parámetros restantes son añadidos por el proceso de firma OAuth.
Ten en cuenta que cualquier URL de callback que uses con el endpoint [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) deberá estar configurada dentro de la configuración de tu [App de desarrollador](/resources/fundamentals/developer-apps) en la página de detalles de la app de la Developer Console.
**La solicitud incluye:**
`oauth_callback="https%3A%2F%2FyourCallbackUrl.com"`
`oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w" `
Tu app debe examinar el estado HTTP de la respuesta. Cualquier valor distinto de 200 indica un error. El cuerpo de la respuesta contendrá los parámetros `oauth_token`, `oauth_token_secret` y `oauth_callback_confirmed`. Tu app debe verificar que `oauth_callback_confirmed` sea true y almacenar los otros dos valores para los siguientes pasos.
**La respuesta incluye**
`oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
`oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI`
`oauth_callback_confirmed=true`
**Paso 2: [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize)**
Haz que el usuario se autentique y envía a la aplicación consumer un request token.
**URL de ejemplo a la que redirigir al usuario:**
`https://api.x.com/oauth/authorize?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
Tras una autenticación exitosa, tu `callback_url` recibirá una solicitud que contiene los parámetros `oauth_token` y `oauth_verifier`. Tu aplicación debe verificar que el token coincida con el request token recibido en el paso 1.
**Solicitud desde la redirección del cliente:**
`https://yourCallbackUrl.com?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY`
**Paso 3: [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token)**
Convierte el request token en un access token utilizable.
Para convertir el request token en un access token utilizable, tu aplicación debe realizar una solicitud al endpoint [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token), conteniendo el valor `oauth_verifier` obtenido en el paso 2. El request token también se pasa en la parte `oauth_token` del encabezado, pero esto se habrá añadido durante el proceso de firma.
**La solicitud incluye:**
`POST /oauth/access_token`
`oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w`
`oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
`oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY`
Una respuesta exitosa contiene los parámetros `oauth_token`, `oauth_token_secret`. El token y el token secret deben almacenarse y usarse para futuras solicitudes autenticadas a la X API. Para determinar la identidad del usuario, usa [GET account/verify\_credentials](/resources/fundamentals/authentication/api-reference).
**La respuesta incluye:**
`oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4`
`oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo`
**Uso de estas credenciales para solicitudes que requieren OAuth 1.0a (application-user)**
Ahora que has obtenido los user access tokens, puedes usarlos para acceder a ciertas APIs como [POST statuses/update](/x-api/posts/manage-tweets/introduction) para crear Tweets en nombre de los usuarios.
**La solicitud incluye:**
`POST statuses/update.json`
`oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w`
`oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4`
#### Caso de uso de ejemplo
El flujo estándar está basado en la web y utiliza el flujo de autorización OAuth de 3 patas. Las capturas de pantalla mostradas aquí son parte de un ejemplo cuyo código fuente puedes ver en [https://github.com/xdevplatform/twauth-web](https://github.com/xdevplatform/twauth-web).
En algún punto de tu aplicación, querrás redirigir a X para autorizar tu aplicación.
Cuando rediriges a X con el request token, se le pedirá al usuario que autorice tu aplicación.
Tras autorizar tu aplicación, el usuario será redirigido a la URL de callback proporcionada cuando generaste el request token. Utilizarás esto para obtener el access token permanente para este usuario y almacenarlo localmente.
# Codificación por porcentaje de parámetros
Source: https://docs.x.com/es/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters
Aplica la codificación por porcentaje según RFC 3986 a los parámetros de OAuth 1.0a para las solicitudes a la X API, con reglas para caracteres reservados y ejemplos de codificación de URL.
### Codificación por porcentaje de parámetros
Partes de la X API, en particular las que tratan con firmas OAuth, requieren que las cadenas estén codificadas de acuerdo con la [RFC 3986, Sección 2.1](http://tools.ietf.org/html/rfc3986#section-2.1). Dado que muchas implementaciones de algoritmos de codificación de URL no son totalmente compatibles con RFC 3986, las codificaciones incorrectas son la causa de muchos errores de firma OAuth. Por esta razón, el algoritmo exacto de firma a usar se cubre en esta página.
Esta página cubre el proceso de codificación de URL descrito en [RFC 3986, Sección 2.1](http://tools.ietf.org/html/rfc3986#section-2.1). Te animamos a consultar esa especificación en caso de cualquier ambigüedad o conflicto con este documento.
#### Codificación de una cadena
El siguiente algoritmo asume que estás codificando una cadena SRC copiando sus valores byte a byte a una cadena DST.
**Paso 1: Mientras SRC contenga bytes no leídos, lee el siguiente byte (8 bits) de SRC.** Normalmente, esto se considera un carácter, pero en el caso de codificaciones donde un carácter puede ser más de un byte (como UTF-8), simplemente lee el primer byte.
**Paso 2: Comprueba si el byte leído coincide con alguno de los siguientes equivalentes ASCII.** La siguiente tabla se ha dividido en filas para mayor legibilidad, pero solo necesitas determinar si el byte leído existe en la tabla en absoluto, no la fila específica.
| Nombre | Caracteres ASCII | Valores de byte equivalentes |
| :-------------------- | :------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Dígitos | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' | 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 |
| Letras mayúsculas | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' | 0x41, 0x42, 0x43, 0x44, 0x45,0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51,0x52, 0x53, 0x54, 0x55, 0x56, 0x57,0x58, 0x59, 0x5A |
| Letras minúsculas | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' | 0x61, 0x62, 0x63, 0x64, 0x65,0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B,0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71,0x72, 0x73, 0x74, 0x75, 0x76, 0x77,0x78, 0x79, 0x7A |
| Caracteres reservados | '-', '.', '\_', '\~' | 0x2D, 0x2E, 0x5F, 0x7E |
**Paso 2b: Si el byte no aparece en la tabla anterior, continúa.** Cualquier otro valor debe codificarse. **Paso 2a: Si el byte aparece en la tabla anterior, cópialo a DST y vuelve al Paso 1.** Los caracteres listados en la tabla anterior no necesitan ser escapados, por lo que simplemente copiarás el byte directamente.
**Paso 3: Escribe el carácter '%' a DST.** El carácter de porcentaje '%' (o 0x25 en hexadecimal y 00100101 en binario) indica que los siguientes dos bytes representarán un byte codificado.
**Paso 4: Escribe dos caracteres que representen el valor hexadecimal codificado en ASCII en mayúsculas del byte actual a DST.** Esto es un poco confuso, así que aquí hay un ejemplo. Imagina que el byte actual es 0xE6 (11100110 en binario). Esto corresponde con el valor codificado en UTF-8 de 'æ'. Para codificar este valor, escribe el carácter 'E' (0x45, de la tabla anterior) y luego el carácter '6' (0x36) a DST. Los últimos tres caracteres escritos deberían haber sido "%E6". Ten en cuenta que si escribes una letra como A, B, C, D, E o F, debes usar el carácter en mayúsculas.
**Paso 5: Vuelve al Paso 1.** Continúa hasta que toda la totalidad de SRC se copie a DST.
#### Ejemplos
Los siguientes ejemplos pueden ser útiles para comparar con la salida de tu propio código. Debes considerar cualquier diferencia como un error. Los espacios codificados como caracteres "+" son un ejemplo de codificación incorrecta.
| Cadena original | Cadena codificada |
| :----------------- | :-------------------------- |
| Ladies + Gentlemen | Ladies%20%2B%20Gentlemen |
| An encoded string! | An%20encoded%20string%21 |
| Dogs, Cats & Mice | Dogs%2C%20Cats%20%26%20Mice |
| ☃ | %E2%98%83 |
# Autorización basada en PIN
Source: https://docs.x.com/es/fundamentals/authentication/oauth-1-0a/pin-based-oauth
Usa el flujo OAuth basado en PIN para X apps que no pueden incrustar un navegador, como herramientas de línea de comandos y consolas de juegos, ingresando un PIN numérico como el oauth_verifier.
### Autorización basada en PIN
El flujo OAuth basado en PIN es una versión del proceso [OAuth de 3 patas](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) y está pensado para aplicaciones que no pueden acceder o incrustar un navegador web para redirigir al usuario después de la autorización. Ejemplos de tales aplicaciones serían aplicaciones de línea de comandos, sistemas embebidos, consolas de juegos y ciertos tipos de aplicaciones móviles.
El flujo OAuth basado en PIN es iniciado por una app en el `request_token` con el `oauth_callback` establecido en `oob`. El término `oob` significa OAuth fuera de banda (out-of-band). El usuario aún visita X para iniciar sesión o autorizar la app, pero no será redirigido automáticamente a la aplicación tras aprobar el acceso. En cambio, verá un código PIN numérico, con instrucciones para regresar a la aplicación e ingresar este valor.
**Nota:** La `callback_url` en la configuración de la X app sigue siendo obligatoria, incluso cuando se utiliza autenticación basada en PIN.
#### Implementación del flujo OAuth basado en PIN
El flujo basado en PIN se implementa de la misma manera que la [autorización de 3 patas](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) (e [Iniciar sesión con X](/resources/fundamentals/authentication#log-in-with-x)), con las siguientes diferencias:
1. El valor de `oauth_callback` debe establecerse en `oob` durante la llamada [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token).
2. Después de que el usuario es enviado a X para autorizar tu app usando una URL [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) o [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize), no será redirigido a tu `callback_url`, sino que verá una pantalla con un PIN de aproximadamente 7 dígitos generado por X con instrucciones para ingresar el PIN en tu aplicación.
3. El usuario ingresa este PIN en tu aplicación, y tu aplicación usa el número de PIN como el `oauth_verifier` en el [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) para obtener un access\_token.
**Nota:** Los números PIN no son reutilizables, y el `access_token` obtenido debe usarse para las solicitudes application-user.
# Autenticación app-only y Bearer Token de OAuth 2.0
Source: https://docs.x.com/es/fundamentals/authentication/oauth-2-0/application-only
Autentica las solicitudes a la X API con Bearer Tokens App-Only de OAuth 2.0 para acceso de servidor a servidor y de solo lectura a datos públicos sin contexto de usuario.
### Autenticación app-only y Bearer Token de OAuth 2.0
X ofrece a las aplicaciones la capacidad de emitir solicitudes autenticadas en nombre de la propia aplicación, en lugar de en nombre de un usuario específico. La implementación de X se basa en el flujo [Client Credentials Grant](http://tools.ietf.org/html/rfc6749#section-4.4) de la [especificación de OAuth 2](http://tools.ietf.org/html/rfc6749).
La autenticación application-only no incluye ningún contexto de usuario y es una forma de autenticación en la que una aplicación realiza solicitudes a la API en su propio nombre. Este método es para desarrolladores que solo necesitan acceso de solo lectura a información pública.
Puedes realizar la autenticación application-only usando las claves de consumer API de tu app o usando un App only Access Token (Bearer Token). Esto significa que las únicas solicitudes que puedes realizar a una X API no deben requerir un usuario autenticado.
Con la autenticación application-only, puedes realizar acciones como:
* Obtener timelines de usuarios
* Acceder a amigos y seguidores de cualquier cuenta
* Acceder a recursos de listas
* Buscar Tweets
Ten en cuenta que solo [OAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret) u [OAuth 2.0 Authorization Code Flow](/resources/fundamentals/authentication/oauth-2-0/authorization-code) con PKCE es necesario para emitir solicitudes en nombre de los usuarios. La página de [Referencia de la API](/resources/fundamentals/authentication/api-reference) describe el método de autenticación necesario para usar una API. Necesitarás autenticación de usuario, contexto de usuario, con un [access token](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) para realizar lo siguiente:
* Publicar Tweets u otros recursos
* Buscar usuarios
* Usar cualquier endpoint geográfico
* Acceder a Mensajes Directos o credenciales de cuenta
* Obtener las direcciones de correo electrónico de los usuarios
#### Flujo de autenticación
Para usar este método, necesitas usar un [App only Access Token](/resources/fundamentals/authentication/oauth-2-0/application-only) (también conocido como [Bearer Token](/resources/fundamentals/authentication/oauth-2-0/bearer-tokens)). Puedes generar un App only Access Token (Bearer Token) pasando tu consumer key y secret a través del endpoint [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token).
El flujo de autenticación application-only sigue estos pasos:
* Una aplicación codifica su consumer key y secret en un conjunto de credenciales especialmente codificadas.
* Una aplicación realiza una solicitud al endpoint [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) para intercambiar estas credenciales por un [App only Access Token](/resources/fundamentals/authentication/oauth-2-0/application-only).
* Al acceder a la REST API, la aplicación usa el App only Access Token para autenticarse.
Debido a que no es necesario firmar una solicitud, este enfoque es mucho más simple que el modelo OAuth 1.0a estándar.
#### Acerca de la autenticación application-only
**Los tokens son contraseñas**
Ten en cuenta que la consumer key & secret y el propio App only Access Token (Bearer Token) otorgan acceso para realizar solicitudes en nombre de una aplicación. Estos valores deben considerarse tan sensibles como las contraseñas y no deben compartirse ni distribuirse a partes no confiables.
**SSL requerido**
Todas las solicitudes (tanto para obtener como para usar los tokens) *deben* usar endpoints HTTPS. Sigue las mejores prácticas detalladas en [Conexión a la X API mediante TLS](/resources/fundamentals/authentication/guides/tls) — los peers deben verificarse **siempre**.
**Sin contexto de usuario**
Al emitir solicitudes usando autenticación application-only, no existe el concepto de "usuario actual". Por lo tanto, los endpoints como [POST statuses/update](/x-api/posts/creation-of-a-post) no funcionarán con la autenticación application-only. Consulta [usar OAuth](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) para más información sobre cómo emitir solicitudes en nombre de un usuario.
**Límites de tasa**
Las aplicaciones tienen dos tipos de grupos de límites de tasa.
Las solicitudes realizadas en nombre de usuarios con access tokens, también conocidas como user-context, se descuentan de un contexto de límite de tasa diferente al utilizado en la autenticación application-only. Por lo tanto, en otras palabras, las solicitudes realizadas en nombre de los usuarios no se descontarán de los límites de tasa disponibles a través de la autenticación app-only, y las solicitudes realizadas a través de app-only auth no se descontarán de los límites de tasa utilizados en la autenticación basada en usuario.
Lee más sobre [Límites de tasa de la API](/x-api/fundamentals/rate-limits) y [revisa los límites](https://developer.x.com/en/portal/products).
#### Emisión de solicitudes application-only
**Paso 1: Codifica la consumer key y secret**
Los pasos para codificar la consumer key y secret de una aplicación en un conjunto de credenciales para obtener un Bearer Token son:
1. Codifica en URL la consumer key y consumer secret según [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Ten en cuenta que, en el momento de escribir esto, esto no cambiará realmente la consumer key y secret, pero este paso debe realizarse igualmente por si el formato de esos valores cambia en el futuro.
2. Concatena la consumer key codificada, un carácter de dos puntos ":" y la consumer secret codificada en una sola cadena.
3. [Codifica en Base64](http://en.wikipedia.org/wiki/Base64) la cadena del paso anterior.
A continuación se muestran valores de ejemplo que muestran el resultado de este algoritmo. Ten en cuenta que el consumer secret utilizado en esta página es para propósitos de prueba y no funcionará para solicitudes reales.
| | |
| :--------------------------------------------------------------- | :------------------------------------------------------------------------------------------ |
| Consumer key | xvz1evFS4wEEPTGEFPHBog |
| Consumer secret | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| Consumer key codificada según RFC 1738
(no cambia) | xvz1evFS4wEEPTGEFPHBog |
| Consumer secret codificada según RFC 1738
(no cambia) | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| Credenciales de Bearer Token | xvz1evFS4wEEPTGEFPHBog:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| Credenciales de Bearer Token codificadas en Base64 | :: eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw== |
**Paso 2: Obtén un App only Access Token (Bearer Token)**
El valor calculado en el paso 1 debe intercambiarse por un App only Access Token emitiendo una solicitud a [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token):
* La solicitud debe ser una solicitud HTTP POST.
* La solicitud debe incluir un encabezado `Authorization` con el valor `Basic .`
* La solicitud debe incluir un encabezado `Content-Type` con el valor `application/x-www-form-urlencoded;charset=UTF-8.`
* El cuerpo de la solicitud debe ser `grant_type=client_credentials`.
**Solicitud de ejemplo (el encabezado Authorization ha sido dividido en varias líneas):**
```json theme={null}
POST /oauth2/token HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant\_type=client\_credentials
```
Si la solicitud se formateó correctamente, el servidor respondería con un payload codificado en JSON:
**Respuesta de ejemplo:**
```json theme={null}
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token\_type":"bearer","access\_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
```
Las aplicaciones deben verificar que el valor asociado a la clave `token_type` del objeto devuelto sea `bearer`. El valor asociado a la clave `access_token` es el App only Access Token (Bearer Token).
Ten en cuenta que solo un App only Access Token es válido para una aplicación a la vez. Emitir otra solicitud con las mismas credenciales a `/oauth2/token` devolverá el mismo token hasta que se invalide.
**Paso 3: Autentica las solicitudes a la API con el App only Access Token (Bearer Token)**
El App only Access Token (Bearer Token) puede usarse para emitir solicitudes a endpoints de la API que admiten autenticación application-only. Para usar el App Access Token, construye una solicitud HTTPS normal e incluye un encabezado `Authorization` con el valor `Bearer . No se requiere firma.`
**Solicitud de ejemplo (el encabezado Authorization ha sido dividido en varias líneas):**
```
GET /1.1/statuses/user\_timeline.json?count=100&screen\_name=twitterapi HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAA
AAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Accept-Encoding: gzip
```
**Invalidar un App only Access Token (Bearer Token)**
Si un App only Access Token queda comprometido o necesita invalidarse por cualquier motivo, emite una llamada a [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token).
**Solicitud de ejemplo (el encabezado Authorization ha sido dividido en varias líneas):**
```bash theme={null}
POST /oauth2/invalidate_token HTTP/1.1
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==
User-Agent: My X App v1.0.23
Host: api.x.com
Accept: */*
Content-Length: 119
Content-Type: application/x-www-form-urlencoded
access_token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
```
**Respuesta de ejemplo:**
```json theme={null}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 127
...
{"access_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
```
#### Casos de error comunes
Esta sección describe algunos errores comunes involucrados en la negociación y el uso de Bearer Tokens. Ten en cuenta que no se cubren aquí todas las posibles respuestas de error: presta atención a los códigos de error y respuestas no manejados.
**Solicitudes no válidas para obtener o revocar un App only Access Token**
Los intentos de:
* Obtener un App only Access Token (Bearer Token) con una solicitud no válida (por ejemplo, omitiendo `grant_type=client_credentials`).
* Obtener o revocar un App only Access Token (Bearer Token) con credenciales de app incorrectas o caducadas.
* Invalidar un App only Access Token (Bearer Token) incorrecto o revocado.
* Obtener un App only Access Token (Bearer Token) con demasiada frecuencia en un corto período de tiempo.
Darán como resultado:
```json theme={null}
HTTP/1.1 403 Forbidden
Content-Length: 105
Content-Type: application/json; charset=utf-8
...
{"errors":\[{"code":99,"label":"authenticity\_token\_error","message":"Unable to verify your credentials"}\]}
```
#### La solicitud a la API contiene un App only Access Token (Bearer Token) no válido
Usar un Access Token incorrecto o revocado para realizar solicitudes a la API dará como resultado:
```json theme={null}
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 61
...
{"errors":\[{"message":"Invalid or expired token","code":89}\]}
```
#### App only Access Token (Bearer Token) usado en un endpoint que no admite autenticación application-only
Solicitar un endpoint que requiere un contexto de usuario (como `statuses/home_timeline`) con un App only Access Token (Bearer Token) producirá:
```json theme={null}
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 91
...
{"errors":\[{"message":"Your credentials do not allow access to this resource","code":220}\]}
```
# OAuth 2.0 Authorization Code Flow con PKCE
Source: https://docs.x.com/es/fundamentals/authentication/oauth-2-0/authorization-code
Referencia del OAuth 2.0 Authorization Code Flow con PKCE de X, que cubre scopes, refresh tokens, clientes confidenciales y tiempos de vida de los access tokens.
### OAuth 2.0 Authorization Code Flow con PKCE
#### Introducción
OAuth 2.0 es un protocolo de autorización estándar del sector que permite un mayor control sobre el alcance de una aplicación y flujos de autorización en múltiples dispositivos. OAuth 2.0 te permite elegir scopes específicos y granulares que te otorgan permisos específicos en nombre de un usuario.
Para habilitar OAuth 2.0 en tu App, debes habilitarlo en la configuración de autenticación de tu App que se encuentra en la sección de configuración de App de la Developer Console.
#### ¿Cuánto tiempo permanecerán válidas mis credenciales?
Por defecto, el access token que crees a través del Authorization Code Flow con PKCE solo permanecerá válido durante dos horas, a menos que hayas usado el scope `offline.access`.
#### Refresh tokens
Los refresh tokens permiten a una aplicación obtener un nuevo access token sin solicitarlo al usuario mediante el flujo de refresh token.
Si se aplica el scope `offline.access`, se emitirá un refresh token de OAuth 2.0. Con este refresh token, obtienes un access token. Si no se pasa este scope, no generaremos un refresh token.
Un ejemplo de la solicitud que harías para usar un refresh token para obtener un nuevo access token es el siguiente:
```bash theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ
```
#### Configuración de la App
Puedes seleccionar la configuración de autenticación de tu App para que sea OAuth 1.0a o OAuth 2.0. También puedes habilitar una App para acceder tanto a OAuth 1.0a como a OAuth 2.0.
OAuth 2.0 se puede usar solo con la X API v2. Si has seleccionado OAuth 2.0, podrás ver un Client ID en la sección Keys and Tokens de tu App.
#### Clientes confidenciales
Los [clientes confidenciales](https://datatracker.ietf.org/doc/html/rfc6749#section-2.1) pueden guardar credenciales de forma segura sin exponerlas a partes no autorizadas y autenticarse de forma segura con el servidor de autorización, manteniendo tu client secret protegido. Los clientes públicos, dado que normalmente se ejecutan en un navegador o dispositivo móvil, no pueden usar tus client secrets. Si seleccionas un tipo de App que es un cliente confidencial, se te proporcionará un client secret.
Si seleccionaste un tipo de cliente que es un cliente confidencial en la Developer Console, también podrás ver un Client Secret. Tus opciones son Native App, Single page App, Web App, Automated App o bot. Native App y Single page Apps son clientes públicos y Web App y Automated App o bots son clientes confidenciales.
No necesitas client id para clientes confidenciales con un encabezado Authorization válido. Aún se te requiere incluir el Client Id en el cuerpo para las solicitudes con un cliente público.
#### Scopes
Los scopes te permiten establecer un acceso granular para tu App, de modo que tu App solo tenga los permisos que necesita. Para saber más sobre qué scopes se corresponden con qué endpoints, consulta nuestra [guía de mapeo de autenticación](/resources/fundamentals/authentication/guides/v2-authentication-mapping).
| | |
| :------------------- | :-------------------------------------------------------------------------------------------------------------------- |
| **Scope** | **Descripción** |
| tweet.read | Todos los Tweets que puedes ver, incluidos los Tweets de cuentas protegidas. |
| tweet.write | Publicar Tweets y hacer Retweet por ti. |
| tweet.moderate.write | Ocultar y mostrar respuestas a tus Tweets. |
| users.email | Correo electrónico de un usuario autenticado. |
| users.read | Cualquier cuenta que puedas ver, incluidas cuentas protegidas. |
| follows.read | Personas que te siguen y personas a las que sigues. |
| follows.write | Seguir y dejar de seguir personas por ti. |
| offline.access | Mantente conectado a tu cuenta hasta que revoques el acceso. |
| space.read | Todos los Spaces que puedes ver. |
| mute.read | Cuentas que has silenciado. |
| mute.write | Silenciar y quitar el silencio a cuentas por ti. |
| like.read | Tweets que te han gustado y los likes que puedes ver. |
| like.write | Dar y quitar Like a Tweets por ti. |
| list.read | Lists, miembros de list y seguidores de list que has creado o de las que eres miembro, incluidas las listas privadas. |
| list.write | Crear y gestionar Lists por ti. |
| block.read | Cuentas que has bloqueado. |
| block.write | Bloquear y desbloquear cuentas por ti. |
| bookmark.read | Obtener Tweets marcados como favoritos de un usuario autenticado. |
| bookmark.write | Marcar y eliminar Bookmarks de Tweets. |
| dm.read | Todos los Mensajes Directos que puedes ver, incluidos los Mensajes Directos de cuentas protegidas. |
| dm.write | Enviar y gestionar Mensajes Directos por ti. |
| media.write | Subir medios. |
#### Límites de tasa
En su mayor parte, los límites de tasa son los mismos que al autenticarse con OAuth 1.0a, con la excepción de Tweets lookup y Users lookup. Estamos aumentando el límite por App de 300 a 900 solicitudes cada 15 minutos al usar OAuth 2.0 para Tweet lookup y user lookup. Para saber más, asegúrate de consultar nuestra [documentación sobre límites de tasa](/resources/fundamentals/rate-limits).
#### Grant types
Solo proporcionamos [authorization code](https://oauth.net/2/grant-types/authorization-code/) con [PKCE](https://oauth.net/2/pkce/) y [refresh token](https://oauth.net/2/grant-types/refresh-token/) como los [grant types](https://oauth.net/2/grant-types/) admitidos para este lanzamiento inicial. Es posible que proporcionemos más grant types en el futuro.
#### Flujo de OAuth 2.0
OAuth 2.0 usa un flujo similar al que utilizamos actualmente para OAuth 1.0a. Puedes consultar un diagrama y una explicación detallada en nuestra [documentación sobre este tema](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens).
#### Glosario
| | |
| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Término** | **Descripción** |
| Grant types | El marco OAuth especifica varios grant types para diferentes casos de uso y un marco para crear nuevos grant types. Los ejemplos incluyen authorization code, client credentials, device code y refresh token. |
| Cliente confidencial | Los clientes son aplicaciones que pueden autenticarse de forma segura con el servidor de autorización, por ejemplo, manteniendo su client secret registrado a salvo. |
| Cliente público | Los clientes no pueden usar client secrets registrados, como aplicaciones que se ejecutan en un navegador o dispositivo móvil. |
| Authorization code flow | Utilizado tanto por clientes confidenciales como públicos para intercambiar un authorization code por un access token. |
| PKCE | Una extensión del authorization code flow para prevenir varios ataques y poder realizar el intercambio OAuth desde clientes públicos de forma segura. |
| Client ID | Se puede encontrar en la sección keys and tokens de la Developer Console bajo el encabezado "Client ID". Si no lo ves, ponte en contacto con nuestro equipo directamente. Se necesitará el Client ID para generar la URL de autorización. |
| Redirect URI | Tu callback URL. Necesitarás tener [validación de coincidencia exacta](https://datatracker.ietf.org/doc/html/rfc6749#section-10.6). |
| Authorization code | Esto permite a una aplicación acceder a las APIs en nombre de los usuarios. Conocido como auth\_code. El auth\_code tiene un límite de tiempo de 30 segundos una vez que el propietario de la App recibe un auth\_code aprobado por el usuario. Tendrás que intercambiarlo por un access token dentro de 30 segundos, o el auth\_code expirará. |
| Access token | Los access tokens son el token que las aplicaciones usan para realizar solicitudes a la API en nombre de un usuario. |
| Refresh token | Permite a una aplicación obtener un nuevo access token sin solicitarlo al usuario mediante el flujo de refresh token. |
| Client Secret | Si has seleccionado un tipo de App que es un cliente confidencial, se te proporcionará un "Client Secret" bajo "Client ID" en la sección keys and tokens de tu App. |
#### Parámetros
Para construir una URL de autorización OAuth 2.0, deberás asegurarte de tener los siguientes parámetros en la URL de autorización.
| | |
| :---------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Parámetro** | **Descripción** |
| response\_type | Necesitarás especificar que se trata de un code con la palabra "code". |
| client\_id | Se puede encontrar en la Developer Console bajo el encabezado "Client ID". |
| redirect\_uri | Tu callback URL. Este valor debe corresponder a una de las Callback URLs definidas en la configuración de tu App. Para OAuth 2.0, deberás tener [validación de coincidencia exacta](https://datatracker.ietf.org/doc/html/rfc6749#section-10.6) para tu callback URL. |
| state | Una cadena aleatoria que proporcionas para verificar contra [ataques CSRF](https://auth0.com/docs/protocols/state-parameters). La longitud de esta cadena puede ser de hasta 500 caracteres. |
| code\_challenge | Un parámetro [PKCE](https://www.oauth.com/oauth2-servers/pkce/authorization-request/), un secreto aleatorio para cada solicitud que realizas. |
| code\_challenge\_method | Especifica el método que estás utilizando para realizar una solicitud (S256 O plain). |
#### Authorize URL
Con OAuth 2.0, creas una URL de autorización, que puedes usar para permitir que un usuario se autentique a través de un flujo de autenticación, similar a "Iniciar sesión" con X.
Un ejemplo de la URL que estás creando es el siguiente:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20account.follows.read%20account.follows.write&state=state&code_challenge=challenge&code_challenge_method=plain
```
Necesitarás tener la codificación adecuada para que esta URL funcione; asegúrate de consultar nuestra documentación sobre [codificación por porcentaje](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters).
# Uso y generación de un Bearer Token app-only
Source: https://docs.x.com/es/fundamentals/authentication/oauth-2-0/bearer-tokens
Genera y usa un Bearer Token app-only para la autenticación application-only OAuth 2.0 de la X API con una solicitud curl al endpoint oauth2/token.
### Uso y generación de un Bearer Token app-only
Un bearer token permite a los desarrolladores tener un punto de entrada más seguro para usar las APIs de X, y son una de las características principales de OAuth 2.0.
La autenticación que usa un Bearer Token también se conoce como autenticación application-only. Un Bearer Token es un array de bytes de formato no especificado que generas usando un script como un comando curl. También puedes obtener un Bearer Token desde la Developer Console dentro de la sección keys and tokens de la configuración de tu App. Puedes encontrar más información sobre esta característica en la [documentación oficial de OAuth](https://oauth.net/2/bearer-tokens/).
#### ¿Cuándo se usan?
Los productos que requieren el uso de un Bearer Token son los siguientes:
* [Engagement API](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api)
* [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)
* Otras APIs que utilizan autenticación con Bearer Token de OAuth 2.0, como los endpoints v2 y Labs.
#### Requisitos previos
Necesitarás [registrarte para una cuenta de desarrollador](https://developer.x.com/en/portal/petition/essential/basic-info) y haber creado una [X App](/resources/fundamentals/developer-apps). Una vez que las tengas, también deberás obtener las API keys que se encuentran en la [Developer Console](/resources/fundamentals/developer-portal). Sigue los pasos a continuación:
1. Inicia sesión en tu cuenta de X en developer.x.com.
2. Navega al [panel de X App](https://developer.x.com/content/developer-twitter/en/apps) y abre la X App para la que deseas generar access tokens.
3. Navega a la página "keys and tokens".
4. Encontrarás las API keys, los user Access Tokens y el Bearer Token en esta página.
### Cómo generar un Bearer Token
Puedes encontrar el Bearer Token para tu App junto con el resto de tus "Keys and Tokens".
Copia la siguiente solicitud cURL en tu línea de comandos después de realizar cambios en las siguientes claves de consumer API previamente obtenidas de tu [X App](/resources/fundamentals/developer-apps). Ten en cuenta que las claves de consumer API utilizadas en esta página han sido dadas de baja y no funcionarán para solicitudes reales.
* **API key** `` p. ej. `xvz1evFS4wEEPTGEFPHBog`
* **API secret key** `` p. ej. `L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg`
```bash theme={null}
curl -u "$API_KEY:$API_SECRET_KEY" \
--data 'grant_type=client_credentials' \
'https://api.x.com/oauth2/token'
```
Aquí hay un ejemplo de cómo debería verse la solicitud curl con tus API keys ingresadas:
```bash theme={null}
curl -u 'xvz1evFS4wEEPTGEFPHBog:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg' \
--data 'grant_type=client_credentials' \
'https://api.x.com/oauth2/token'
```
Así es como se vería la respuesta. Ten en cuenta que este es un Bearer Token dado de baja:
`{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F"}`
Nuestro Bearer Token usado para autenticarse en recursos con OAuth 2.0 sería:
`AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F`
# OAuth 2.0
Source: https://docs.x.com/es/fundamentals/authentication/oauth-2-0/overview
El Bearer Token de OAuth 2.0 autentica solicitudes en nombre de tu App de desarrollador. Como este método es específico de la App, no involucra a ningún usuario.
### Bearer Token (también conocido como app-only)
El Bearer Token de OAuth 2.0 autentica solicitudes en nombre de tu [App de desarrollador](/resources/fundamentals/developer-apps). Como este método es específico de la App, no involucra a ningún usuario. Este método es típicamente para desarrolladores que necesitan acceso de solo lectura a información pública.
Este método de autenticación requiere que pases un Bearer Token con tu solicitud, que puedes generar dentro de la sección Keys and tokens de tus Apps de desarrollador. Aquí hay un ejemplo de cómo se ve una solicitud con un Bearer Token ficticio:
```json theme={null}
curl "https://api.x.com/2/tweets?ids=1261326399320715264,1278347468690915330" \
-H "Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAFnz2wAAAAAAxTmQbp%2BIHDtAhTBbyNJon%2BA72K4%3DeIaigY0QBrv6Rp8KZQQLOTpo9ubw5Jt?WRE8avbi"
```
Las llamadas a la API que utilizan autenticación app-only tienen [límites de tasa](/resources/fundamentals/rate-limits) por endpoint a nivel de App.
Para usar este método, necesitarás un Bearer Token, que puedes generar pasando tu API Key y Secret a través del endpoint [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token), o generándolo en la sección "keys and token" de la configuración de tu App en la [Developer Console](/resources/fundamentals/developer-portal).
Si deseas revocar un Bearer Token, puedes usar el endpoint [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token), o hacer clic donde dice "revoke" junto al Bearer Token en la sección "keys and tokens" de la configuración de tu App.
### OAuth 2.0 Authorization Code Flow con PKCE
El OAuth 2.0 Authorization Code Flow con PKCE te permite autenticarte en nombre de otro usuario con mayor control sobre los scopes de una aplicación y mejora los flujos de autorización en múltiples dispositivos. En otras palabras, los desarrolladores que crean aplicaciones para personas en X tendrán más control sobre la información que su App solicita a sus usuarios, de modo que solo tengas que pedir a tus usuarios finales los datos y la información que necesitas.
Este moderno protocolo de autorización te permitirá presentar a tus usuarios finales un flujo de consentimiento más simplificado para autorizar tu app, que solo muestra los scopes específicos que has solicitado de ellos. Esto no solo reduce tu carga de datos, sino que también puede generar una mayor confianza por parte de los usuarios finales.
# OAuth 2.0 Authorization Code Flow con PKCE
Source: https://docs.x.com/es/fundamentals/authentication/oauth-2-0/user-access-token
Guía paso a paso para conectar usuarios a los endpoints de la X API v2 con OAuth 2.0 Authorization Code Flow con PKCE, incluidas las URLs de autorización y el intercambio de tokens.
### Cómo conectarse a endpoints usando OAuth 2.0 Authorization Code Flow con PKCE
#### Cómo conectarse a los endpoints
Para autenticar a tus usuarios, tu App deberá implementar un flujo de autorización. Este flujo de autorización te permite dirigir a tus usuarios a un diálogo de autorización en X. Desde allí, la experiencia principal de X mostrará el diálogo de autorización y manejará la autorización en nombre de tu App. Tus usuarios podrán autorizar tu App o denegar el permiso. Después de que el usuario tome su decisión, X redirigirá al usuario a tu App, donde podrás intercambiar el authorization code por un access token (si el usuario autorizó tu App), o manejar un rechazo (si el usuario no autorizó tu App).
#### Trabajando con clientes confidenciales
Si estás trabajando con clientes confidenciales, necesitarás usar un esquema de [autenticación básica](https://datatracker.ietf.org/doc/html/rfc2617#section-2) para generar un encabezado de autorización con codificación base64 mientras realizas solicitudes a los endpoints de token.
El `userid` y la `password` están separados por un solo carácter de dos puntos (":") dentro de una cadena codificada en base64 en las credenciales.
Un ejemplo se vería así:
`-header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='`
Si el user agent desea enviar el Client ID "Aladdin" y la contraseña "open sesame", usaría el siguiente campo de encabezado:
`Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==`
Para crear el encabezado de autorización básica necesitarás codificar en base64 tu Client ID y Client Secret, que se pueden obtener desde la página "Keys and Tokens" de tu App dentro de la [Developer Console.](https://developer.x.com/en/portal/dashboard)
#### Pasos para conectarse usando OAuth 2.0
**Paso 1: Construye una Authorize URL**
Tu App necesitará construir una URL de autorización a X, indicando los scopes que tu App necesita autorizar. Por ejemplo, si tu App necesita buscar Tweets, usuarios y gestionar follows, debería solicitar los siguientes scopes:
`tweet.read%20users.read%20follows.read%20follows.write`
La URL también contendrá los parámetros `code_challenge` y state, además de los otros parámetros requeridos. En producción deberías usar una cadena aleatoria para el `code_challenge`.
**Paso 2: GET oauth2/authorize**
Haz que el usuario se autentique y envíe a la aplicación un authorization code. Si has habilitado OAuth 2.0 para tu App, puedes encontrar tu Client ID en la página "Keys and Tokens" de tu App.
Una URL de ejemplo a la que redirigir al usuario se vería así:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20follows.read%20follows.write&state=state&code_challenge=challenge&code_challenge_method=plain
```
Una URL de ejemplo con offline\_access se vería así:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20follows.read%20offline.access&state=state&code_challenge=challenge&code_challenge_method=plain
```
Tras una autenticación exitosa, el redirect\_uri recibiría una solicitud que contiene el parámetro auth\_code. Tu aplicación debe verificar el parámetro state.
Una solicitud de ejemplo desde la redirección del cliente sería:
```
https://www.example.com/?state=state&code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE
```
**Paso 3: POST oauth2/token - Access Token**
En este punto, puedes usar el authorization code para crear un access token y un refresh token (solo si se solicita el scope `offline.access`). Puedes realizar una solicitud POST al siguiente endpoint:
```
https://api.x.com/2/oauth2/token
```
Necesitarás pasar el `Content-Type` de `application/x-www-form-urlencoded` a través de un encabezado. Además, deberías tener en tu solicitud: `code`, `grant_type`, `client_id` y `redirect_uri`, y el `code_verifier`.
Aquí hay un ejemplo de solicitud de token para un cliente público:
```json theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ' \
--data-urlencode 'redirect_uri=https://www.example.com' \
--data-urlencode 'code_verifier=challenge'
```
Aquí hay un ejemplo usando un cliente confidencial:
```json theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'redirect_uri=https://www.example.com' \
--data-urlencode 'code_verifier=challenge'
```
**Paso 4: Conéctate a las APIs**
Ahora estás listo para conectarte a los endpoints usando OAuth 2.0. Para hacerlo, harás solicitudes a la API como lo harías usando [autenticación con Bearer Token](/resources/fundamentals/authentication/oauth-2-0/application-only). En lugar de pasar tu Bearer Token, querrás usar el access token que generaste en el último paso. Como respuesta, deberías ver el payload apropiado correspondiente al endpoint que estás solicitando. Esta solicitud es la misma tanto para clientes públicos como confidenciales.
Un ejemplo de la solicitud que harías se vería de la siguiente manera:
```json theme={null}
curl --location --request GET 'https://api.x.com/2/tweets?ids=1261326399320715264,1278347468690915330' \
--header 'Authorization: Bearer Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE'
```
**Paso 5: POST oauth2/token - refresh token**
Un refresh token permite a una aplicación obtener un nuevo access token sin solicitarlo al usuario. Puedes crear un refresh token realizando una solicitud POST al siguiente endpoint: [https://api.x.com/2/oauth2/token](https://api.x.com/2/oauth2/token) Necesitarás añadir el `Content-Type` de `application/x-www-form-urlencoded` a través de un encabezado. Además, también deberás pasar tu refresh\_token, establecer tu grant\_type como `refresh_token` y definir tu `client_id`.
Esta solicitud funcionará para clientes públicos:
```json theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ'
```
Aquí hay un ejemplo de uno para clientes confidenciales:
```json theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE'\
--data-urlencode 'grant_type=refresh_token'
```
**Paso 6: POST oauth2/revoke - Revoke Token**
Un revoke token invalida un access token o refresh token. Esto se usa para habilitar una funcionalidad de "cerrar sesión" en los clientes, lo que te permite limpiar cualquier credencial de seguridad asociada al flujo de autorización que ya no sea necesaria. El revoke token es para que una App revoque un token y no un usuario. Puedes crear una solicitud de revoke token realizando una solicitud POST a la siguiente URL si la App desea revocar programáticamente el acceso otorgado:
```
https://api.x.com/2/oauth2/revoke
```
Necesitarás pasar el `Content-Type` de `application/x-www-form-urlencoded` a través de un encabezado, tu token y tu client\_id.
En algunos casos, un usuario puede desear revocar el acceso otorgado a una App; puede revocar el acceso visitando la [página de Apps conectadas](https://x.com/settings/connected_apps).
```bash theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/revoke' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ'
```
Esta solicitud funcionará para clientes confidenciales:
```bash theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/revoke' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'token=Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE'
```
# Autenticación
Source: https://docs.x.com/es/fundamentals/authentication/overview
Las APIs de X manejan enormes cantidades de datos. La forma en que aseguramos estos datos para desarrolladores y usuarios es a través de la autenticación.
Las APIs de X manejan enormes cantidades de datos, y la autenticación asegura esos datos tanto para los desarrolladores como para los usuarios. Puedes elegir entre varios métodos de autenticación, que se enumeran a continuación.
La mayoría de los desarrolladores no necesitan manejar las complejidades de la autenticación directamente: las bibliotecas cliente se encargan de ellas automáticamente.
Puedes encontrar una lista de las bibliotecas cliente disponibles en nuestra página de [Herramientas y bibliotecas](/resources/tools-and-libraries).
## Métodos de autenticación
OAuth 1.0a permite a una App de desarrollador de X autorizada acceder a información privada de la cuenta o realizar una acción en X en nombre de una cuenta de X.
[**Más información**](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret)
El Access Token app-only permite a una app de desarrollador de X acceder a información disponible públicamente en X.
[**Más información**](/resources/fundamentals/authentication/oauth-2-0/overview)
Muchas de las APIs enterprise de X requieren el uso de HTTP Basic Authentication.
[**Más información**](/resources/fundamentals/authentication/basic-auth)
El contexto de usuario OAuth 2.0 te permite autenticarte en nombre de otra cuenta con mayor control sobre el alcance de una aplicación y flujos de autorización en múltiples dispositivos.
[**Más información**](/resources/fundamentals/authentication/oauth-2-0/authorization-code)
**Nota:**
Puedes obtener las claves de API de tu app, el Access Token app-only, el Access Token personal y el Access Token Secret desde la sección [Apps de desarrollador de X](/resources/fundamentals/developer-apps) en la [Developer Console](/resources/fundamentals/developer-portal).
**Para realizar solicitudes en nombre de otro usuario**, genera un conjunto separado de Access Tokens para ese usuario usando el [flujo OAuth de 3 patas](https://developer.x.com/resources/fundamentals/authentication/obtaining-user-access-tokens), y luego pasa esos tokens del usuario con tus solicitudes de contexto de usuario OAuth 1.0a o contexto de usuario OAuth 2.0.
## Recursos adicionales
Aprende cómo generar tokens y autenticar solicitudes usando nuestras guías de integración.
Revisa nuestras guías de referencia para nuestros endpoints de autenticación.
Asegúrate de protegerte y de comprender las mejores prácticas para almacenar tus claves y tokens.
¿Tienes una pregunta? Visita nuestras preguntas frecuentes.
# Conteo de caracteres
Source: https://docs.x.com/es/fundamentals/counting-characters
Cómo cuenta X los caracteres en Posts: límite de 280, puntos de código ponderados, acortamiento de URLs, manejo de emojis y Unicode, y casos especiales.
Los Posts en X pueden contener hasta **280 caracteres**. Sin embargo, no todos los caracteres cuentan igual: los emojis, las URLs y ciertos rangos de Unicode tienen reglas de conteo especiales.
***
## Ponderación de caracteres
X usa un sistema de conteo de caracteres ponderado. La mayoría de los caracteres cuentan como 1, pero algunos cuentan como 2:
| Tipo de carácter | Peso | Máx. de caracteres |
| :---------------------------------- | :-------------- | :----------------- |
| Latín, puntuación, símbolos comunes | 1 | 280 |
| Emojis | 2 | 140 emojis |
| CJK (chino, japonés, coreano) | 2 | 140 caracteres |
| Otro Unicode | 2 (por defecto) | Varía |
Usa la biblioteca de código abierto [twitter-text](https://github.com/twitter/twitter-text) para contar los caracteres con precisión en tu app.
***
## Conteo de emojis
Todos los emojis cuentan como **2 caracteres**, sin importar su complejidad:
| Emoji | Visualización | Conteo de caracteres | Unicode |
| :---------- | :----------------- | :------------------- | :------------------ |
| 👾 | Un solo emoji | 2 | U+1F47E |
| 🙋🏽 | Con tono de piel | 2 | 🙋 + modificador 🏽 |
| 👨🎤 | Combinado con ZWJ | 2 | 👨 + ZWJ + 🎤 |
| 👨👩👧👦 | Secuencia familiar | 2 | 4 emojis + 3 ZWJs |
Los uniones de ancho cero (ZWJ) combinan emojis visualmente, pero no se suman al conteo.
***
## Manejo de URLs
Todas las URLs se envuelven con el acortador `t.co` y cuentan como **23 caracteres**, independientemente de la longitud original:
```
https://example.com → 23 caracteres
https://example.com/very/long/path → 23 caracteres
```
Esto se aplica a cualquier URL válida detectada en el texto del post.
***
## Casos especiales
| Contenido | Regla de conteo |
| :--------------------------- | :--------------------------------------------------------------------- |
| **@menciones en respuestas** | Las @menciones autocompletadas al inicio de las respuestas no cuentan |
| **Nuevas @menciones** | Las @menciones que añadas manualmente cuentan normalmente |
| **Medios** | Los medios adjuntos (vía clientes oficiales) cuentan como 0 caracteres |
| **Hashtags** | Cuentan normalmente (# + texto de la etiqueta) |
***
## Codificación de texto
La X API requiere codificación **UTF-8**. La longitud de los caracteres se calcula usando la Forma de Normalización Unicode C (NFC).
Ejemplo con `café`:
| Forma | Bytes | Caracteres |
| :----------------- | :---------- | :--------- |
| NFC (compuesta) | `c a f é` | 4 |
| NFD (descompuesta) | `c a f e ́` | 5 |
X normaliza a NFC, así que ambas se codifican como 4 caracteres.
***
## Implementación
Usa la biblioteca oficial [twitter-text](https://github.com/twitter/twitter-text) para contar caracteres con precisión:
```javascript theme={null}
import { parseTweet } from 'twitter-text';
const result = parseTweet('Hello, world! 👋');
console.log(result.weightedLength); // 16
console.log(result.valid); // true
```
```python theme={null}
from twitter_text import parse_tweet
result = parse_tweet('Hello, world! 👋')
print(result.weightedLength) # 16
print(result.valid) # True
```
La biblioteca maneja todos los casos límite, incluidas las secuencias de emojis, la detección de URLs y la normalización Unicode.
***
## Recursos
Biblioteca oficial de código abierto para el análisis de texto.
Definiciones de pesos de caracteres y rangos Unicode.
# Apps
Source: https://docs.x.com/es/fundamentals/developer-apps
Crea y configura apps de desarrollador de X para obtener credenciales, establecer permisos de OAuth 1.0a y 2.0, gestionar callbacks y rotar claves.
Las apps son contenedores para tus credenciales de la API. Cada app tiene sus propias claves, tokens y configuraciones.
***
## Credenciales de la app
Cuando creas una app, puedes generar estas credenciales:
| Credencial | Caso de uso |
| :------------------------ | :----------------------------------------------------------------------------------------- |
| **API Key y Secret** | Autenticación con OAuth 1.0a. Se usan para firmar solicitudes o generar tokens de usuario. |
| **Access Token y Secret** | Realizar solicitudes en nombre de tu propia cuenta (OAuth 1.0a). |
| **Client ID y Secret** | Autenticación con OAuth 2.0. Se usan para el flujo de authorization code. |
| **Bearer Token** | Autenticación app-only para endpoints de datos públicos. |
Elige **OAuth 2.0** para nuevos proyectos. Ofrece scopes detallados y es obligatorio para los endpoints de contexto de usuario de la X API v2.
***
## Crear una app
Ve a [console.x.com](https://console.x.com) e inicia sesión.
Ingresa un nombre, una descripción y un caso de uso para tu app.
Después de crearla, genera las claves y tokens que necesites.
Guarda las credenciales inmediatamente: solo se muestran una vez.
***
## Permisos de la app (OAuth 1.0a)
Las apps de OAuth 1.0a tienen tres niveles de permisos:
* Ver posts, usuarios y datos públicos
* No se puede publicar, dar like ni modificar nada
* No se puede acceder a los Mensajes Directos
* Todos los permisos de lectura
* Publicar y eliminar posts
* Seguir/dejar de seguir usuarios
* Dar like y republicar
* No se puede acceder a los Mensajes Directos
* Todos los permisos de lectura y escritura
* Enviar y leer Mensajes Directos
Cambiar los permisos requiere que los usuarios vuelvan a autorizar tu app para obtener nuevos tokens con el alcance actualizado.
***
## Tipos de app de OAuth 2.0
Al configurar OAuth 2.0, selecciona el tipo de tu app:
| Tipo | Cliente | Caso de uso |
| :---------------------- | :----------- | :------------------------------------------------------------------------------- |
| **Web App** | Confidencial | Aplicaciones del lado del servidor que pueden almacenar secretos de forma segura |
| **Automated App / Bot** | Confidencial | Bots y servicios automatizados que se ejecutan en servidores |
| **Native App** | Público | Apps móviles o de escritorio que no pueden proteger secretos |
| **Single Page App** | Público | Apps JavaScript basadas en navegador |
Los **clientes confidenciales** reciben un Client Secret. Los **clientes públicos** usan solo PKCE.
***
## URLs de callback
Las URLs de callback (URIs de redirección) son obligatorias para los flujos de OAuth. Después de que un usuario autoriza tu app, es redirigido a tu URL de callback con un código de autorización.
### Requisitos
* Agrega las URLs de callback a la lista de permitidas de tu app en la Developer Console
* Las URLs deben coincidir exactamente (incluidas las barras finales)
* Máximo **10 URLs de callback** por app
* Usa `https://` en producción
* Para desarrollo local, usa `http://127.0.0.1` (no `localhost`)
### Protocolos no permitidos
Estos protocolos no se pueden usar: `javascript`, `data`, `file`, `ftp`, `mailto`, `telnet` y otros esquemas no estándar.
`vbscript`, `javascript`, `vbs`, `data`, `mocha`, `keyword`, `livescript`, `ftp`, `file`, `gopher`, `acrobat`, `callto`, `daap`, `itpc`, `itms`, `firefoxurl`, `hcp`, `ldap`, `mailto`, `mmst`, `mmsu`, `msbd`, `rtsp`, `mso-offdap`, `snews`, `news`, `nntp`, `outlook`, `stssync`, `rlogin`, `telnet`, `tn3270`, `shell`, `sip`
***
## Mejores prácticas
Crea apps diferentes para desarrollo, staging y producción.
Regenera las claves periódicamente y si sospechas que están comprometidas.
Solicita únicamente los permisos que realmente necesite tu app.
Revisa la Developer Console con regularidad para rastrear el uso de la API.
***
## Etiquetas de cuenta automatizada
Si tu app ejecuta una cuenta bot, puedes etiquetarla como automatizada:
1. Ve a la **Configuración** de tu cuenta bot
2. Selecciona **Tu cuenta** → **Automatización**
3. Vincula tu cuenta administradora
Esto genera confianza con los usuarios y distingue a tu bot del spam.
***
## Solución de problemas
Asegúrate de que tu URL de callback sea exactamente igual a la registrada en la Developer Console, incluido el protocolo y las barras finales. Codifica la URL en HTTP cuando la pases como parámetro de consulta.
```json theme={null}
{
"errors": [{
"code": 415,
"message": "Callback URL not approved for this client application."
}]
}
```
Si tu app aparece como suspendida, revisa tu correo electrónico para ver un aviso del equipo de la plataforma X. Usa el [formulario de ayuda de la plataforma](https://help.x.com/forms/platform) para apelar.
# Developer Console
Source: https://docs.x.com/es/fundamentals/developer-portal
Usa la Developer Console de X para gestionar proyectos y apps, monitorear el uso de la API, acceder a credenciales, invitar equipo y ver facturación.
La [Developer Console](https://console.x.com) es tu centro principal para administrar el acceso a la X API. Crea apps, genera credenciales, monitorea el uso y administra la facturación, todo en un solo lugar.
***
## Qué puedes hacer
Configura apps para obtener credenciales de la API. Configura autenticación, permisos y URLs de callback.
Rastrea el uso de la API en tiempo real. Consulta los costos por endpoint y administra tu saldo de créditos.
Crea claves de API, tokens de acceso y credenciales de OAuth para tus apps.
Compra créditos para la facturación de pago por uso. Sin suscripciones ni compromisos.
***
## Primeros pasos
Ve a [console.x.com](https://console.x.com) e inicia sesión con tu cuenta de X. Acepta el Acuerdo para Desarrolladores.
Haz clic en **New App** y proporciona un nombre y una descripción. Esto genera tus credenciales de la API.
Copia y almacena de forma segura tu API Key, API Secret y Access Tokens. Estos no se mostrarán de nuevo.
Usa tus credenciales para autenticar las solicitudes a la API. Consulta la [guía de inicio rápido](/x-api/getting-started/make-your-first-request).
**Almacena las credenciales de forma segura.** Las claves y tokens de la API solo se muestran una vez al generarlos. Usa un gestor de contraseñas o un vault seguro. Si los pierdes, deberás regenerarlos, lo que invalidará las credenciales anteriores.
***
## Facturación y créditos
La X API utiliza precios de pago por uso con un sistema basado en créditos:
| Característica | Descripción |
| :----------------------------- | :---------------------------------------------------------------------- |
| **Sin tarifas mensuales** | Paga solo por lo que uses, sin suscripciones |
| **Basado en créditos** | Compra créditos por adelantado, se descuentan al usar la API |
| **Seguimiento en tiempo real** | Monitorea uso y costos en el panel de la consola |
| **Precios por endpoint** | Distintos endpoints tienen distintos costos |
| **Deduplicación** | El mismo recurso solicitado dos veces en 24 horas solo se cobra una vez |
Consulta los precios actuales y compra créditos en la [Developer Console](https://console.x.com).
[Más información sobre precios →](/x-api/getting-started/pricing)
***
## Gestión del equipo
La gestión del equipo solo está disponible para **cuentas Enterprise**.
Las cuentas Enterprise pueden invitar a miembros del equipo para colaborar:
| Rol | Capacidades |
| :---------------- | :-------------------------------------------------------------------------- |
| **Administrador** | Acceso completo: administrar apps, facturación, miembros del equipo y roles |
| **Desarrollador** | Administrar sus propias apps, acceso de solo lectura a las apps del equipo |
Para invitar a un miembro del equipo, navega a la página Team en tu consola e ingresa su handle de X.
***
## Próximos pasos
Aprende sobre la configuración, los permisos y las credenciales de la app.
Usa tus credenciales para llamar a la API.
# Límites de tasa
Source: https://docs.x.com/es/fundamentals/rate-limits
Límites de tasa de la X API por niveles de acceso y endpoints: límites a nivel de app vs. usuario, encabezados de respuesta y prácticas de reintentos.
Los límites de tasa controlan cuántas solicitudes a la API puedes realizar en un período de tiempo determinado. Garantizan un uso justo y la estabilidad del sistema en toda la plataforma.
***
## Límites de tasa por producto
Cada producto de la X API tiene su propio enfoque de límite de tasa:
Límites por endpoint basados en ventanas de 15 minutos. Consulta tablas detalladas y consejos de recuperación.
Límites personalizados según tu acuerdo enterprise y paquete de datos.
Límites específicos para los endpoints de gestión de anuncios y analítica.
***
## Cómo funcionan los límites de tasa
| Concepto | Descripción |
| :---------------------- | :------------------------------------------------------------- |
| **Ventana de tiempo** | La mayoría de los límites se reinician cada 15 minutos |
| **Límites por usuario** | Se aplican al usar tokens de usuario de OAuth 1.0a u OAuth 2.0 |
| **Límites por app** | Se aplican al usar autenticación con Bearer Token (app-only) |
| **Por endpoint** | Cada endpoint tiene su propio límite |
***
## Comprobar tus límites
Cada respuesta de la API incluye encabezados que muestran el estado actual del límite de tasa:
```
x-rate-limit-limit: 900
x-rate-limit-remaining: 847
x-rate-limit-reset: 1705420800
```
| Encabezado | Descripción |
| :----------------------- | :---------------------------------------------------- |
| `x-rate-limit-limit` | Máximo de solicitudes permitidas en la ventana actual |
| `x-rate-limit-remaining` | Solicitudes restantes en la ventana actual |
| `x-rate-limit-reset` | Marca de tiempo Unix de cuándo se reinicia el límite |
***
## Errores de límite de tasa
Cuando superas un límite de tasa, recibirás una respuesta **429 Too Many Requests**:
```json theme={null}
{
"errors": [{
"code": 88,
"message": "Rate limit exceeded"
}]
}
```
***
## Mejores prácticas
Almacena las respuestas de la API localmente para reducir solicitudes repetidas para los mismos datos.
Cuando se aplique el límite, espera antes de reintentar. Duplica el tiempo de espera con cada reintento.
Monitorea los encabezados de límite de tasa para evitar alcanzar los límites de forma proactiva.
Para datos en tiempo real, usa filtered stream en lugar de hacer polling a los endpoints de búsqueda.
***
## Próximos pasos
Para tablas detalladas de límites de tasa por endpoint, consulta la página de límites de tasa de tu API específica:
* [Límites de tasa de la X API v2](/x-api/fundamentals/rate-limits)
* [Límites de tasa de la X Ads API](/x-ads-api/fundamentals/rate-limiting)
# Seguridad
Source: https://docs.x.com/es/fundamentals/security
Mejores prácticas de seguridad para la X API: almacenamiento de credenciales, manejo de OAuth, rotación de claves, callbacks seguros y divulgación.
Crear aplicaciones seguras protege tanto a tus usuarios como a la plataforma X. Esta guía cubre las prácticas de seguridad esenciales para los desarrolladores de la X API.
***
## Requisitos básicos
Todas las solicitudes a la API deben usar HTTPS. El HTTP plano es rechazado.
Nunca expongas claves o tokens de API en código del lado del cliente, registros o repositorios.
***
## Proteger las credenciales
Tus claves y tokens de la API son las llaves de tu app. Mantenlos seguros:
Almacena las credenciales en variables de entorno, no en el código.
```bash theme={null}
export X_API_KEY="your-api-key"
export X_API_SECRET="your-api-secret"
```
Agrega los archivos de credenciales a `.gitignore`. Usa herramientas como `git-secrets` para evitar confirmaciones accidentales.
Regenera las claves periódicamente e inmediatamente si sospechas que están comprometidas.
Solicita solamente los scopes de OAuth que tu app realmente necesite.
### Si las credenciales se ven comprometidas
1. **Regenera inmediatamente** en la [Developer Console](https://console.x.com)
2. **Revoca los tokens antiguos**: regenerar automáticamente invalida las credenciales antiguas
3. **Audita el uso**: verifica si hay actividad no autorizada en la API
4. **Actualiza tu app**: despliega las nuevas credenciales en todos los entornos
***
## Seguridad de la aplicación
### Validación de entradas
Nunca confíes en la entrada del usuario. Valida y sanitiza todos los datos antes de usarlos:
```python theme={null}
# Mal - vulnerable a inyección
query = f"from:{user_input}"
# Bien - valida la entrada primero
import re
if re.match(r'^[a-zA-Z0-9_]{1,15}$', user_input):
query = f"from:{user_input}"
```
### Codificación de salida
Escapa los datos de la X API antes de mostrarlos en HTML para prevenir XSS:
```javascript theme={null}
// Mal - vulnerable a XSS
element.innerHTML = tweet.text;
// Bien - escapar HTML
element.textContent = tweet.text;
```
### Vulnerabilidades comunes a prevenir
| Vulnerabilidad | Prevención |
| :----------------- | :-------------------------------------------------------------------------- |
| **XSS** | Escapa todo el contenido generado por usuarios antes de renderizar |
| **CSRF** | Usa tokens anti-CSRF en formularios; verifica el parámetro `state` de OAuth |
| **Inyección SQL** | Usa consultas parametrizadas, nunca concatenes la entrada del usuario |
| **Open redirects** | Valida las URLs de callback contra una lista de permitidas |
***
## Seguridad de OAuth
### Parámetro state
Usa siempre el parámetro `state` en los flujos de OAuth para prevenir CSRF:
```python theme={null}
import secrets
# Generar state antes de la autorización
state = secrets.token_urlsafe(32)
session['oauth_state'] = state
# Verificar state después del callback
if request.args.get('state') != session.get('oauth_state'):
abort(403) # State no coincide - posible CSRF
```
### Almacenamiento de tokens
| Tipo de token | Recomendación de almacenamiento |
| :----------------- | :-------------------------------------------------------- |
| **Access tokens** | Base de datos cifrada o vault seguro |
| **Refresh tokens** | Base de datos cifrada con controles de acceso adicionales |
| **Bearer tokens** | Variables de entorno o configuración segura |
***
## Prácticas de desarrollo seguro
Realiza revisiones de seguridad y pruebas de penetración periódicas.
Mantén las dependencias actualizadas. Usa herramientas para detectar paquetes vulnerables.
Registra eventos de seguridad pero nunca registres credenciales ni datos sensibles.
Configura alertas para patrones inusuales de uso de la API.
***
## Reportar problemas de seguridad
Si descubres una vulnerabilidad de seguridad que afecte a X:
**Reporta en un plazo de 48 horas.** Los usuarios de la X Developer Platform deben notificar a X en un plazo no mayor a 48 horas tras sospechar un incidente de seguridad.
Reporta vulnerabilidades en los sistemas de X a través de HackerOne.
Si tu app que usa datos de X sufre una brecha, repórtalo por el mismo canal.
***
## Lista de verificación de cumplimiento
* [ ] Todas las solicitudes a la API usan TLS/HTTPS
* [ ] Credenciales almacenadas de forma segura (no en código ni logs)
* [ ] Tokens de usuario cifrados en reposo
* [ ] Validación de entradas en todos los datos proporcionados por usuarios
* [ ] Codificación de salida para prevenir XSS
* [ ] Protección CSRF en los flujos de OAuth
* [ ] Logging de seguridad habilitado (sin datos sensibles)
* [ ] Plan de respuesta a incidentes documentado
* [ ] Dependencias actualizadas periódicamente
* [ ] Scopes mínimos de OAuth solicitados
***
## Recursos
Implementa OAuth correctamente.
Configura los permisos mínimos requeridos.
# IDs de X
Source: https://docs.x.com/es/fundamentals/x-ids
Comprende los IDs Snowflake de 64 bits en la X API para Posts y usuarios, incluyendo formato, orden, inflación de IDs y manejo seguro en clientes JavaScript.
Cada objeto en la X API —posts, usuarios, listas, DMs, spaces— tiene un ID único. Entender cómo funcionan estos IDs te ayuda a crear integraciones confiables.
***
## Formato de ID
Los IDs de X son **enteros sin signo de 64 bits** generados con un sistema llamado "Snowflake". Cada ID codifica:
* **Marca de tiempo** — Cuándo se creó el objeto
* **Número de trabajador** — Qué servidor generó el ID
* **Número de secuencia** — Orden dentro de ese milisegundo
Esto significa que los IDs están ordenados aproximadamente en el tiempo: los IDs más altos generalmente representan objetos más nuevos.
Los IDs son únicos a nivel global en toda X, no solo dentro de un mismo tipo de objeto.
***
## Representación como cadena vs. entero
**Usa siempre IDs como cadenas en tu código.** Algunos lenguajes de programación (como JavaScript) no pueden representar con precisión enteros de 64 bits.
En JavaScript, los enteros están limitados a 53 bits. Esto causa pérdida de precisión con IDs grandes:
```javascript theme={null}
// ¡Esto pierde precisión!
const id = 10765432100123456789;
console.log(id.toString()); // "10765432100123458000" — ¡incorrecto!
// Usa cadenas en su lugar
const id = "10765432100123456789";
console.log(id); // "10765432100123456789" — ¡correcto!
```
### Versiones de la API
| Versión | Formato de ID |
| :------------- | :------------------------------------------------------------------------ |
| **X API v2** | Los IDs se devuelven como cadenas por defecto |
| **X API v1.1** | Devuelve tanto `id` (entero) como `id_str` (cadena): usa siempre `id_str` |
***
## Trabajar con IDs
### Almacenar IDs
Almacena los IDs como cadenas o enteros de 64 bits en tu base de datos:
| Base de datos | Tipo recomendado |
| :------------ | :--------------------------------------------------------- |
| PostgreSQL | `BIGINT` o `TEXT` |
| MySQL | `BIGINT UNSIGNED` o `VARCHAR(20)` |
| MongoDB | Cadena |
| SQLite | `TEXT` (los enteros de SQLite tienen un máximo de 63 bits) |
### Comparar IDs
Al comparar IDs para orden cronológico:
```python theme={null}
# Python - seguro para enteros de 64 bits
if int(id1) > int(id2):
print("id1 is newer")
# JavaScript - compara como cadenas (lexicográficamente funciona para IDs de la misma longitud)
# O usa BigInt
if (BigInt(id1) > BigInt(id2)) {
console.log("id1 is newer");
}
```
***
## Tipos de ID comunes
| Objeto | Ejemplo de ID | Notas |
| :----------- | :-------------------- | :--------------------------------------------- |
| Post (Tweet) | `1234567890123456789` | También llamado Tweet ID |
| Usuario | `2244994945` | Las cuentas más antiguas tienen IDs más cortos |
| Lista | `1234567890` | |
| Space | `1YqGodQbNXDxv` | Alfanumérico, no en formato Snowflake |
| Evento de DM | `1234567890123456789` | |
***
## Recursos relacionados
Consulta los campos de ID para cada tipo de objeto.
Recupera posts por ID.
# Livestreams de la Plataforma para Desarrolladores de X
Source: https://docs.x.com/es/livestreams
Mira las grabaciones de los livestreams de la Plataforma para Desarrolladores de X, incluidos recorridos de producto, análisis técnicos en profundidad, sesiones AMA y tutoriales de integración.
Ve las grabaciones y repeticiones de transmisiones anteriores sobre la Plataforma para Desarrolladores de X, diseñadas para ayudar a la comunidad de desarrolladores a aprender y construir con nuestras herramientas.
Estas incluyen análisis en profundidad, guías de introducción y mucho más.
## Transmisiones anteriores
# Realiza tu primera solicitud
Source: https://docs.x.com/es/make-your-first-request
Envía tu primera solicitud a la X API v2 en minutos usando cURL o Postman, incluyendo autenticación, selección del endpoint y análisis de la respuesta JSON.
Esta guía te muestra paso a paso cómo realizar tu primera solicitud a la X API. Necesitarás una [cuenta de desarrollador con credenciales de app](/x-api/getting-started/getting-access) antes de comenzar.
***
## Inicio rápido con cURL
La forma más rápida de probar la API es con cURL. Vamos a buscar un usuario:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Reemplaza `$BEARER_TOKEN` con tu Bearer Token real. Obtendrás una respuesta como esta:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Guía paso a paso
En la [Developer Console](https://console.x.com), navega a tu app y copia el Bearer Token.
Comienza con alguno de estos endpoints aptos para principiantes:
| Endpoint | Qué hace |
| :------------------------------------------------ | :---------------------------------------------------- |
| [User lookup](/x-api/users/lookup/introduction) | Obtén el perfil de usuario por nombre de usuario o ID |
| [Post lookup](/x-api/posts/lookup/introduction) | Obtén un post por ID |
| [Recent search](/x-api/posts/search/introduction) | Busca posts de los últimos 7 días |
Usa cURL, Postman o tu cliente HTTP preferido:
```bash theme={null}
# Buscar un usuario por nombre de usuario
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Las respuestas son JSON. Los datos principales están en el campo `data`:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Solicita más datos con fields
Por defecto, los endpoints devuelven campos mínimos. Usa el parámetro `fields` para solicitar datos adicionales:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers?user.fields=created_at,description,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Respuesta:
```json 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 Platform",
"public_metrics": {
"followers_count": 570842,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
[Más información sobre fields →](/x-api/fundamentals/fields)
***
## Más ejemplos
```bash theme={null}
curl "https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=from:xdevelopers&tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/tweets?max_results=5" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Usar código en lugar de cURL
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/users/by/username/xdevelopers"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers)
print(response.json())
```
```javascript theme={null}
const bearerToken = "YOUR_BEARER_TOKEN";
const url = "https://api.x.com/2/users/by/username/xdevelopers";
fetch(url, {
headers: { Authorization: `Bearer ${bearerToken}` }
})
.then(res => res.json())
.then(data => console.log(data));
```
Para uso en producción, recomendamos los SDKs oficiales:
* [Python SDK](/xdks/python/overview)
* [TypeScript SDK](/xdks/typescript/overview)
Se encargan automáticamente de la autenticación, la paginación y los límites de tasa.
***
## Herramientas para pruebas
Pruebas visuales de la API con nuestra colección.
Ejemplos en múltiples lenguajes.
Documentación completa de los endpoints.
***
## Solución de problemas
* Verifica que tu Bearer Token sea correcto
* Asegúrate de que el token no haya sido regenerado
* Verifica el formato del encabezado `Authorization`: `Bearer YOUR_TOKEN`
* Es posible que tu app no tenga acceso a este endpoint
* Algunos endpoints requieren autenticación de contexto de usuario (OAuth 1.0a o 2.0)
* Verifica los permisos de tu app en la Developer Console
* Alcanzaste un límite de tasa
* Consulta el encabezado `x-rate-limit-reset` para saber cuándo reintentar
* Implementa retroceso exponencial en tu código
[Referencia completa de errores →](/x-api/fundamentals/response-codes-and-errors)
***
## Próximos pasos
Comprende OAuth para solicitudes con contexto de usuario.
Descubre lo que puedes construir.
Desarrollo más rápido con bibliotecas oficiales.
Ideas de qué crear.
# Suscríbete a las noticias para desarrolladores
Source: https://docs.x.com/es/newsletter
Suscríbete al newsletter de la Plataforma para Desarrolladores de X para recibir actualizaciones de productos, nuevos endpoints, cambios obsoletos, eventos y otras noticias para desarrolladores de API.
Regístrate para recibir correos electrónicos sobre las últimas noticias, actualizaciones de productos y eventos del equipo de Desarrolladores de X.
# Plataforma para desarrolladores de X
Source: https://docs.x.com/es/overview
Crea, analiza e innova con datos globales en tiempo real de X. Accede a posts, usuarios y tendencias vía APIs modernas con precios de pago por uso.
## Productos
Elige el nivel de acceso que se ajuste a tus necesidades.
Precios basados en créditos sin compromisos. Paga solo por lo que uses.
Endpoints de alto volumen, gestión de cuenta dedicada y límites de tasa personalizados.
Gana créditos gratuitos de la [xAI API](https://docs.x.ai) cuando compras créditos de la X API: hasta un 20% de devolución según tu gasto. [Más información](/x-api/getting-started/pricing#free-xai-api-credits)
***
## Primeros pasos
Las Owned Reads te permiten acceder a tus propios datos con un costo reducido. Las solicitudes de tus propios posts, marcadores, seguidores, likes y más tienen un precio de \$0.001 por recurso.
Obtén tus claves de API y realiza tu primera solicitud en minutos.
Explora endpoints para posts, usuarios, spaces, DMs, listas y más.
SDKs oficiales de Python y TypeScript para un desarrollo más rápido.
***
## Recursos
Guías paso a paso para casos de uso e integraciones comunes.
SDKs oficiales y bibliotecas de la comunidad para todos los lenguajes.
Obtén ayuda de la comunidad y del equipo de X.
llms.txt, skill.md, servidores MCP y recursos para el desarrollo con IA.
***
## Otros productos
Administra de forma programática campañas publicitarias, segmentación, creatividades y analítica.
# Estado de la plataforma para desarrolladores de X
Source: https://docs.x.com/es/status
Estado en vivo de la API v2 de X, las APIs Enterprise, la API de Ads y los endpoints de streaming, con incidentes actuales y disponibilidad histórica.
Todos los sistemas están operativos.
OperativoNormalNormal
***
## Historial de incidentes
### Julio de 2026
El incidente se ha resuelto. | **30 de junio, 23:00 UTC - 1 de julio, 01:00 UTC**
### Junio de 2026
El incidente se ha resuelto. | **22 de junio, 12:00 UTC - 15:41 UTC**
El incidente se ha resuelto. | **17 de junio, 02:20 UTC - 03:45 UTC**
### Abril de 2026
El incidente se ha resuelto. | **14 de abril, 21:00 UTC - 21:30 UTC**
El incidente se ha resuelto. | **1 de abril, 20:15 UTC - 20:30 UTC**
### Marzo de 2026
El incidente se ha resuelto. | **31 de marzo, 20:45 UTC - 21:00 UTC**
El incidente está en curso. | **24 de marzo, 02:00 UTC - Actual**
El incidente se ha resuelto. | **27 de marzo, 23:20 UTC - 28 de marzo, 00:56 UTC**
El incidente se ha resuelto. | **24 de marzo, 15:20:00 UTC - 18:00:00 UTC**
El incidente se ha resuelto. | **24 de marzo, 15:20:00 UTC - 18:00:00 UTC**
### Febrero de 2026
El incidente se ha resuelto. | **16 de febrero, 18:20 UTC - 19:50 UTC**
El incidente se ha resuelto. | **16 de febrero, 13:27 UTC - 14:29 UTC**
### Enero de 2026
El incidente se ha resuelto. | **29 de enero, 04:00 UTC - 04:45 UTC**
El incidente se ha resuelto. | **29 de enero, 04:00 UTC - 04:45 UTC**
El incidente se ha resuelto. | **25 de enero, 17:00 UTC - 19:00 UTC**
El incidente se ha resuelto. | **24 de enero, 16:48 UTC - 20:30 UTC**
El incidente se ha resuelto. | **23 de enero, 19:25 UTC - 20:30 UTC**
El incidente se ha resuelto. | **22 de enero, 17:30 UTC - 17:45 UTC**
El incidente se ha resuelto. | **16 de enero, 15:39 UTC - 21:00 UTC**
### Diciembre de 2025
El incidente se ha resuelto. | **5 de diciembre, 7:00 UTC - 15 de octubre, 8:40 UTC**
### Septiembre de 2025
El incidente se ha resuelto. | **10 de septiembre, 20:30 UTC - 11 de septiembre, 04:30 UTC**
El incidente se ha resuelto. | **10 de septiembre, 20:30 UTC - 10 de septiembre, 22:00 UTC**
### Agosto de 2025
El incidente se ha resuelto. | **12 de agosto, 01:00 UTC - 12 de agosto, 13:30 UTC**
### Mayo de 2025
El incidente se ha resuelto. | **26 de junio, 17:00 UTC - 26 de junio, 17:45 UTC**
El incidente se ha [resuelto](https://downdetector.com/status/google/). | **12 de junio, 15:00 UTC - 12 de junio, 23:00 UTC**
El incidente se ha resuelto. | **30 de mayo, 20:20 UTC - 30 de mayo, 21:00 UTC**
El incidente se ha resuelto. | **30 de mayo, 18:45 UTC - 30 de mayo, 21:00 UTC**
El incidente se ha resuelto. | **28 de mayo, 17:00 UTC - 28 de mayo, 21:41 UTC**
El incidente se ha resuelto. | **23 de mayo, 17:35 UTC - 27 de mayo, 00:00 UTC**
El incidente se ha resuelto. | **22 de mayo, 18:00 UTC**
El incidente se ha resuelto. | **9 de mayo, 05:00 - 9 de mayo, 07:00 UTC**
### Abril de 2025
El incidente se ha resuelto. | **2 de abril, 17:10 - 2 de abril, 20:30 UTC**
El incidente se ha resuelto. | **2 de abril, 13:09 - 2 de abril, 13:51 UTC**
### Marzo de 2025
El incidente se ha resuelto. | **10 de marzo, 12:00 - 11 de marzo, 00:00 UTC**
### Febrero de 2025
El incidente está en curso. | **6 de febrero, 00:00**
El incidente se ha resuelto. | **3 de febrero, 17:30 - 4 de febrero, 01:00 UTC**
### Enero de 2025
No hay incidentes pasados.
No hay incidentes pasados.
### Diciembre de 2024
No hay incidentes pasados.
No hay incidentes pasados.
# Casos de éxito
Source: https://docs.x.com/es/success-stories
Historias de éxito de clientes de desarrolladores y empresas que construyen con la X API, incluidos casos de estudio en marketing, investigación, salud y finanzas.
Empresas e individuos de todo el mundo han utilizado la Plataforma para Desarrolladores de X para innovar creativamente, obtener información valiosa y dar forma al futuro.
## Explora los casos de éxito
# Soporte para desarrolladores
Source: https://docs.x.com/es/support
Canales de soporte para la X API: foro de la comunidad de desarrolladores, Stack Overflow, issues de GitHub, página de estado y opciones de contacto.
Ya sea que estés solucionando un problema, buscando orientación o quieras conectarte con otros desarrolladores, te tenemos cubierto.
***
## Comunidad y ayuda
Haz preguntas, comparte tus proyectos y obtén ayuda de la comunidad de desarrolladores de X y del equipo. Este es el mejor lugar para obtener soporte sobre preguntas técnicas.
Consulta el estado operativo actual de la X API v2, las APIs Enterprise y la Developer Console.
***
## Contacto y formularios
¿Te interesa el acceso a la API a nivel enterprise? Envía tu interés y nuestro equipo se pondrá en contacto.
Obtén ayuda con preguntas de facturación para suscripciones de autoservicio y Enterprise API.
¿Preguntas sobre políticas, cumplimiento o necesitas aprobación para casos de uso específicos? Contacta a nuestro equipo de políticas.
***
## Documentación y recursos
¿Eres nuevo en la X API? Empieza aquí para obtener tus claves de API y realizar tu primera solicitud.
Referencia completa de todos los endpoints, parámetros y formatos de respuesta de la X API v2.
Aprende sobre OAuth 1.0a, OAuth 2.0 y cómo autenticar tus solicitudes a la API.
SDKs oficiales de Python y TypeScript para acelerar tu desarrollo.
Comprende los límites de tasa y cómo manejarlos en tu aplicación.
Referencia de códigos de error de la API y cómo resolver problemas comunes.
***
## Políticas y directrices
Guía práctica sobre lo que está permitido y lo que no al construir con la X API.
Los términos legales vinculantes para el acceso a la X API.
Reglas y expectativas para construir en X.
Actividades prohibidas o que requieren aprobación especial.
***
## Consejos de solución de problemas
* Comprueba que tus claves y tokens de la API sean correctos
* Asegúrate de usar el método de autenticación adecuado para el endpoint (OAuth 1.0a vs OAuth 2.0)
* Verifica que tu app tenga los permisos requeridos (lectura, escritura, acceso a DMs)
* Comprueba que tus tokens no hayan caducado: regenera si es necesario
* Revisa los encabezados `x-rate-limit-*` en las respuestas de la API para monitorear tu uso
* Implementa retroceso exponencial cuando recibas errores 429
* Almacena en caché las respuestas cuando sea posible para reducir las llamadas a la API
* Considera mejorar tu nivel de acceso para obtener mayores límites
* Consulta la [guía de Límites de tasa](/x-api/fundamentals/rate-limits) para información detallada
* Revisa las [Directrices para desarrolladores](/developer-guidelines) para entender qué pudo causar la suspensión
* Consulta tu correo electrónico para ver comunicaciones de X sobre la suspensión
* Envía una apelación a través del [formulario de soporte de políticas](https://help.x.com/forms/platform)
* Causas comunes: likes automatizados, DMs/menciones no solicitados, scraping, abuso de límites de tasa
* Revisa los [niveles de precios](/x-api/getting-started/pricing) para encontrar el plan adecuado
* Para necesidades enterprise, envía el [formulario de interés en Enterprise API](/forms/enterprise-api-interest)
* Para mejoras de acceso, usa el [formulario de mejora de caso de uso](/forms/use-case/upgrade)
* Explora la [Referencia de la API](/x-api/introduction) completa
* Comprueba si la funcionalidad existe en los [endpoints v1.1](/x-api/migrate/overview) y aún no está en v2
* Pregunta en los [Foros para desarrolladores](https://devcommunity.x.com) si tienes dudas
***
## Mantente al día
Las últimas actualizaciones, nuevas funciones y cambios de la API.
Síguenos para anuncios y noticias para desarrolladores.
Historial de incidentes pasados y sus resoluciones.
# Herramientas y bibliotecas
Source: https://docs.x.com/es/tools-and-libraries
SDKs oficiales de la X API en Python y TypeScript, herramientas CLI como xurl, servidor playground, servidores MCP para IA y bibliotecas comunitarias.
Acelera tu desarrollo con SDKs oficiales, herramientas para desarrolladores y bibliotecas de la comunidad.
***
## SDKs oficiales
Soporte async, type hints y renovación automática de tokens. Perfecto para análisis de datos y automatización.
Seguridad total de tipos y soporte de ESM. Funciona en Node.js y bundlers modernos.
### Inicio rápido
```bash theme={null}
pip install xdk
```
```python theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
for page in client.posts.search_recent(query="api", max_results=10):
if page.data and len(page.data) > 0:
print(page.data[0].text)
break
```
```bash theme={null}
npm install @xdevplatform/xdk
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ bearerToken: 'YOUR_BEARER_TOKEN' });
const userResponse = await client.users.getByUsername('XDevelopers');
console.log(userResponse.data?.username);
```
***
## Herramientas para desarrolladores
Pruebas interactivas de la API para todos los endpoints de v2.
CLI similar a curl para la X API con autenticación OAuth integrada. Sin gestión manual de tokens.
Servidor mock local para probar los endpoints de la X API v2 sin usar créditos reales.
XMCP, llms.txt, skill.md, servidor MCP de la documentación y recursos para el desarrollo con IA.
### Otras herramientas
| Herramienta | Descripción |
| :------------------------------------------------------ | :------------------------------------------------------- |
| [OpenAPI Spec](https://api.x.com/2/openapi.json) | Especificación de la API legible por máquina |
| [twitter-text](https://github.com/twitter/twitter-text) | Analizar y validar el texto de posts, contar caracteres |
| [Generador de embeds](https://publish.x.com/#) | Crea posts, timelines o botones embebibles para tu sitio |
***
## Bibliotecas de la comunidad
Bibliotecas mantenidas por la comunidad con soporte para X API v2. Consulta la documentación de cada biblioteca para conocer la cobertura actual.
| Biblioteca | Descripción |
| :----------------------------------------------------------- | :----------------------------------------------- |
| [tweepy](https://github.com/tweepy/tweepy) | Popular biblioteca de Python con soporte para v2 |
| [twarc](https://twarc-project.readthedocs.io/) | CLI y biblioteca para recolección de datos |
| [python-twitter](https://github.com/sns-sdks/python-twitter) | Wrapper simple en Python |
| [TwitterAPI](https://github.com/geduldig/TwitterAPI) | Wrapper minimalista en Python |
| Biblioteca | Descripción |
| :------------------------------------------------------------------- | :----------------------------------------------------------- |
| [node-twitter-api-v2](https://github.com/PLhery/node-twitter-api-v2) | Cliente Node.js fuertemente tipado y con todas las funciones |
| [twitter.js](https://github.com/twitterjs/twitter.js) | Biblioteca orientada a objetos para Node.js |
| [twitter-v2](https://github.com/HunterLarco/twitter-v2) | Biblioteca cliente asíncrona |
| Biblioteca | Descripción |
| :-------------------------------------------------------------- | :--------------------------- |
| [go-twitter](https://github.com/g8rswimmer/go-twitter) | Biblioteca Go para la API v2 |
| [gotwi](https://github.com/michimani/gotwi) | Wrapper Go para v2 |
| [twitter-stream](https://github.com/Fallenstedt/twitter-stream) | Wrapper de filtered stream |
| Biblioteca | Descripción |
| :---------------------------------------------------- | :----------------------------- |
| [twittered](https://github.com/redouane59/twittered) | Cliente Java para v2 |
| [twitter4j-v2](https://github.com/takke/twitter4j-v2) | Wrapper de Twitter4J v2 |
| [KTweet](https://github.com/ChromasIV/KTweet) | Biblioteca Kotlin para v2 |
| [Tweedle](https://github.com/tyczj/Tweedle) | Biblioteca Kotlin para Android |
| Biblioteca | Descripción |
| :---------------------------------------------------------------- | :-------------------------- |
| [twitter-api-v2-php](https://github.com/noweh/twitter-api-v2-php) | Cliente PHP para v2 |
| [bird-elephant](https://github.com/danieldevine/bird-elephant) | Biblioteca PHP para v2 |
| [twitteroauth](https://github.com/abraham/twitteroauth) | Biblioteca popular de OAuth |
| Biblioteca | Descripción |
| :---------------------------------------------------------------- | :------------------------ |
| [tweetkit](https://github.com/julianfssen/tweetkit) | Cliente Ruby para v2 |
| [twitter\_oauth2](https://github.com/nov/twitter_oauth2) | Biblioteca para OAuth 2.0 |
| [omniauth-twitter2](https://github.com/unasuke/omniauth-twitter2) | Estrategia para OmniAuth |
| Lenguaje | Biblioteca |
| :------------- | :--------------------------------------------------------------------------------------------------------- |
| **C#/.NET** | [Tweetinvi](https://github.com/linvi/tweetinvi), [LinqToTwitter](https://github.com/JoeMayo/LinqToTwitter) |
| **Rust** | [twitter-v2](https://github.com/jpopesculian/twitter-v2-rs) |
| **Swift** | [Twift](https://github.com/daneden/Twift/), [TwitterAPIKit](https://github.com/mironal/TwitterAPIKit) |
| **R** | [academictwitteR](https://github.com/cjbarrie/academictwitteR) |
| **PowerShell** | [BluebirdPS](https://github.com/thedavecarroll/BluebirdPS) |
Las bibliotecas de la comunidad no son mantenidas por X. Consulta sus repositorios para soporte y estado actual.
***
## Código de muestra
* [X API v2 Sample Code](https://github.com/xdevplatform/Twitter-API-v2-sample-code) — Ejemplos en Python, JavaScript, Ruby y más
* [Repositorio de Code Samples](https://github.com/xdevplatform/samples) — Ejemplos usando los XDKs oficiales
* [GitHub de X Developer](https://github.com/xdevplatform) — Repositorios y herramientas oficiales
***
## Bibliotecas de X Ads API
Para herramientas y bibliotecas específicas de la X Ads API, consulta la página de [herramientas y bibliotecas de la Ads API](/x-ads-api/tools-and-libraries).
# Recursos para agentes
Source: https://docs.x.com/es/tools/ai
Recursos para agentes de IA que usan la X API, incluidos llms.txt, skill.md, servidores MCP, specs OpenAPI y guías de integración para Grok, Cursor y Windsurf.
Recursos para conectar herramientas de IA a la X API y su documentación.
***
## Usa la X API desde herramientas de IA
Dale a tu agente de IA la capacidad de llamar directamente a los endpoints de la X API.
**Servidores MCP** — XMCP expone más de 200 endpoints de la X API como herramientas MCP invocables. Docs MCP permite a los agentes buscar y leer estos documentos sobre la marcha.
**Especificación OpenAPI** — Definición de la API legible por máquina ([https://api.x.com/2/openapi.json](https://api.x.com/2/openapi.json)) para autogenerar clientes o alimentar a los agentes.
| Recurso | Qué hace | URL |
| :------------------------- | :---------------------------------------------------------------------------------------------------- | :----------------------------------------------------------- |
| **X MCP** | Servidor MCP alojado — los agentes pueden buscar, consultar usuarios, gestionar bookmarks y mucho más | [docs.x.com/tools/mcp](/tools/mcp) |
| **Especificación OpenAPI** | Definición de la API legible por máquina para la generación de código y herramientas para agentes | [api.x.com/2/openapi.json](https://api.x.com/2/openapi.json) |
***
## Lee la documentación de la X API desde herramientas de IA
Dale a tu agente de IA contexto sobre cómo funciona la X API.
**llms.txt / llms-full.txt** — Índice de documentación y archivos Markdown de contenido completo para que los LLMs los ingieran.
**skill.md** — Resumen de capacidades (agentskills.io) que le indica a los agentes exactamente qué acciones, parámetros y restricciones existen.
**Docs MCP** — Busca y lee cualquier página de documentación directamente desde tu asistente de IA a través de MCP.
| Recurso | Qué hace | URL |
| :---------------- | :--------------------------------------------------------------------------------------- | :----------------------------------------------------------- |
| **llms.txt** | Índice de documentación — títulos de páginas, URLs y descripciones | [docs.x.com/llms.txt](https://docs.x.com/llms.txt) |
| **llms-full.txt** | Documentación completa en un solo archivo para carga de contexto completo | [docs.x.com/llms-full.txt](https://docs.x.com/llms-full.txt) |
| **skill.md** | Resumen de capacidades — acciones, entradas y restricciones | [docs.x.com/skill.md](https://docs.x.com/skill.md) |
| **Docs MCP** | Servidor MCP — los agentes pueden buscar y leer páginas de documentación sobre la marcha | [docs.x.com/mcp](https://docs.x.com/mcp) |
# llms.txt & llms-full.txt
Source: https://docs.x.com/es/tools/llms-txt
Usa llms.txt y llms-full.txt para dar a herramientas de IA como Cursor, Windsurf y Grok acceso estructurado a la documentación de la X API para una generación de código precisa.
**llms.txt** — Un índice estructurado de todas las páginas de documentación (títulos, URLs, descripciones breves). Ofrece a las herramientas de IA un mapa de lo que está disponible.
**llms-full.txt** — La documentación completa en un solo archivo Markdown para máximo contexto.
El [estándar `llms.txt`](https://llmstxt.org) es como un sitemap para IA. Ayuda a los LLMs a entender la estructura de tu documentación y encontrar contenido relevante — similar a cómo `sitemap.xml` ayuda a los motores de búsqueda.
| Archivo | Qué contiene | Ideal para |
| :-------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------- | :--------------------------------------------------- |
| [`llms.txt`](https://docs.x.com/llms.txt) | Índice raíz curado + enlaces a índices por sección | Vista general rápida y punto de entrada para agentes |
| [`x-api/llms.txt`](https://docs.x.com/x-api/llms.txt) | Más de 370 páginas de referencia de la X API v2 | Posts, Users, DMs, Streams, Compliance, etc. |
| [`enterprise-api/llms.txt`](https://docs.x.com/enterprise-api/llms.txt) | Enterprise, Account Activity, GNIP, Webhooks | Datos empresariales históricos y en tiempo real |
| [`x-ads-api/llms.txt`](https://docs.x.com/x-ads-api/llms.txt) | Ads API (campañas, creatividades, audiencias, analítica) | Publicidad y medición |
| [`xdks/python/llms.txt`](https://docs.x.com/xdks/python/llms.txt) + [`xdks/typescript/llms.txt`](https://docs.x.com/xdks/typescript/llms.txt) | Referencias completas de cliente y modelos del SDK | Desarrolladores de Python y TypeScript/JavaScript |
| [`llms-full.txt`](https://docs.x.com/llms-full.txt) | Toda la documentación como un solo archivo Markdown | Máximo contexto para razonamiento profundo |
Estos archivos (más los índices específicos por sección bajo `/x-api/llms.txt`, `/enterprise-api/llms.txt`, `/x-ads-api/llms.txt` y los XDKs) están disponibles en la raíz y bajo `/.well-known/`. Cada página de documentación admite el sufijo `.md` para Markdown limpio (ejemplo: `https://docs.x.com/x-api/posts/get-post-by-id.md`).
***
## Cómo usarlo
**Muy recomendado para agentes:** Empieza leyendo [AGENTS.md](https://docs.x.com/AGENTS.md) (o AGENT.md) para obtener orientación explícita sobre el uso.
La mayoría de las herramientas de IA aceptan URLs directamente. Solo proporciona la URL y la herramienta obtendrá y analizará el contenido:
* **Grok**: Pega `https://docs.x.com/llms-full.txt` en el chat y haz preguntas sobre la X API
* **Cursor / Windsurf**: Añade `https://docs.x.com/llms-full.txt` como contexto de documentación para tu proyecto
* **Agentes personalizados**: Obtén el archivo de forma programática e inclúyelo en tu prompt del sistema o ventana de contexto
```bash theme={null}
# Obtén el índice de documentación
curl https://docs.x.com/llms.txt
# Obtén la documentación completa
curl https://docs.x.com/llms-full.txt
# Obtén cualquier página individual como Markdown
curl https://docs.x.com/tools/llms-txt.md
```
# Servidores MCP para la X API y la documentación
Source: https://docs.x.com/es/tools/mcp
Conecta Grok, Cursor y otras herramientas de IA a la X API y a la documentación para desarrolladores de X mediante servidores MCP con xurl y búsqueda.
Hay dos servidores [MCP](https://modelcontextprotocol.io) (Model Context Protocol) disponibles para trabajar con X desde herramientas de IA:
| Servidor | Qué hace | URL |
| :----------- | :--------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |
| **X MCP** | Llama a los endpoints de la X API (buscar posts, consultar usuarios, marcadores, tendencias, noticias, Articles y más) | `https://api.x.com/mcp` (alojado; conéctate vía `xurl mcp`) |
| **Docs MCP** | Busca y lee la documentación de la X API | `https://docs.x.com/mcp` (alojado) |
***
## X MCP — X API
Conecta cualquier herramienta de IA compatible con MCP (Grok Build, Cursor, Claude, VS Code, y otras) directamente a la **X API**. El modelo puede entonces buscar en el archivo completo, consultar usuarios, gestionar marcadores, obtener tendencias y noticias, y redactar borradores de Articles — todo con los permisos de tu propia cuenta de X.
La X API expone un servidor MCP alojado con **Streamable HTTP** en **`https://api.x.com/mcp`** (protocolo `2025-06-18`, `serverInfo: xmcp`). Accedes a él a través del puente de código abierto **`xurl mcp`**, que se encarga del OAuth por ti e inyecta un Bearer token nuevo en cada llamada.
### Capacidades de un vistazo
| Categoría | Lo que el modelo puede hacer |
| ------------------------- | -------------------------------------------------------------------------------------------------- |
| **Posts** | Obtener posts, ver quiénes dieron like / repostearon / citaron, conteos recientes |
| **Búsqueda** | Búsqueda de posts en el archivo completo, búsqueda de usuarios, búsqueda de noticias |
| **Usuarios** | Resolver el usuario actual, buscar por id / handle, leer posts, timeline y menciones de un usuario |
| **Marcadores** | Listar / agregar / quitar marcadores y gestionar carpetas de marcadores |
| **Noticias y tendencias** | Obtener noticias, obtener tendencias para una ubicación (WOEID) |
| **Articles** | Crear borradores de Articles y publicarlos |
### Cómo funciona
El OAuth de X requiere *tu propia* app de desarrollador. No hay registro dinámico de clientes y `api.x.com/mcp` no anuncia el descubrimiento OAuth nativo de MCP. En lugar de apuntar tu cliente directamente a la URL, ejecutas un pequeño puente local. El puente posee la identidad de la app, realiza el inicio de sesión único y mantiene el token actualizado.
```mermaid theme={null}
flowchart LR
A["MCP client (Grok Build, Cursor, …)"] -- "stdio JSON-RPC" --> B["xurl mcp (local bridge)"]
B -- "HTTPS + Authorization: Bearer" --> C[("api.x.com/mcp")]
B <-- "OAuth2 PKCE login + auto-refresh" --> D["X OAuth"]
```
* El puente se ejecuta mediante el **lanzador de npm** (`npx`), por lo que **no hay un paso de instalación aparte**.
* En la **primera ejecución sin token en caché**, abre tu navegador para un inicio de sesión OAuth2 único, y luego almacena en caché y **refresca automáticamente** el token para siempre.
* Todos los diagnósticos van a **stderr**; **stdout permanece como un canal JSON-RPC limpio**.
### Cómo empezar
Elige una de dos rutas:
* **Simple — Bearer de solo aplicación.** Pega el Bearer token de tu app en un header `Authorization` en el cliente MCP. Sin puente, sin inicio de sesión en navegador. Endpoints de solo lectura; sin contexto de usuario (no puede actuar como tú). Funciona con clientes que admiten MCP remoto con headers personalizados.
* **Completa — puente `xurl mcp` (contexto de usuario OAuth 2.0).** Un puente local se encarga del inicio de sesión OAuth 2.0 PKCE y refresca los tokens automáticamente, para que el modelo actúe con los scopes de tu cuenta. Requerida para escrituras (marcadores, Articles) y cualquier herramienta con contexto de usuario.
#### Ruta simple (Bearer de solo aplicación)
1. **Crea una app de X** en el [X Developer Portal](https://developer.x.com).
2. **Copia el Bearer token de solo aplicación** desde la página "Keys and tokens" de la app.
3. Apunta tu cliente a `https://api.x.com/mcp` con el token como header `Authorization` — consulta [Solo aplicación (URL directa, sin puente)](#app-only-direct-url-no-bridge) más abajo para el snippet.
#### Ruta completa (puente xurl)
1. **Crea una app de X** con **OAuth 2.0** habilitado.
2. **Registra la URI de redirección** `http://localhost:8080/callback` en la app (requerida para el inicio de sesión por navegador en la primera ejecución). Para usar otra, define `REDIRECT_URI` y registra esa en su lugar.
3. **Copia tu `CLIENT_ID` y `CLIENT_SECRET`** — los colocarás en la configuración del cliente. Si alguna vez ejecutas `xurl auth oauth2` manualmente (por ejemplo, el flujo headless de más abajo), expórtalos como variables de entorno en esa shell primero — el login falla en el navegador sin ellos.
4. **Ten Node.js instalado** (para `npx`).
5. Recomendamos que **instales [xurl](https://github.com/xdevplatform/xurl)**:
```bash theme={null}
brew install --cask xdevplatform/tap/xurl # Homebrew
npm install -g @xdevplatform/xurl # npm (global)
curl -fsSL https://raw.githubusercontent.com/xdevplatform/xurl/main/install.sh | bash
```
**El primer inicio de sesión necesita un navegador.** En una máquina sin interfaz gráfica o remota, autentícate primero fuera de banda con `xurl auth oauth2 --headless` (flujo de pegar un código), y luego el puente simplemente reutilizará el token en caché. Consulta [Headless](/tools/mcp#headless--remote-machines).
### Conecta tu cliente
#### 1. Grok Build
```toml xurl bridge (~/.grok/config.toml) theme={null}
[mcp_servers.xapi]
command = "npx"
args = ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"]
enabled = true
startup_timeout_sec = 300 # give the first-run browser login time
[mcp_servers.xapi.env]
CLIENT_ID = "YOUR_X_APP_CLIENT_ID"
CLIENT_SECRET = "YOUR_X_APP_CLIENT_SECRET"
```
```toml App-only Bearer (~/.grok/config.toml) theme={null}
[mcp_servers.xapi]
url = "https://api.x.com/mcp"
enabled = true
[mcp_servers.xapi.headers]
Authorization = "Bearer YOUR_APP_ONLY_BEARER_TOKEN"
```
O agrega el puente xurl con un solo comando (los flags `-e` se convierten en el entorno del servidor, los argumentos después de `--` van a `npx`):
```bash theme={null}
grok mcp add xapi npx \
-e CLIENT_ID=YOUR_X_APP_CLIENT_ID \
-e CLIENT_SECRET=YOUR_X_APP_CLIENT_SECRET \
-- -y @xdevplatform/xurl mcp https://api.x.com/mcp
```
Verifica y lista:
```bash theme={null}
grok mcp doctor xapi # ✓ server started, ✓ handshake OK, ✓ tools discovered
grok mcp list
```
La primera vez que se invoque una herramienta (o al ejecutar `doctor`), tu navegador se abrirá para iniciar sesión en X — complétalo una vez y listo.
#### 2. Cursor
Crea `~/.cursor/mcp.json` (global, para todos los proyectos) o `.cursor/mcp.json` (solo este proyecto):
```json xurl bridge theme={null}
{
"mcpServers": {
"xapi": {
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": {
"CLIENT_ID": "YOUR_X_APP_CLIENT_ID",
"CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET"
}
}
}
}
```
```json App-only Bearer theme={null}
{
"mcpServers": {
"xapi": {
"url": "https://api.x.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_APP_ONLY_BEARER_TOKEN"
}
}
}
}
```
Luego abre **Cursor → Settings → MCP**, confirma que **xapi** muestra un punto verde y sus herramientas. En el primer uso, Cursor inicia el puente y tu navegador se abre para iniciar sesión; la lista de herramientas se completa una vez que finaliza el handshake.
#### 3. Claude Desktop
Edita `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/`, Windows: `%APPDATA%\Claude\`):
```json xurl bridge theme={null}
{
"mcpServers": {
"xapi": {
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": { "CLIENT_ID": "YOUR_X_APP_CLIENT_ID", "CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET" }
}
}
}
```
```json App-only Bearer theme={null}
{
"mcpServers": {
"xapi": {
"url": "https://api.x.com/mcp",
"headers": { "Authorization": "Bearer YOUR_APP_ONLY_BEARER_TOKEN" }
}
}
}
```
Reinicia Claude Desktop; las herramientas de X aparecen en el menú de herramientas (🔌).
#### 4. VS Code (GitHub Copilot / modo Agent)
Agrega a `.vscode/mcp.json`:
```json xurl bridge theme={null}
{
"servers": {
"xapi": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": { "CLIENT_ID": "YOUR_X_APP_CLIENT_ID", "CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET" }
}
}
}
```
```json App-only Bearer theme={null}
{
"servers": {
"xapi": {
"type": "http",
"url": "https://api.x.com/mcp",
"headers": { "Authorization": "Bearer YOUR_APP_ONLY_BEARER_TOKEN" }
}
}
}
```
#### 5. Cualquier cliente MCP
**Puente xurl (stdio):**
| Campo | Valor |
| ------------------- | ----------------------------------------------------------------------------------- |
| `command` | `npx` |
| `args` | `["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"]` |
| `env` | `CLIENT_ID`, `CLIENT_SECRET` |
| timeout de arranque | **≥ 300s** (para que el inicio de sesión en la primera ejecución pueda completarse) |
Si instalaste `xurl` de forma nativa, reemplaza `command`/`args` por `"command": "xurl", "args": ["mcp", "https://api.x.com/mcp"]`.
**Bearer de solo aplicación (HTTP remoto):**
| Campo | Valor |
| ----------------------- | ----------------------------------- |
| `url` | `https://api.x.com/mcp` |
| `headers.Authorization` | `Bearer YOUR_APP_ONLY_BEARER_TOKEN` |
### Autenticación
#### Contexto de usuario OAuth 2.0 (predeterminado)
El puente se autentica como **tú** (flujo PKCE), por lo que las herramientas actúan con los scopes de tu cuenta. Orden de resolución de credenciales: **variables de entorno `CLIENT_ID`/`CLIENT_SECRET` → la app activa en `~/.xurl`**. El puente almacena los tokens en caché en `~/.xurl` y los refresca automáticamente (incluyendo un refresh forzado tras un `401`).
#### Inicio de sesión en navegador en la primera ejecución
Sin un token en caché, el puente imprime en stderr y abre tu navegador:
```
[xurl mcp] no valid OAuth2 token; opening the browser to sign in -- complete the login to start the bridge...
[xurl mcp] authentication complete; starting bridge
```
El handshake de MCP se mantiene en espera hasta que termines — por eso los clientes necesitan un `startup_timeout_sec` generoso.
#### Headless / máquinas remotas
¿No hay un navegador accesible? Autentícate una vez fuera de banda y luego inicia el cliente:
```bash theme={null}
# Required: the env block in your client config only applies to the bridge,
# not to manual xurl runs — export the credentials in this shell first.
export CLIENT_ID="YOUR_X_APP_CLIENT_ID"
export CLIENT_SECRET="YOUR_X_APP_CLIENT_SECRET"
xurl auth oauth2 --headless # prints an auth URL; you paste back the redirect URL/code
xurl auth oauth2 --app my-app --headless # for a specific app
```
#### Solo aplicación (URL directa, sin puente)
Para endpoints de lectura puedes omitir el puente y apuntar un cliente directamente a la URL con un **Bearer token estático de solo aplicación**. Esto es útil para clientes que admiten MCP remoto con headers personalizados:
```toml theme={null}
# ~/.grok/config.toml
[mcp_servers.xapi_direct]
url = "https://api.x.com/mcp"
enabled = true
[mcp_servers.xapi_direct.headers]
Authorization = "Bearer YOUR_APP_ONLY_BEARER_TOKEN"
```
Contrapartida: sin auto-refresh y sin contexto de usuario (sin acciones como tú). Se recomienda el puente para tener funcionalidad completa.
#### Múltiples apps y cuentas
El inicio de sesión de OAuth autoriza **la cuenta de X que esté con sesión iniciada cuando se abre el navegador** — no necesariamente la cuenta que es dueña de la app. Si estás publicando en nombre de una cuenta secundaria o de bot, cambia a esa cuenta en tu navegador antes de completar el inicio de sesión (o usa `-u` para elegir un usuario previamente autorizado).
```bash theme={null}
xurl --app my-app mcp # bridge using a specific registered app
xurl mcp -u alice https://api.x.com/mcp # act as a specific OAuth2 user
```
En una configuración de cliente, agrega `"--app", "my-app"` o `"-u", "alice"` a `args`.
### Referencia de configuración
| Ajuste | Dónde | Notas |
| ----------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------ |
| `CLIENT_ID` / `CLIENT_SECRET` | `env` | Las credenciales de tu app de X (o apóyate en una app registrada en `~/.xurl`) |
| `REDIRECT_URI` | `env` | Sobrescribe el callback; debe estar registrado en la app. Por defecto `http://localhost:8080/callback` |
| `startup_timeout_sec` | configuración del cliente | Establece **≥ 300** para que el inicio de sesión en la primera ejecución pueda completarse |
| `[URL]` posicional | `args` | Por defecto `https://api.x.com/mcp` |
| `--app NAME` | `args` | Usa una app registrada específica |
| `-u, --username` | `args` | Actúa como un usuario OAuth2 específico |
Sobrescrituras avanzadas de variables de entorno (rara vez necesarias): `AUTH_URL`, `TOKEN_URL`, `API_BASE_URL`, `INFO_URL`.
### Verifica y resuelve problemas
```bash theme={null}
grok mcp doctor xapi # Grok Build: end-to-end check
# or test the bridge by hand (Ctrl-C to exit):
npx -y @xdevplatform/xurl mcp https://api.x.com/mcp
```
| Síntoma | Causa / Solución |
| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| El cliente excede el tiempo de espera al arrancar | Aumenta `startup_timeout_sec` a 300+; el puente está esperando tu inicio de sesión en el navegador |
| El navegador nunca se abre | Sin display (headless) → ejecuta primero `xurl auth oauth2 --headless`; asegúrate de que `npx` se resuelva |
| `401` / `token refresh failed` | Credenciales de la app incorrectas, o refresh token revocado → vuelve a ejecutar el inicio de sesión (`xurl auth oauth2 [--app NAME]`) |
| El navegador muestra "Something went wrong — You weren't able to give access to the App" | `CLIENT_ID`/`CLIENT_SECRET` no están definidos donde se ejecuta `xurl` → colócalos en el bloque `env` del cliente, o haz `export` en tu shell antes de ejecutar `xurl auth oauth2` manualmente |
| Error de redirect/callback en el navegador | `http://localhost:8080/callback` no está registrado en la app (o `REDIRECT_URI` no coincide) |
| `client-not-enrolled` después de iniciar sesión | La app no está en el paquete/entorno correcto de X → en el portal muévela a **Pay-per-use** + **Production** |
| `npx` descarga una versión obsoleta | Hay un mirror de registro privado por defecto → fija `--registry=https://registry.npmjs.org/` en `args` |
| Salida vacía o ilegible de las herramientas | No ejecutes el cliente con `--verbose`; stdout debe permanecer como un canal JSON-RPC limpio |
### Seguridad y mejores prácticas
* **Trata `~/.xurl` y los access tokens como secretos** — no los pegues en chats, logs ni configuraciones compartidas. Prefiere archivos `.mcp.json`/`.grok/config.toml` por proyecto que referencien variables de entorno antes que comprometer secretos en texto plano.
* **Usa una app dedicada** para MCP con solo los scopes que necesites.
* **Las escrituras cuentan para los límites de tasa** (marcadores, `article_publish`) y son más estrictas que las lecturas; espera `429`s ocasionales y aplica back off.
* **El puente es local** — tus credenciales nunca salen de tu máquina excepto como un Bearer token enviado por TLS a `api.x.com`.
***
## Docs MCP — búsqueda en la documentación
X aloja un servidor MCP para la documentación de la X API en `https://docs.x.com/mcp`. Conéctalo a tu herramienta de IA para buscar y leer páginas de documentación sin salir de tu flujo de trabajo.
### Herramientas disponibles
| Herramienta | Descripción |
| :----------- | :------------------------------------------------------------------------------------------------------ |
| `search_x` | Busca en la documentación de X información relevante, ejemplos de código, referencias de la API y guías |
| `get_page_x` | Recupera el contenido completo de una página de documentación específica por su ruta |
### Configuración
Agrega el servidor MCP de la documentación a la configuración de tu cliente MCP:
```json theme={null}
{
"mcpServers": {
"x-docs": {
"url": "https://docs.x.com/mcp"
}
}
}
```
Esto es útil cuando estás construyendo con la X API y quieres que tu asistente de IA consulte sobre la marcha detalles de endpoints, guías de autenticación o ejemplos de código.
***
## Usando ambos servidores juntos
Puedes conectar ambos servidores MCP simultáneamente. Esto le da a tu asistente de IA la capacidad de consultar la documentación *y* llamar a la API.
**Grok Build** (`~/.grok/config.toml`):
```toml theme={null}
[mcp_servers.xapi]
command = "npx"
args = ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"]
enabled = true
startup_timeout_sec = 300
[mcp_servers.xapi.env]
CLIENT_ID = "YOUR_X_APP_CLIENT_ID"
CLIENT_SECRET = "YOUR_X_APP_CLIENT_SECRET"
[mcp_servers.x-docs]
url = "https://docs.x.com/mcp"
enabled = true
```
**Estilo Cursor / Claude** (`mcp.json`):
```json theme={null}
{
"mcpServers": {
"xapi": {
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": {
"CLIENT_ID": "YOUR_X_APP_CLIENT_ID",
"CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET"
}
},
"x-docs": {
"url": "https://docs.x.com/mcp"
}
}
}
```
***
## Especificación OpenAPI
La especificación de la API legible por máquina para todos los endpoints de la X API v2.
| Recurso | URL |
| :-------------------------------- | :--------------------------------------------------------------------- |
| **Especificación OpenAPI (JSON)** | [`https://api.x.com/2/openapi.json`](https://api.x.com/2/openapi.json) |
```bash theme={null}
curl https://api.x.com/2/openapi.json -o openapi.json
```
Puedes usarla para autogenerar clientes de API, importarla en [Postman](https://www.postman.com/xapidevelopers/x-api-public-workspace/collection/34902927-2efc5689-99c6-4ab6-8091-996f35c2fd80), alimentarla en agentes de IA personalizados o validar esquemas de petición/respuesta.
# Python XDK
Source: https://docs.x.com/es/tools/python-xdk
Instala y usa la biblioteca cliente oficial Python XDK para la X API v2, incluyendo la configuración de autenticación, solicitudes paginadas y ejemplos de streaming.
El [Python XDK](https://github.com/xdevplatform/xdk-py) es la biblioteca cliente oficial para la X API v2. Maneja la autenticación, la paginación y el streaming para que puedas centrarte en construir.
Código fuente, issues y releases.
***
## Instalación
```bash theme={null}
pip install xdk
```
Requiere Python 3.8+.
***
## Guía rápida
```python theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search for posts
for page in client.posts.search_recent(query="X API", max_results=10):
if page.data and len(page.data) > 0:
print(page.data[0].text)
break
```
***
## Características clave
| Característica | Descripción |
| :------------------------------- | :------------------------------------------------------------------------------- |
| **Soporte de OAuth** | Bearer Token, OAuth 2.0 con PKCE y OAuth 1.0a |
| **Paginación automática** | Itera a través de los resultados sin manejar `next_token` manualmente |
| **Streaming** | Datos en tiempo real a través de conexiones persistentes (filtered stream, etc.) |
| **Cobertura completa de la API** | Todos los endpoints de la X API v2 — búsqueda, timelines, filtered stream y más |
***
## Autenticación
```python theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
```
```python theme={null}
from xdk import Client
from xdk.oauth2_auth import OAuth2PKCEAuth
auth = OAuth2PKCEAuth(
client_id="YOUR_CLIENT_ID",
redirect_uri="YOUR_CALLBACK_URL",
scope="tweet.read users.read offline.access"
)
auth_url = auth.get_authorization_url()
tokens = auth.fetch_token(authorization_response=callback_url)
client = Client(bearer_token=tokens["access_token"])
```
```python theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
```
***
## Métodos comunes
| Categoría | Método |
| :--------- | :----------------------------- |
| **Posts** | `client.posts.search_recent()` |
| **Users** | `client.users.get_me()` |
| **Spaces** | `client.spaces.get()` |
| **Lists** | `client.lists.get()` |
| **DMs** | `client.direct_messages.get()` |
***
## Más información
Instalación de desarrollo, requisitos previos y verificación.
Recorrido paso a paso de tu primera solicitud.
Guía detallada para todos los métodos de autenticación.
Paginación automática e iteradores.
Datos en tiempo real a través de filtered stream.
Referencia completa del cliente y los modelos.
Para ver ejemplos de código, consulta el [repositorio de ejemplos](https://github.com/xdevplatform/samples/tree/main/python).
# skill.md
Source: https://docs.x.com/es/tools/skill-md
skill.md es un resumen estructurado de capacidades que describe lo que los agentes de IA pueden hacer con la X API, usado por herramientas como agentskills.io para habilitar flujos de trabajo.
El archivo [`skill.md`](https://docs.x.com/skill.md) sigue la [especificación de agentskills.io](https://agentskills.io/specification) y describe lo que los agentes de IA pueden *hacer* con la X API. Mientras que [`llms.txt`](/tools/llms-txt) es un directorio de páginas, `skill.md` es un resumen de capacidades — enumera acciones específicas, entradas requeridas y restricciones para que los agentes puedan usar la API de forma más fiable.
***
## Qué se incluye
* **Capacidades** — lo que los agentes pueden lograr (buscar posts, crear posts, gestionar usuarios, etc.)
* **Habilidades** — acciones específicas organizadas por categoría con los parámetros requeridos
* **Flujos de trabajo** — procedimientos paso a paso para tareas comunes
* **Contexto** — información general sobre autenticación, límites de tasa y arquitectura
```bash theme={null}
# Obtén el archivo skill
curl https://docs.x.com/skill.md
```
***
## Endpoints de descubrimiento
Los agentes pueden descubrir archivos skill de forma programática a través de los endpoints well-known:
```bash theme={null}
# Endpoint de descubrimiento (spec agent-skills 0.2.0)
curl https://docs.x.com/.well-known/agent-skills/index.json
# Formato de descubrimiento original
curl https://docs.x.com/.well-known/skills/index.json
```
Puedes añadir las capacidades de la X API a cualquier agente que admita la [CLI skills](https://www.npmjs.com/package/skills):
```bash theme={null}
npx skills add https://docs.x.com
```
# TypeScript XDK
Source: https://docs.x.com/es/tools/typescript-xdk
Instala y usa la biblioteca cliente oficial TypeScript XDK para la X API v2, con ejemplos de autenticación, respuestas tipadas, paginación y streaming.
El [TypeScript XDK](https://github.com/xdevplatform/twitter-api-typescript-sdk) es la biblioteca cliente oficial para la X API v2. Seguridad de tipos completa, paginación automática y streaming basado en eventos.
Código fuente, issues y releases.
***
## Instalación
```bash npm theme={null}
npm install @xdevplatform/xdk
```
```bash yarn theme={null}
yarn add @xdevplatform/xdk
```
```bash pnpm theme={null}
pnpm add @xdevplatform/xdk
```
Requiere Node.js 16+ y TypeScript 4.5+ (si usas TypeScript).
***
## Guía rápida
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ bearerToken: 'YOUR_BEARER_TOKEN' });
const userResponse = await client.users.getByUsername('XDevelopers');
console.log(userResponse.data?.username);
```
***
## Características clave
| Característica | Descripción |
| :------------------------------- | :------------------------------------------------------------------------- |
| **Seguridad de tipos** | Definiciones completas de TypeScript para todos los endpoints y parámetros |
| **Autenticación** | Bearer Token, OAuth 2.0 con PKCE y OAuth 1.0a |
| **Paginación automática** | Soporte de iteración asíncrona para endpoints paginados |
| **Streaming** | Streaming basado en eventos con reconexión automática |
| **Cobertura completa de la API** | Users, Posts, Lists, Bookmarks, Communities y más |
***
## Autenticación
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ bearerToken: 'YOUR_BEARER_TOKEN' });
```
```typescript theme={null}
import { Client, OAuth2, generateCodeVerifier, generateCodeChallenge } from '@xdevplatform/xdk';
const oauth2 = new OAuth2({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
redirectUri: 'https://your-app.com/callback',
scope: ['tweet.read', 'users.read', 'offline.access'],
});
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
const authUrl = await oauth2.getAuthorizationUrl('state');
const tokens = await oauth2.exchangeCode(authCode, codeVerifier);
const client = new Client({ accessToken: tokens.access_token });
```
```typescript theme={null}
import { Client, OAuth1 } from '@xdevplatform/xdk';
const oauth1 = new OAuth1({
apiKey: 'YOUR_API_KEY',
apiSecret: 'YOUR_API_SECRET',
accessToken: 'YOUR_ACCESS_TOKEN',
accessTokenSecret: 'YOUR_ACCESS_TOKEN_SECRET'
});
const client = new Client({ oauth1: oauth1 });
```
***
## Métodos comunes
| Categoría | Método |
| :--------- | :------------------------------- |
| **Posts** | `client.posts.search()` |
| **Users** | `client.users.getMe()` |
| **Spaces** | `client.spaces.findSpaceById()` |
| **Lists** | `client.lists.getList()` |
| **DMs** | `client.directMessages.lookup()` |
***
## Más información
Gestores de paquetes, configuración de TypeScript y requisitos.
Guía detallada para todos los métodos de autenticación.
Iteración asíncrona y respuestas paginadas.
Streaming basado en eventos con reconexión.
Referencia completa del cliente, interfaces y tipos.
Para ver ejemplos de código, consulta el [repositorio de ejemplos](https://github.com/xdevplatform/samples/tree/main/javascript).
# xurl — CLI estilo curl con OAuth para la X API
Source: https://docs.x.com/es/tools/xurl
Instala y usa xurl, CLI estilo curl para la X API con OAuth integrado para probar endpoints, firmar solicitudes y hacer prototipos desde la terminal.
[xurl](https://github.com/xdevplatform/xurl) es una herramienta de línea de comandos estilo curl para la X API. Se encarga automáticamente de la autenticación OAuth para que puedas hacer solicitudes a la API sin gestionar tokens ni firmar solicitudes manualmente.
Código fuente, releases y documentación.
***
## Instalación
Instala con Go, o descarga un binario precompilado desde [releases](https://github.com/xdevplatform/xurl/releases).
```bash theme={null}
go install github.com/xdevplatform/xurl@latest
```
***
## Configuración
### 1. Crea una app de X
xurl se autentica usando tu propia app de desarrollador. En el [X Developer Portal](https://developer.x.com):
1. Crea (o abre) una app con **OAuth 2.0** habilitado.
2. Registra la URI de redirección `http://localhost:8080/callback` en la app.
3. Copia el **Client ID** y el **Client Secret** de la app desde la página "Keys and tokens".
### 2. Configura tus credenciales
Exporta las credenciales en la misma shell desde la que ejecutarás xurl:
```bash theme={null}
export CLIENT_ID="your-x-app-client-id"
export CLIENT_SECRET="your-x-app-client-secret"
```
### 3. Autoriza
```bash theme={null}
xurl auth oauth2
```
Esto abre un flujo de OAuth en el navegador. Una vez autorizado, xurl almacena tus tokens localmente en `~/.xurl` para que no necesites autenticarte de nuevo.
Si el navegador muestra **"Something went wrong — You weren't able to give access to the App"**, xurl inició el login sin credenciales válidas. Asegúrate de que `CLIENT_ID` y `CLIENT_SECRET` estén exportados en la shell donde ejecutaste `xurl auth oauth2`, y de que `http://localhost:8080/callback` esté registrado como URI de redirección en tu app.
***
## Uso
### Solicitudes crudas a la API
Usa xurl como curl — se encarga de los headers de autenticación automáticamente:
```bash theme={null}
# Consultar un usuario
xurl /2/users/by/username/xdevelopers
# Buscar posts recientes
xurl "/2/tweets/search/recent?query=from:xdevelopers&max_results=10"
# Crear un post
xurl -X POST /2/tweets -d '{"text": "Hello from xurl!"}'
```
### Comandos de acceso rápido
xurl incluye atajos integrados para operaciones comunes:
```bash theme={null}
# Consultar un usuario por nombre de usuario
xurl user xdevelopers
# Buscar posts recientes
xurl search "X API"
# Publicar un tweet
xurl post "Hello from xurl!"
```
***
## ¿Por qué usar xurl?
| Característica | curl | xurl |
| :----------------------- | :------------------------------------ | :-------------------------------------------- |
| **Autenticación** | Configuración manual del header OAuth | Automática — solo ejecuta `xurl auth` una vez |
| **Gestión de tokens** | Tú manejas el refresh/rotación | Almacenamiento y refresh de tokens integrados |
| **Atajos de API** | URL completa requerida | Comandos abreviados para tareas comunes |
| **Firma de solicitudes** | Firma OAuth 1.0a manual | Automática para todas las solicitudes |
***
## Uso de xurl con agentes de IA
xurl incluye un archivo [`SKILL.md`](https://github.com/xdevplatform/xurl/blob/main/SKILL.md) que describe sus capacidades en un formato legible por máquina. Los agentes de IA pueden usarlo para entender cómo invocar los comandos de xurl en tu nombre.
```bash theme={null}
npx skills add https://github.com/xdevplatform/xurl
```
***
## Relacionado
Comienza a usar la X API con cURL o SDKs.
Prueba endpoints localmente con datos simulados — sin gastar créditos de la API.
# Tutoriales
Source: https://docs.x.com/es/tutorials
Tutoriales de la X API sobre Postman, Python, R, filtered streaming, búsqueda en archivo completo, webhooks, OAuth y otros flujos comunes.
Aprende cómo explorar los Posts y menciones de un usuario usando los endpoints de timeline de Posts del usuario y de timeline de menciones del usuario en los últimos 7 días.
[**Ver tutorial**](/tutorials/explore-a-users-posts)
Aprende a empezar a usar Postman para realizar solicitudes a la X API y la X Ads API.
[**Ver tutorial**](/tutorials/postman-getting-started)
Aprende a usar R para conectarte al endpoint de user lookup y cómo trabajar con el JSON devuelto por la X API v2.
[**Ver tutorial**](/tutorials/getting-started-with-r-and-v2-of-the-x-api)
Aprende a usar el endpoint de full-archive search para buscar el historial completo de los datos públicos de X, crear un dataset de Posts geoetiquetados y paginar los resultados de una consulta.
[**Ver tutorial**](/tutorials/getting-historical-posts-using-the-full-archive-search-endpoint)
Obtén una visión general de cómo ingerir Posts a escala y usar los metadatos para clasificarlos en categorías o subcategorías específicas.
[**Ver tutorial**](/tutorials/post-processing-x-data-with-the-google-cloud-platform)
# Qué construir
Source: https://docs.x.com/es/what-to-build
Ideas y casos de uso para la X API: chatbots, paneles de analítica, moderación de contenido, herramientas de investigación y apps de comunidad.
La X API abre posibilidades en moderación, analítica, creación de comunidades y mucho más. Aquí tienes ideas para inspirar tu próximo proyecto.
***
## Construye para la seguridad y la moderación
Ayuda a crear conversaciones más sanas en X.
Crea herramientas para ayudar a los usuarios a gestionar respuestas, filtrar contenido y proteger su experiencia.
Detecta y marca contenido abusivo, ofrece herramientas de bloqueo masivo.
**Endpoints relevantes:**
* [Blocks](/x-api/users/blocks/introduction) — Bloquea y desbloquea usuarios
* [Mutes](/x-api/users/mutes/introduction) — Silencia cuentas y palabras clave
* [Hide replies](/x-api/posts/hide-replies/introduction) — Oculta respuestas no deseadas
* [Manage posts](/x-api/posts/manage-tweets/introduction) — Controla la configuración de respuestas
***
## Construye para creadores
Ayuda a las personas a expresarse y a hacer crecer su audiencia.
Programa posts, hilos y calendarios de contenido.
Sincroniza contenido entre plataformas y formatos.
Ayuda a los usuarios a componer y publicar hilos extensos.
Crea bots útiles que aporten valor a la conversación.
**Endpoints relevantes:**
* [Manage posts](/x-api/posts/manage-tweets/introduction) — Crea y elimina posts
* [Media upload](/x-api/media/quickstart/media-upload-chunked) — Sube imágenes y videos
* [Spaces](/x-api/spaces/lookup/introduction) — Descubre conversaciones de audio
***
## Construye para analítica
Ayuda a los usuarios a entender su impacto y su audiencia.
Visualiza métricas de interacción, tendencias de crecimiento y alcance.
Analiza seguidores, patrones de interacción y demografía.
Sigue hashtags, temas y volumen de conversación.
Compara cuentas, evalúa el rendimiento.
**Endpoints relevantes:**
* [Metrics](/x-api/fundamentals/metrics) — Datos de interacción y rendimiento
* [Search posts](/x-api/posts/search/introduction) — Búsqueda histórica y reciente
* [Post counts](/x-api/posts/counts/introduction) — Analítica de volumen
* [Annotations](/x-api/fundamentals/post-annotations) — Clasificación temática
***
## Construye para comunidades
Ayuda a las personas a conectarse y organizarse en torno a intereses compartidos.
Herramientas de moderación, gestión de miembros e interacción.
Organiza Spaces, eventos en vivo y actividades grupales.
Agrega y cura contenido por tema o interés.
Crea herramientas para idiomas y regiones específicas.
**Endpoints relevantes:**
* [Lists](/x-api/lists/list-lookup/introduction) — Listas curadas de cuentas
* [Spaces](/x-api/spaces/lookup/introduction) — Conversaciones de audio
* [Follows](/x-api/users/follows/introduction) — Gestión de relaciones
***
## Construye para investigación
Analiza conversaciones públicas y extrae insights.
Estudia el discurso público, la difusión de información y las tendencias.
Encuentra historias, verifica información, sigue noticias de última hora.
Monitorea el sentimiento de marca, las tendencias del sector y a los competidores.
Entrena modelos, analiza redes, estudia patrones de comportamiento.
**Endpoints relevantes:**
* [Full-archive search](/x-api/posts/search/introduction) — Busca posts desde 2006
* [Filtered stream](/x-api/posts/filtered-stream/introduction) — Posts coincidentes casi en tiempo real
* [Post annotations](/x-api/fundamentals/post-annotations) — Reconocimiento de entidades
* [Conversation ID](/x-api/fundamentals/conversation-id) — Reconstrucción de hilos
***
## Construye para hacer el bien
Usa la API para generar un impacto positivo.
Monitorea emergencias, coordina ayuda y difunde concienciación.
Crea herramientas que hagan X más accesible para todos.
Crea herramientas de aprendizaje, recursos didácticos y tutoriales.
Ayuda a las personas a estar informadas y a participar en la democracia.
***
## Construye con agentes de IA
Conecta herramientas de IA con la X API y crea flujos de trabajo inteligentes.
Usa XMCP para dar a los asistentes de IA acceso directo a los endpoints de la X API: crea posts, busca y administra cuentas mediante lenguaje natural.
Alimenta LLMs con datos de X para análisis de sentimiento, generación de contenido e informes automatizados.
Da a Grok, Cursor o tu herramienta de IA preferida contexto completo sobre la X API con llms.txt para un desarrollo más rápido.
Crea agentes que monitoreen tendencias, respondan menciones o curen contenido automáticamente.
**Comienza aquí:**
* [XMCP](/tools/mcp#xmcp--x-api-endpoints) — Servidor MCP para la X API
* [llms-full.txt](https://docs.x.com/llms-full.txt) — Alimenta tu herramienta de IA con la documentación completa
* [OpenAPI Spec](https://api.x.com/2/openapi.json) — Definición de la API legible por máquina
[Explora todos los recursos para agentes](/tools/ai)
***
## Primeros pasos
¿Listo para construir? Este es tu camino:
[Regístrate para una cuenta de desarrollador](/x-api/getting-started/getting-access) y crea una app.
[Realiza tu primera solicitud](/x-api/getting-started/make-your-first-request) y explora la API.
Selecciona un [SDK o biblioteca](/tools-and-libraries) para tu lenguaje.
¡Empieza con algo pequeño, itera y comparte lo que has creado!
***
## Comparte tu trabajo
¿Creaste algo con la X API? Nos encantaría verlo:
* Compártelo en el [Foro para desarrolladores](https://devcommunity.x.com)
* Etiqueta a [@XDevelopers](https://x.com/XDevelopers) en X
* Envíalo a nuestras [Historias de éxito](/success-stories)
# Analytics
Source: https://docs.x.com/es/x-ads-api/analytics
Obtén métricas de rendimiento de campañas en la X Ads API utilizando endpoints de analytics síncronos y asíncronos con opciones de segmentación y granularidad.
Las métricas de analytics ayudan a partners y anunciantes a comprender el rendimiento del contenido que promocionan en X. Esto incluye información como impresiones, clics, vistas de video y gasto. Además, los partners y anunciantes pueden obtener métricas detalladas para distintos segmentos de las audiencias a las que llegan.
La Ads API admite dos formas de obtener métricas detalladas de rendimiento de campañas: de manera síncrona y asíncrona. Con las llamadas síncronas de analytics, las métricas solicitadas se devuelven en la respuesta. Con los endpoints asíncronos de analytics, las métricas solicitadas están disponibles en un archivo de resultados descargable una vez que el "job" asociado haya terminado de procesarse. El endpoint síncrono admite rangos de tiempo cortos y es ideal para optimizaciones de campaña en tiempo real. Los endpoints asíncronos admiten rangos de tiempo mucho más largos y, por tanto, están pensados para obtener muchos más datos, siendo ideales para generar reportes o realizar recargas históricas (backfills).
## Detalles
### Síncrono vs. asíncrono
Las diferencias entre los endpoints de analytics síncronos y asíncronos se resumen en la siguiente tabla. Esta información está pensada para ayudar a los desarrolladores a elegir qué conjunto de endpoints utilizar.
| Característica | Síncrono | Asíncrono |
| :---------------------- | :------------------------------------------------------------------ | :----------------------------------------------------------------------------------- |
| Límite de uso | A nivel de usuario: 250 solicitudes / 15 minutos | A nivel de cuenta: 100 jobs concurrentes\* |
| Rango de tiempo | 7 días | 90 días (no segmentado) 45 días (segmentado) |
| Segmentación | No | Sí |
| La respuesta devuelve | Datos de métricas | Estado de procesamiento del job\*\* |
| Caso de uso recomendado | Optimización en tiempo real Solicitudes de interfaz de usuario | Sincronización programada periódicamente Recarga (backfill) de datos históricos |
\* Se refiere al número máximo de jobs que pueden estar en estado de procesamiento en un momento dado.
\*\* Una vez que el job haya terminado de procesarse correctamente, se devuelve una URL. Desde allí se puede descargar el archivo de resultados comprimido (gzip).
Más allá de esto, los endpoints ofrecen la misma funcionalidad.
### Casos de uso
Existen tres casos de uso principales para analytics.
1. Optimización en tiempo real: usar métricas de rendimiento para actualizar campañas activas
2. Sincronización: sincronizaciones en segundo plano programadas periódicamente
3. Onboarding de cuentas nuevas: recarga (backfill) de datos históricos
El endpoint síncrono de analytics puede utilizarse para optimización en tiempo real, con el fin de actualizar campañas en función de los cambios en las métricas durante los últimos 5 a 15 minutos. Cualquiera de los endpoints puede emplearse para sincronización de analytics. Ten en cuenta que el rango de tiempo deseado y la necesidad de segmentación determinarán qué endpoint utilizar. El onboarding de cuentas nuevas solo debe realizarse con los endpoints asíncronos de analytics. (El endpoint síncrono de analytics nunca debe usarse para obtener grandes volúmenes de datos).
Los endpoints asíncronos de analytics pueden alimentar dashboards y otros elementos de interfaz de usuario si las métricas se sincronizan con un proceso de backend. Tu implementación debe evitar llamar a los endpoints asíncronos de analytics para responder a solicitudes de la interfaz de usuario.
### Opciones de la solicitud
Las solicitudes de analytics están acotadas a cuentas de anuncios y, por tanto, requieren el ID de la cuenta en la ruta del recurso. Las opciones de la solicitud, listadas a continuación, se especifican como parámetros de consulta. Se requieren los siguientes tipos de valores.
* Entidades: el tipo de entidad y hasta 20 IDs de entidad para los que deseas solicitar analytics
* Rango de tiempo: las horas de inicio y fin, expresadas en ISO 8601
* **Nota:** deben expresarse en horas completas
* Grupos de métricas: uno o más conjuntos de métricas relacionadas (consulta Metrics and Segmentation para ver la lista de métricas dentro de cada grupo)
* Granularidad: especifica el nivel de agregación con el que se deben devolver las métricas
* Placement: determina si las métricas se obtienen para anuncios servidos dentro o fuera de X
* **Nota:** solo se puede especificar un único valor de placement por solicitud
Usa los parámetros de solicitud `start_time` y `end_time` para especificar un rango de tiempo. Estos valores deben alinearse con la granularidad especificada de la siguiente manera.
1. `TOTAL`: especifica cualquier rango de tiempo (dentro de los límites del endpoint)
2. `DAY`: tanto el valor de inicio como el de fin deben alinearse con la medianoche en la zona horaria de la cuenta
3. `HOUR`: especifica cualquier rango de tiempo (dentro de los límites del endpoint)
La hora de fin es exclusiva. Por ejemplo, una solicitud con `start_time=2026-01-01T00:00:00Z` y `end_time=2026-01-02T00:00:00Z` devolverá métricas de analytics correspondientes a un solo día (no dos), ya que este rango de tiempo cubre únicamente un período de 24 horas.
**Segmentación**
Disponible únicamente a través de nuestros endpoints asíncronos de analytics, la segmentación permite a partners y anunciantes obtener métricas desglosadas por determinados valores de segmentación. Para solicitar métricas segmentadas, utiliza el parámetro de solicitud `segmentation_type`. Para más detalles sobre las opciones de segmentación, consulta [Metrics and Segmentation](/x-ads-api/analytics#metrics-and-segmentation).
## Preguntas frecuentes
¿Por qué los números de la Ads API no coinciden con lo que se muestra en la interfaz de X Ads?
* Asegúrate de haber solicitado los datos para todos los placements: `ALL_ON_TWITTER`, `SPOTLIGHT` y `TREND`.
* Recuerda que las horas de fin en la Ads API son exclusivas; en la interfaz de Ads son inclusivas
¿Por qué los números cambian dependiendo de cuándo solicito los datos?
* En cuanto las métricas de reporte están disponibles, puedes obtenerlas. Están disponibles casi en tiempo real. Sin embargo, estos resultados iniciales son estimaciones y, por tanto, se espera que cambien. Las métricas se finalizan después de 24 horas, salvo los datos de gasto.
* Las métricas de gasto suelen ser definitivas dentro de los 3 días siguientes al evento. No obstante, procesamos los datos de facturación hasta 14 días desde la fecha del evento (por filtrado de spam, por ejemplo).
¿Cómo puedo determinar qué IDs de entidad solicitar para un período de tiempo específico?
* Usa el [endpoint Active Entities](/x-ads-api/analytics#active-entities-2)
¿Por qué todos los valores en la respuesta de analytics son `null`?
* Es probable que la campaña no se haya servido durante el período de tiempo solicitado
* Usa el [endpoint Active Entities](/x-ads-api/analytics#active-entities-2) para determinar qué entidades consultar para analytics y en qué período de tiempo
¿Por qué la API muestra valores `null` mientras que la UI muestra 0?
* La UI elige mostrar estos valores como 0, pero los valores son equivalentes
¿Cómo puedo solicitar métricas asociadas con un placement granular, como la timeline de X?
* Admitimos los siguientes valores de placement en analytics: `ALL_ON_TWITTER`, `SPOTLIGHT` y `TREND`
¿Es posible obtener métricas para entidades eliminadas o pausadas?
* Sí. El estado de la entidad no afecta la disponibilidad de las métricas de analytics.
¿Por qué los valores segmentados no coinciden con los no segmentados?
* *No* se espera que los datos segmentados sumen al 100 % de los datos no segmentados, debido a cómo se deriva esta información.
¿Por qué los valores segmentados de la API no coinciden con lo que muestra la UI de Ads Manager?
* La API devuelve métricas segmentadas acotadas al tipo de entidad específico que consultas (CAMPAIGN, PROMOTED\_TWEET). La UI de Ads Manager agrega los datos entre tipos de entidades. Son vistas diferentes de los mismos datos subyacentes y este es el comportamiento esperado.
¿Es posible solicitar datos segmentados por múltiples dimensiones?
* No admitimos la segmentación múltiple.
## Buenas prácticas
Algunas buenas prácticas al recopilar datos de [analytics](/x-ads-api/analytics) de la Ads API.
### Rate Limiting y reintentos
* En consultas que están limitadas por rate limit (las que devuelven un código de estado `HTTP 429`), debes inspeccionar el header `x-rate-limit-reset` y reintentar solo en o después del momento indicado.
* En consultas que resulten en un código de estado HTTP 503 Service Unavailable, debes inspeccionar el header `retry-after` y reintentar solo después del momento indicado.
* Las aplicaciones que no respeten los tiempos indicados para los reintentos podrían ver su acceso a la Ads API revocado o limitado sin previo aviso.
### Métricas de analytics en pocas palabras
* Todas las métricas de analytics quedan fijas y no cambiarán después de 24 horas, salvo `billed_charge_local_micro`.
* La métrica `billed_charge_local_micro` es una estimación hasta 3 días después de que se devuelven los datos.
* Tras 24 horas, esta métrica puede disminuir debido a créditos por sobregasto (anuncios servidos después del `end_time` indicado) y por eventos facturables que se determinen como junk. Esta métrica cambia mínimamente después de 24 horas.
* Consulta [Analytics](/x-ads-api/analytics) para más información.
### Obtención de datos no segmentados en tiempo real
* Proporciona siempre tanto un `start_time` como un `end_time`.
* No extraigas datos para ninguna entidad con más de 7 días de antigüedad.
* Solicita los datos (idealmente) con granularidad `HOUR`, ya que siempre puedes agregar y sumar métricas para obtener granularidades `DAY` y `TOTAL`.
* Solicita los datos (idealmente) a nivel de `line_items` y `promoted_tweets`, ya que siempre puedes agregar y sumar estas métricas para obtener totales en toda la jerarquía de entidades de anuncios (es decir, a nivel de campaña, instrumento de financiación o cuenta).
* Guarda y almacena los valores de las métricas de analytics de tu lado (localmente).
* No consultes repetidamente datos con más de 30 días de antigüedad. Estos datos no cambiarán y deben almacenarse localmente.
* Todos los datos no segmentados son en tiempo real y deberían estar disponibles a los pocos segundos de ocurrir un evento.
* Agrupa las métricas de conversión y las que no son de conversión en solicitudes separadas.
### Obtención de datos segmentados
* Consulta las directrices proporcionadas anteriormente en "Obtención de datos no segmentados en tiempo real". A continuación se ofrecen recomendaciones adicionales.
* Para la mayoría de los tipos de datos segmentados, es posible que los datos no estén completos durante hasta 1 hora en ocasiones. Los datos segmentados por `INTERESTS` pueden retrasarse hasta 12 horas.
* No se espera que los datos segmentados sumen al 100 % de los datos no segmentados, debido a cómo se deriva esta información.
### Obtención de datos históricos
* Al realizar backfill de datos (es decir, al añadir una nueva cuenta de anunciante), es posible que tengas que hacer varias solicitudes en bloques más pequeños de `start_time` y `end_time`.
* Limita tus extracciones a ventanas de fechas de 30 días.
* Regula (throttle) estas solicitudes y distribúyelas en el tiempo para no agotar tus rate limits con estas extracciones.
### Ejemplo
Puedes encontrar un script de ejemplo que demuestra algunas de estas buenas prácticas (`fetch_stats`) en nuestro repositorio de [ads-platform-tools en GitHub](https://github.com/xdevplatform/ads-platform-tools).
## Métricas por objetivo
Las métricas aplicables a una entidad dependen del [objetivo de la campaña](/x-ads-api/campaign-management). Usa esta guía para determinar los grupos de métricas relevantes que debes obtener para cada tipo de objetivo, así como la forma de calcular métricas derivadas adicionales.
### `ENGAGEMENTS`
**Grupos de métricas relevantes:** `ENGAGEMENT` y `BILLING`.
| | |
| :--------------- | :-------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| Engagement Rate | `engagements/impressions` |
| CPE | `billed_charge_local_micro/engagements` |
### `WEBSITE_CLICKS` y `WEBSITE_CONVERSIONS`
**Grupos de métricas relevantes:** `ENGAGEMENT`, `BILLING` y `WEB_CONVERSION`.
| | |
| :---------------- | :----------------------------------------------------------------------------------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Click Rate | `clicks/impressions` |
| CPLC | `billed_charge_local_micro/clicks` |
| Total Conversions | `conversion_custom` + `conversion_site_visits` + `conversion_sign_ups` + `conversion_downloads` + `conversion_purchases` |
| Conversion Rate | Total Conversions / `impressions` |
| CPA | `billed_charge_local_micro` / Total Conversions |
### `APP_INSTALLS`
**Grupos de métricas relevantes:** `ENGAGEMENT`, `BILLING`, `MOBILE_CONVERSION` y `LIFE_TIME_VALUE_MOBILE_CONVERSION`. `VIDEO` también es aplicable si se utiliza una video app card en los creativos.
| | |
| :--------------- | :----------------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| CPM | `billed_charge_local_micro/impressions/1000` |
| App Click Rate | `app_clicks/impressions` |
| CPAC | `billed_charge_local_micro/app_clicks` |
| CPI | `billed_charge_local_micro/mobile_conversion_installs` |
### `FOLLOWERS`
**Grupos de métricas relevantes:** `ENGAGEMENT` y `BILLING`.
| | |
| :--------------- | :------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Follow Rate | `follows/impressions` |
| CPF | `billed_charge_local_micro/follows` |
### `VIDEO_VIEWS`
**Grupos de métricas relevantes:** `ENGAGEMENT`, `BILLING` y `VIDEO`.
| | |
| :--------------- | :-------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Video Rate | `video_total_views/impressions` |
| Cost Per View | `billed_charge_local_micro/video_total_views` |
### `VIDEO_VIEWS_PREROLL`
**Grupos de métricas relevantes:** `ENGAGEMENT`, `BILLING` y `VIDEO`.
| | |
| :--------------- | :-------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Video Rate | `video_total_views/impressions` |
| Cost Per View | `billed_charge_local_micro/video_total_views` |
## Métricas y segmentación
Este documento es una visión general de las métricas disponibles desde nuestro [Analytics](/x-ads-api/analytics) para cada tipo de entidad, así como la segmentación disponible para cada métrica.
| | | | | | | |
| :------------------- | :-------------------------- | :-------------------- | :---------------- | :---------------------------------- | :---------------------------------------- | :------------------------------------------------------------------------ |
| | Grupos de métricas | | | | | |
| Entidad | [`ENGAGEMENT`](#engagement) | [`BILLING`](#BILLING) | [`VIDEO`](#VIDEO) | [`WEB_CONVERSION`](#WEB_CONVERSION) | [`MOBILE_CONVERSION`](#MOBILE_CONVERSION) | [`LIFE_TIME_VALUE_MOBILE_CONVERSION`](#LIFE_TIME_VALUE_MOBILE_CONVERSION) |
| `ACCOUNT` | ✔\* | | | | | |
| `FUNDING_INSTRUMENT` | ✔\* | ✔ | | | | |
| `CAMPAIGN` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
| `LINE_ITEM` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
| `PROMOTED_TWEET` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
\*Algunas métricas de la familia `ENGAGEMENT` no están disponibles a nivel de cuenta ni de instrumento de financiación. Consulta la sección `ENGAGEMENT` para más detalles.
### Métricas disponibles por grupo de métricas
#### `ENGAGEMENT`
| | | | | |
| :---------------------- | :------------------------------------------------------------------------------------- | :---------------------- | :------------ | :------------------------------------------- |
| Métrica | Descripción | Segmentación disponible | Tipo de dato | Disponible para Account / Funding Instrument |
| `engagements` | Número total de engagements | ✔ | Array de ints | ✔ |
| `impressions` | Número total de impresiones | ✔ | Array de ints | ✔ |
| `retweets` | Número total de reposts | ✔ | Array de ints | ✔ |
| `replies` | Número total de respuestas | ✔ | Array de ints | ✔ |
| `likes` | Número total de likes | ✔ | Array de ints | ✔ |
| `follows` | Número total de follows | ✔ | Array de ints | ✔ |
| `card_engagements` | Número total de engagements de card | ✔ | Array de ints | |
| `clicks` | Número total de clics, incluyendo favoritos y otros engagements | ✔ | Array de ints | |
| `app_clicks` | Número de intentos de instalación o apertura de la app | ✔ | Array de ints | |
| url\_clicks | Total de clics en el enlace o la Website Card de un anuncio, incluyendo los orgánicos. | ✔ | Array de ints | |
| `qualified_impressions` | Número total de impresiones cualificadas | ✔ | Array de ints | |
| `carousel_swipes` | Total de swipes en imágenes o videos de Carrusel | ✔ | Array de ints | |
#### `BILLING`
| | | | |
| :-------------------------- | :------------------------------------- | :---------------------- | :------------ |
| Métrica | Descripción | Segmentación disponible | Tipo de dato |
| `billed_engagements` | Número total de engagements facturados | ✔ | Array de ints |
| `billed_charge_local_micro` | Gasto total en micros | ✔ | Array de ints |
#### `VIDEO`
Aviso sobre cambios en la definición de métricas de video:
La métrica `video_total_views` dentro del grupo de métricas `VIDEO` reportará cualquier vista que esté visible al menos al 50 % durante 2 segundos, según el estándar MRC.
Nuestra definición original de vista de video del 100 % visible durante al menos 3 segundos seguirá estando disponible como una nueva métrica `video_3s100pct_views` dentro del grupo de métricas `VIDEO`. Para continuar pujando y cobrando con base en la definición original de vista, usa la nueva bid\_unit `VIEW_3S_100PCT` disponible.
| | | | |
| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------ | :---------------------- | :------------ |
| Métrica | Descripción | Segmentación disponible | Tipo de dato |
| `video_total_views` | Número total de vistas de video | ✔ | Array de ints |
| `video_views_25` | Número total de vistas en las que se reprodujo al menos el 25 % del video. | ✔ | Array de ints |
| `video_views_50` | Número total de vistas en las que se reprodujo al menos el 50 % del video. | ✔ | Array de ints |
| `video_views_75` | Número total de vistas en las que se reprodujo al menos el 75 % del video. | ✔ | Array de ints |
| `video_views_100` | Número total de vistas en las que se reprodujo el 100 % del video. | ✔ | Array de ints |
| `video_cta_clicks` | Total de clics en la llamada a la acción | ✔ | Array de ints |
| `video_content_starts` | Número total de inicios de reproducción de video | ✔ | Array de ints |
| `video_3s100pct_views` | Número total de vistas en las que se reprodujeron al menos 3 segundos estando el 100 % en pantalla (legacy `video_total_views`) | ✔ | Array de ints |
| `video_6s_views` | Número total de vistas en las que se reprodujeron al menos 6 segundos del video | ✔ | Array de ints |
| `video_15s_views` | Número total de vistas en las que se reprodujeron al menos 15 segundos del video o el 95 % de la duración total | ✔ | Array de ints |
#### `WEB_CONVERSION`
| | | | |
| :----------------------- | :----------------------------------------------------------------------------------------------------- | :---------------------- | :----------- |
| Métrica | Descripción | Segmentación disponible | Tipo de dato |
| `conversion_purchases` | Número de conversiones del tipo PURCHASE y el correspondiente importe de venta y cantidad de pedido | Solo `PLATFORMS` | Objeto JSON |
| `conversion_sign_ups` | Número de conversiones del tipo SIGN\_UP y el correspondiente importe de venta y cantidad de pedido | Solo `PLATFORMS` | Objeto JSON |
| `conversion_site_visits` | Número de conversiones del tipo SITE\_VISIT y el correspondiente importe de venta y cantidad de pedido | Solo `PLATFORMS` | Objeto JSON |
| `conversion_downloads` | Número de conversiones del tipo DOWNLOAD y el correspondiente importe de venta y cantidad de pedido | Solo `PLATFORMS` | Objeto JSON |
| `conversion_custom` | Número de conversiones del tipo CUSTOM y el correspondiente importe de venta y cantidad de pedido | Solo `PLATFORMS` | Objeto JSON |
#### `MOBILE_CONVERSION`
Las estadísticas de conversión móvil solo están disponibles para las cuentas de anunciante habilitadas para MACT.
| | | | |
| :----------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------- | :----------- |
| Métrica | Descripción | Segmentación disponible | Tipo de dato |
| `mobile_conversion_spent_credits` | Desglose de conversiones móviles del tipo SPENT\_CREDIT por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_installs` | Desglose de conversiones móviles del tipo INSTALL por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_content_views` | Desglose de conversiones móviles del tipo CONTENT\_VIEW por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_add_to_wishlists` | Desglose de conversiones móviles del tipo ADD\_TO\_WISHLIST por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_checkouts_initiated` | Desglose de conversiones móviles del tipo CHECKOUT\_INITIATED por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_reservations` | Desglose de conversiones móviles del tipo RESERVATION por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_tutorials_completed` | Desglose de conversiones móviles del tipo TUTORIAL\_COMPLETED por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_achievements_unlocked` | Desglose de conversiones móviles del tipo ACHIEVEMENT\_UNLOCKED por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_searches` | Desglose de conversiones móviles del tipo SEARCH por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_add_to_carts` | Desglose de conversiones móviles del tipo ADD\_TO\_CART por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_payment_info_additions` | Desglose de conversiones móviles del tipo PAYMENT\_INFO\_ADDITION por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_re_engages` | Desglose de conversiones móviles del tipo RE\_ENGAGE por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_shares` | Desglose de conversiones móviles del tipo SHARE por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_rates` | Desglose de conversiones móviles del tipo RATE por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_logins` | Desglose de conversiones móviles del tipo LOGIN por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_updates` | Desglose de conversiones móviles del tipo UPDATE por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_levels_achieved` | Desglose de conversiones móviles del tipo LEVEL\_ACHIEVED por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_invites` | Desglose de conversiones móviles del tipo INVITE por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| `mobile_conversion_key_page_views` | Desglose de conversiones móviles del tipo KEY\_PAGE\_VIEW por post\_view y post\_engagement | ✔ | Objeto JSON |
| mobile\_conversion\_downloads | Desglose de conversiones móviles del tipo DOWNLOAD por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| mobile\_conversion\_purchases | Desglose de conversiones móviles del tipo PURCHASE por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| mobile\_conversion\_sign\_ups | Desglose de conversiones móviles del tipo SIGN\_UP por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
| mobile\_conversion\_site\_visits | Desglose de conversiones móviles del tipo SITE\_VISIT por post\_view, post\_engagement, assisted, order\_quantity y sale\_amount | ✔ | Objeto JSON |
#### `LIFE_TIME_VALUE_MOBILE_CONVERSION`
Las estadísticas de conversión móvil de por vida (lifetime) solo están disponibles para las cuentas de anunciante habilitadas para MACT.
| | | | |
| :-------------------------------------------------------- | :---------------------------------------------------------------- | :---------------------- | :----------- |
| Métrica | Descripción | Segmentación disponible | Tipo de dato |
| `mobile_conversion_lifetime_value_purchases` | Desglose de conversiones móviles del tipo PURCHASE | | Objeto JSON |
| `mobile_conversion_lifetime_value_sign_ups` | Desglose de conversiones móviles del tipo SIGN\_UP | | Objeto JSON |
| `mobile_conversion_lifetime_value_updates` | Desglose de conversiones móviles del tipo UPDATE | | Objeto JSON |
| `mobile_conversion_lifetime_value_tutorials_completed` | Desglose de conversiones móviles del tipo TUTORIAL\_COMPLETED | | Objeto JSON |
| `mobile_conversion_lifetime_value_reservations` | Desglose de conversiones móviles del tipo RESERVATION | | Objeto JSON |
| `mobile_conversion_lifetime_value_add_to_carts` | Desglose de conversiones móviles del tipo ADD\_TO\_CART | | Objeto JSON |
| `mobile_conversion_lifetime_value_add_to_wishlists` | Desglose de conversiones móviles del tipo ADD\_TO\_WISHLIST | | Objeto JSON |
| `mobile_conversion_lifetime_value_checkouts_initiated` | Desglose de conversiones móviles del tipo CHECKOUT\_INITIATED | | Objeto JSON |
| `mobile_conversion_lifetime_value_levels_achieved` | Desglose de conversiones móviles del tipo LEVEL\_ACHIEVED | | Objeto JSON |
| `mobile_conversion_lifetime_value_achievements_unlocked` | Desglose de conversiones móviles del tipo ACHIEVEMENT\_UNLOCKED | | Objeto JSON |
| `mobile_conversion_lifetime_value_shares` | Desglose de conversiones móviles del tipo SHARE | | Objeto JSON |
| `mobile_conversion_lifetime_value_invites` | Desglose de conversiones móviles del tipo INVITE | | Objeto JSON |
| `mobile_conversion_lifetime_value_payment_info_additions` | Desglose de conversiones móviles del tipo PAYMENT\_INFO\_ADDITION | | Objeto JSON |
| `mobile_conversion_lifetime_value_spent_credits` | Desglose de conversiones móviles del tipo SPENT\_CREDIT | | Objeto JSON |
| `mobile_conversion_lifetime_value_rates` | Desglose de conversiones móviles del tipo RATE | | Objeto JSON |
### Segmentación
La elaboración de reportes con segmentación permite obtener métricas desglosadas por los valores de un tipo de segmentación determinado. La segmentación solo está disponible a través de [consultas asíncronas de analytics](/x-ads-api/analytics#asynchronous-analytics) debido a su considerable complejidad añadida.
A partir de mayo de 2026, solo están habilitados los siguientes tipos de segmentación. METROS devuelve códigos DMA de Nielsen como cadenas numéricas (819 = Seattle-Tacoma). Los tipos de segmentación geográfica como METROS requieren el parámetro country (96683cc9126741d1 para US).
| | |
| :------------------- | :---------------------------- |
| Tipo de segmentación | Parámetro `country` requerido |
| `AGE` | |
| `GENDER` | |
| `METROS` | ✔ |
| `PLATFORMS` | |
## Métricas derivadas
Las métricas de campaña dependen de su [objetivo de campaña](/x-ads-api/campaign-management). Usa esta guía para determinar cómo calcular métricas derivadas para utilizarlas en función de los objetivos establecidos.
Cualquier `metric` sin llaves es una métrica que devuelven los endpoints de [analytics](/x-ads-api/analytics#synchronous-analytics) de la Ads API. Cualquier nombre rodeado por `{llaves}` indica una métrica derivada para esa categoría.
### ENGAGEMENTS
| | |
| :------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `{Total Engagements}` | `promoted_account_follows + promoted_tweet_search_engagements + promoted_tweet_timeline_engagements + promoted_tweet_profile_engagements` o `promoted_account_follows + promoted_tweet_search_clicks + promoted_tweet_search_replies + promoted_tweet_search_retweets + promoted_tweet_search_follows + promoted_tweet_timeline_clicks + promoted_tweet_timeline_replies + promoted_tweet_timeline_retweets + promoted_tweet_timeline_follows + promoted_tweet_profile_clicks + promoted_tweet_profile_replies + promoted_tweet_profile_retweets + promoted_tweet_profile_follows` |
| `{Engagement Rate}` | `{Total Engagements} / {Impressions}` |
| `billed_charge_local_micro / {Total Engagements}` | |
### WEBSITE\_CLICKS
| | |
| :------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `{Link Clicks}` | `promoted_tweet_search_url_clicks + promoted_tweet_timeline_url_clicks + promoted_tweet_profile_url_clicks` |
| `{Click Rate}` | `{Link Clicks} / {Impressions}` |
| `billed_charge_local_micro / {Link Clicks}` | |
| `conversion_site_visits` | |
| `{Conversion Rate}` | `conversion_site_visits / {Impressions}` |
| `billed_charge_local_micro / conversion_site_visits` | |
### APP\_INSTALLS
| | |
| :------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `{App Clicks}` | `promoted_tweet_app_install_attempts + promoted_tweet_app_open_attempts + promoted_tweet_timeline_url_clicks + promoted_tweet_search_url_clicks` |
| `{App Click Rate}` | `{App Clicks} / {Impressions}` |
| `billed_charge_local_micro / {App Clicks}` | |
| `billed_charge_local_micro / mobile_conversion_installs` | |
### FOLLOWERS
| | |
| :----------------------------------------------------- | :------------------------------ |
| Métrica derivada | Cálculo con la métrica expuesta |
| `promoted_account_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `promoted_account_follows` | |
| `{Follow Rate}` | `promoted_account_follow_rate` |
| `billed_charge_local_micro / promoted_account_follows` | |
### VIDEO\_VIEWS
| | |
| :------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| | `billed_charge_local_micro / {Impressions} / 1000` |
| `{Video Views}` | `promoted_video_total_views` |
| `{Video Rate}` | `promoted_video_total_views / {Impressions}` |
| `{Cost Per View}` | `billed_charge_local_micro / promoted_video_total_views` |
### QUALIFIED\_IMPRESSIONS
| | |
| :------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| Métrica derivada | Cálculo con la métrica expuesta |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| | `billed_charge_local_micro / {Impressions} / 1000` |
| `{Qualified Impressions}` | `promoted_tweet_timeline_qualified_impressions + promoted_tweet_search_qualified_impressions + promoted_tweet_profile_qualified_impressions` |
| `{Qualified Impression Rate}` | `{Qualified Impressions} / {Impressions}` |
| `{Cost Per 1000 Qualified Impressions }` | `billed_charge_local_micro / {Qualified Impressions} / 1000` |
### CUSTOM
Para `placement_type` `PROMOTED_ACCOUNT`, consulta el objetivo `FOLLOWERS` indicado anteriormente. Para todos los demás placements con este objetivo, consulta `ENGAGEMENTS` para las métricas derivadas correspondientes.
## Guías
### Active Entities
#### Introducción
El [endpoint Active Entities](/x-ads-api/analytics#get-stats-accounts-account-id-active-entities) está pensado para usarse junto con nuestros endpoints de analytics [síncronos](/x-ads-api/analytics#get-stats-accounts-account-id) y [asíncronos](/x-ads-api/analytics#asynchronous-analytics), ya que proporciona información sobre qué campañas solicitar para analytics. Lo hace devolviendo detalles sobre las entidades de anuncios y cuándo cambiaron sus métricas. Usar este endpoint simplificará enormemente tu código y la lógica de obtención de analytics.
Esta guía incluye información y contexto sobre el endpoint y su fuente de datos. También proporciona [directrices de uso](#usage) y una serie de [solicitudes de ejemplo](#example) que muestran cómo usar Active Entities junto con nuestros endpoints de analytics. La [sección Resumen](#summary) ofrece una descripción de alto nivel del enfoque recomendado.
#### Datos
Cada vez que cambia la métrica de una entidad de anuncios, registramos información sobre ese cambio. Estos eventos de cambio se almacenan en buckets horarios e incluyen detalles sobre la entidad y el momento al que aplica el cambio. Esto último es necesario porque los eventos de cambio no siempre corresponden al momento en que fueron registrados. Los ajustes de facturación son una razón habitual para esto, pero hay otras.
#### Endpoint
### Solicitud
Las solicitudes de Active Entities están acotadas a cuentas de anuncios y tienen tres parámetros de consulta obligatorios: `entity`, `start_time` y `end_time`.
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=PROMOTED_TWEET&start_time=2026-03-05T00:00:00Z&end_time=2026-03-06T00:00:00Z"`
Se admiten los siguientes valores de `entity`: `CAMPAIGN`, `FUNDING_INSTRUMENT`, `LINE_ITEM`, `PROMOTED_ACCOUNT` y `PROMOTED_TWEET`. Esto refleja los tipos de entidad que admiten nuestros endpoints de analytics.
Los valores `start_time` y `end_time` deben expresarse en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) y especifican qué buckets horarios consultar. Deben expresarse en horas completas.
Este endpoint también admite tres parámetros opcionales que pueden usarse para filtrar los resultados: `funding_instrument_ids`, `campaign_ids` y `line_item_ids`. Funcionan en todos los niveles de la jerarquía de anuncios y con cualquier tipo de `entity` especificado.
### Respuesta
La respuesta de Active Entities para la solicitud anterior se muestra a continuación.
```json theme={null}
{
"request": {
"params": {
"account_id": "18ce54d4x5t",
"entity": "PROMOTED_TWEET",
"start_time": "2026-03-05T00:00:00Z",
"end_time": "2026-03-06T00:00:00Z"
}
},
"data": [
{
"entity_id": "2r0wxw",
"activity_start_time": "2026-03-04T20:55:20Z",
"activity_end_time": "2026-03-05T03:43:56Z",
"placements": [
"ALL_ON_TWITTER"
]
},
{
"entity_id": "2r30fn",
"activity_start_time": "2026-03-05T08:11:08Z",
"activity_end_time": "2026-03-05T14:40:59Z",
"placements": [
"ALL_ON_TWITTER",
"PUBLISHER_NETWORK"
]
}
]
}
```
El array `data` incluye un objeto por cada entidad que debe incluirse en una solicitud de analytics posterior. No debes solicitar analytics para IDs fuera de este conjunto.
Cada objeto incluye cuatro campos: `entity_id`, `activity_start_time`, `activity_end_time` y `placements`. Los tiempos de inicio y fin de actividad representan el rango temporal al que aplican los eventos de cambio de la entidad asociada y, por tanto, determinan las fechas que deben especificarse en las solicitudes de analytics posteriores. El array `placements` puede incluir los siguientes valores: `ALL_ON_TWITTER`, `SPOTLIGHT` y `TREND`. Indica qué placements deben solicitarse para el ID de entidad dado.
#### Uso
El endpoint Active Entities debe dictar cómo se realizan las solicitudes de analytics. Las siguientes directrices de uso están redactadas para apoyar la sincronización de analytics, permitiendo a los partners mantener sus almacenes de datos sincronizados con X. En otras palabras, describe cómo realizar sincronizaciones en segundo plano programadas periódicamente.
Hay dos decisiones que debe tomar un desarrollador.
1. Con qué frecuencia solicitar la información de active entities y, por tanto, con qué frecuencia extraer analytics.
2. Cómo usar los tiempos de inicio y fin de actividad para determinar los valores `start_time` y `end_time` de la solicitud de analytics.
Estos se discuten con más detalle en cada una de las dos subsecciones, a continuación, tras el resumen.
### Resumen
Usa el endpoint Active Entities de la siguiente manera para dictar cómo se realizan las solicitudes de analytics. Sigue estos pasos una vez que hayas decidido con qué frecuencia solicitar la información de active entities y, por tanto, con qué frecuencia extraer analytics.
1. Haz la solicitud a Active Entities.
2. Divide la respuesta por placement. Un grupo para `ALL_ON_TWITTER`, uno para `SPOTLIGHT` y otro para `TREND`.
3. Para cada grupo de placement, haz lo siguiente.
1. Extrae los IDs de entidad.
2. Determina los valores `start_time` y `end_time` de analytics.
* Encuentra el `activity_start_time` mínimo. Redondea este valor hacia abajo.
* Encuentra el `activity_end_time` máximo. Redondea este valor hacia arriba.
3. Realiza la(s) solicitud(es) de analytics.
* Agrupa los IDs de entidad en lotes de 20.
* Usa los valores `start_time` y `end_time` del punto #3b.
* Especifica el valor de `placement` adecuado.
4. Escribe en tu almacén de datos.
Consulta [active\_entities.py](https://github.com/xdevplatform/twitter-python-ads-sdk/blob/master/examples/active_entities.py) como ejemplo que utiliza el SDK de Python.
### Frecuencia
La respuesta a la primera pregunta determina el rango de tiempo que se debe usar en las solicitudes de Active Entities. Por ejemplo, si solicitas información de active entities cada hora, el rango de tiempo debe ser de una hora. Si solicitas información de active entities una vez al día, el rango de tiempo debe ser de un día. En otras palabras, los rangos de tiempo deben seleccionarse de modo que el `start_time` de la solicitud actual sea igual al `end_time` de la solicitud anterior.
**Nota**: Una ventana de tiempo solo debe solicitarse una vez. Solicitar una ventana de tiempo más de una vez generará solicitudes de analytics innecesarias. (Excepción más abajo).
Para los partners que deseen solicitar analytics varias veces por hora para la hora *actual*, aplica el mismo patrón: la frecuencia determina el rango de tiempo. La tabla siguiente muestra timestamps de inicio y fin de Active Entities de ejemplo para este escenario.
| | | |
| :----------------------- | :------------------------- | :----------------------- |
| **Hora de la solicitud** | **timestamp `start_time`** | **timestamp `end_time`** |
| 00:15:00 | 00:00:00 | 00:15:00 |
| 00:30:00 | 00:15:00 | 00:30:00 |
| 00:45:00 | 00:30:00 | 00:45:00 |
| 01:00:00 | 00:45:00 | 01:00:00 |
Dada la forma en que se almacenan los eventos de cambio, las cuatro solicitudes de Active Entities anteriores consultan el mismo bucket horario, lo cual es necesario para este caso de uso. Sin embargo, después de la hora actual, este bucket horario ya no debe consultarse.
### Tiempos de actividad
Recomendamos el siguiente enfoque para trabajar con los tiempos de inicio y fin de actividad. A través de todos los objetos en la respuesta de Active Entities, encuentra el `activity_start_time` mínimo y el `activity_end_time` máximo. Modifica estos valores redondeando hacia abajo el tiempo mínimo de inicio de actividad y redondeando hacia arriba el tiempo máximo de fin de actividad. Concretamente, pon a cero los timestamps en ambos casos y suma un día al tiempo de fin, como se ilustra en la siguiente tabla. Estos son los tiempos de inicio y fin que deben especificarse en las solicitudes de analytics posteriores.
| | |
| :----------------------------------------------------- | :----------------------------------------------------- |
| **Min, max activity times** | **Tiempos derivados** |
| 2026-03-04T20:55:20Z
2026-03-05T14:40:59Z | 2026-03-04T00:00:00Z
2026-03-06T00:00:00Z |
**Nota**: Es importante incluir los timestamps con horas, minutos y segundos a cero. De lo contrario, si solo se pasa la fecha, asumiremos que estás solicitando analytics que empiezan y terminan a medianoche en la zona horaria de la cuenta de anuncios, lo que puede no ser deseable. Por ejemplo, si el tiempo mínimo de inicio de actividad es 2026-02-28T01:30:07Z y se omite el timestamp para una cuenta de anuncios con un offset de -08:00:00, la solicitud de analytics omitirá los cambios que ocurrieron entre las 01:30 y las 08:00.
Alternativamente, si prefieres solicitar analytics solo para la ventana de tiempo de actividad devuelta sin expandirla a días completos, puedes hacerlo. Con este enfoque, los tiempos derivados de inicio y fin serían 2026-03-04T20:00:00Z y 2026-03-05T15:00:00Z, respectivamente. (Ten en cuenta que rangos como estos no se aceptan si especificas granularidad `DAY` en la solicitud de analytics).
#### Ejemplo
Esta sección muestra cómo usar Active Entities junto con el endpoint síncrono de analytics. (Las respuestas se han modificado ligeramente para mejorar la legibilidad). En este ejemplo, se llama al endpoint Active Entities al inicio de cada hora, mirando cada solicitud la hora anterior. La respuesta determina cómo se utiliza el endpoint síncrono de analytics.
La primera solicitud de Active Entities se realiza a las 03:00:00. La respuesta indica que las métricas del line item dvcz7 cambiaron y que esos eventos de cambio aplican a la ventana entre 02:02:55 y 02:28:12.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T02:00:00Z&end_time=2026-02-11T03:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": [
{
"entity_id": "dvcz7",
"activity_start_time": "2026-02-11T02:02:55Z",
"activity_end_time": "2026-02-11T02:58:12Z",
"placements": [
"ALL_ON_TWITTER"
]
}
]
}
```
Con base en estos tiempos de inicio y fin de actividad y siguiendo el enfoque descrito arriba, los valores `start_time` y `end_time` de analytics se establecen en 2026-02-11T00:00:00Z y 2026-02-12T00:00:00Z, respectivamente. Vemos que el tercer elemento en cada uno de los arrays de métricas debajo es distinto de cero, como esperábamos en función de la información de active entities.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=dvcz7&start_time=2026-02-11T00:00:00Z&end_time=2026-02-12T00:00:00Z&granularity=HOUR&metric_groups=ENGAGEMENT,VIDEO&placement=ALL_ON_TWITTER"`
```
```json theme={null}
{
"data_type": "stats",
"time_series_length": 24,
"data": [
{
"id": "dvcz7",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
0,0,2792,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"engagements": [
0,0,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"video_total_views": [
0,0,1326,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
}
}
]
}
],
"request": {}
}
```
La siguiente solicitud de Active Entities ocurre a las 04:00:00 y solo mira la hora anterior. Como se mencionó antes, una ventana de tiempo solo debe solicitarse una vez. Con base en la respuesta, vemos que los eventos de cambio de este line item aplican *tanto* a las 02:00:00 como a las 03:00:00. En la solicitud de analytics posterior, esperamos ver cambios para ambas horas.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T03:00:00Z&end_time=2026-02-11T04:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": [
{
"entity_id": "dvcz7",
"activity_start_time": "2026-02-11T02:07:17Z",
"activity_end_time": "2026-02-11T03:49:22Z",
"placements": [
"ALL_ON_TWITTER"
]
}
]
}
```
Además de ver métricas distintas de cero para las 03:00:00, observamos que las impresiones, el gasto y las vistas de video MRC se han actualizado respecto a sus valores anteriores. Las impresiones, por ejemplo, ahora son 2.995 para la hora 02:00:00, frente a 2.792 anteriores. Esto demuestra cómo los eventos de cambio que se registraron durante la hora 03:00:00 aplican a la hora 02:00:00.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=dvcz7&start_time=2026-02-11T00:00:00Z&end_time=2026-02-12T00:00:00Z&granularity=HOUR&metric_groups=ENGAGEMENT,VIDEO&placement=ALL_ON_TWITTER"`
```
```json theme={null}
{
"data_type": "stats",
"time_series_length": 24,
"data": [
{
"id": "dvcz7",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
0,0,2995,734,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"engagements": [
0,0,65,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"video_total_views": [
0,0,1449,342,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
}
}
]
}
],
"request": {}
}
```
La solicitud de Active Entities a las 05:00:00, mirando de nuevo solo la hora anterior, muestra que los eventos de cambio aplican únicamente a la hora 03:00:00. Los cambios en las métricas de analytics en la solicitud posterior lo reflejan.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T04:00:00Z&end_time=2026-02-11T05:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": [
{
"entity_id": "dvcz7",
"activity_start_time": "2026-02-11T03:42:39Z",
"activity_end_time": "2026-02-11T03:48:48Z",
"placements": [
"ALL_ON_TWITTER"
]
}
]
}
```
La respuesta de analytics muestra que solo las métricas de la hora 03:00:00 han cambiado; los valores para la hora 02:00:00 son los mismos que en la solicitud anterior de analytics.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=dvcz7&start_time=2026-02-11T00:00:00Z&end_time=2026-02-12T00:00:00Z&granularity=HOUR&metric_groups=ENGAGEMENT,VIDEO&placement=ALL_ON_TWITTER"`
```
```json theme={null}
{
"data_type": "stats",
"time_series_length": 24,
"data": [
{
"id": "dvcz7",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
0,0,2995,753,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"engagements": [
0,0,65,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"video_total_views": [
0,0,1449,351,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
}
}
]
}
],
"request": {}
}
```
Finalmente, a las 06:00:00 vemos que no hay eventos de cambio adicionales. **Nota**: Esto *no* implica que las métricas de este line item no puedan cambiar en el futuro.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T05:00:00Z&end_time=2026-02-11T06:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": []
}
```
### Guía asíncrona
## Referencia de la API
### Asynchronous Analytics
#### Introducción
Los endpoints asíncronos de analytics permiten a partners y anunciantes solicitar métricas enviando solicitudes de creación que el servidor procesa de forma asíncrona. (Nos referimos a estos como "jobs" asíncronos de analytics). Con este enfoque, la conexión del cliente no necesita permanecer abierta hasta que la solicitud sea atendida.
Estos endpoints, al igual que su contraparte síncrona, permiten a partners y anunciantes solicitar estadísticas detalladas sobre el rendimiento de campañas. Admiten solicitar datos para cuentas, instrumentos de financiación, campañas, line items, posts promocionados y creativos de medios. La diferencia entre estos y el endpoint síncrono es que los endpoints asíncronos de analytics admiten rangos de fechas más largos, de hasta 90 días, así como segmentación. Puedes encontrar detalles adicionales sobre las diferencias entre ambos en nuestra página [Analytics Overview](/x-ads-api/analytics).
A diferencia de nuestros endpoints síncronos, el rate limiting se basa en el número de jobs concurrentes para una cuenta determinada. En otras palabras, se basa en el número de jobs que pueden estar en estado de procesamiento en un momento dado. Esto se cuenta a nivel de cuenta de anuncios.
#### Uso
Obtener métricas de campaña usando los endpoints asíncronos de analytics es un proceso de varios pasos. Implica crear un job, comprobar si el job ha terminado de procesarse y, finalmente, descargar los datos. El archivo de datos debe descomprimirse. Los cuatro pasos específicos se describen a continuación.
1. Crea el job usando el endpoint [POST stats/jobs/accounts/:account\_id](/x-ads-api/analytics#asynchronous-analytics).
2. Realiza solicitudes a intervalos regulares al endpoint [GET stats/jobs/accounts/:account\_id](/x-ads-api/analytics#asynchronous-analytics) para determinar si el job ha terminado de procesarse.
3. Una vez que el job haya terminado de procesarse, descarga el archivo de datos.
4. Descomprime el archivo de datos.
El objeto de respuesta devuelto en el archivo de datos tiene el mismo esquema JSON que la respuesta del endpoint síncrono de analytics.
Las métricas de campaña segmentadas solo están disponibles a través de los endpoints asíncronos de analytics. Las métricas de campaña pueden desglosarse por ubicación, género, interés, palabra clave y más. Para una lista completa de opciones, consulta la página [Metrics and Segmentation](/x-ads-api/analytics#metrics-and-segmentation). Para solicitar métricas segmentadas, utiliza el parámetro de solicitud `segmentation_type` al crear el job.
#### Ejemplo
Esta sección demuestra cómo usar los endpoints asíncronos de analytics.
Empieza creando un job usando el endpoint [POST stats/jobs/accounts/:account\_id](/x-ads-api/analytics#asynchronous-analytics). El ejemplo siguiente solicita métricas de engagement —como impresiones, likes, clics, etc.— para un line item específico durante el lapso de una semana. (Ten en cuenta que el rango de tiempo solicitado llega hasta, pero no incluye, el 20 de marzo, ya que el timestamp se establece a medianoche).
```text theme={null}
$ twurl -X POST -H ads-api.x.com "/12/stats/jobs/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=el32n&start_time=2026-03-12T00:00:00Z&end_time=2026-03-20T00:00:00Z&granularity=TOTAL&placement=ALL_ON_TWITTER&metric_groups=ENGAGEMENT"
```
```json theme={null}
{
"request": {
"params": {
"start_time": "2026-03-12T00:00:00Z",
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"placement": "ALL_ON_TWITTER",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"metric_groups": [
"ENGAGEMENT"
]
}
},
"data": {
"start_time": "2026-03-12T00:00:00Z",
"segmentation_type": null,
"url": null,
"id_str": "1120829647711653888",
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"id": 1120829647711653888,
"expires_at": null,
"account_id": "18ce54d4x5t",
"status": "PROCESSING",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"created_at": "2026-04-01T23:19:46Z",
"platform": null,
"updated_at": "2026-04-01T23:19:46Z",
"metric_groups": [
"ENGAGEMENT"
]
}
}
```
Esta respuesta no devuelve las métricas del line item. Simplemente proporciona información sobre el job que acabas de crear. El ID del job es necesario para verificar el estado del job. Esto se muestra tanto en los atributos de respuesta `id` como `id_str`.
A continuación, querrás comprobar si el job que has creado, usando el `id_str` de la respuesta anterior, ha terminado de procesarse, lo cual se indica con `"status": "SUCCESS"` en la respuesta. Esto significa que los datos están listos para descargarse. El campo `url` contiene el enlace de descarga.
```text theme={null}
$ twurl -H ads-api.x.com "/12/stats/jobs/accounts/18ce54d4x5t?job_ids=1120829647711653888"
```
```json theme={null}
{
"request": {
"params": {
"job_ids": [
1120829647711653888
]
}
},
"next_cursor": "1120828505715920896",
"data": [
{
"start_time": "2026-03-12T00:00:00Z",
"segmentation_type": null,
"url": "https://ton.twimg.com/advertiser-api-async-analytics/stats_job_1120829647711653888.json.gz",
"id_str": "1120829647711653888",
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"id": 1120829647711653888,
"expires_at": "2026-04-03T23:19:48Z",
"account_id": "18ce54d4x5t",
"status": "SUCCESS",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"created_at": "2026-04-01T23:19:46Z",
"platform": null,
"updated_at": "2026-04-01T23:19:48Z",
"metric_groups": [
"ENGAGEMENT"
]
}
]
}
```
Aunque en el ejemplo anterior estamos pasando un único ID de job, en la práctica querrás usar el parámetro `job_ids` para comprobar el estado de múltiples jobs a la vez, especificando hasta 200 IDs de job.
A continuación, descarga el archivo de datos usando el valor `url` indicado.
```text theme={null}
$ wget https://ton.twimg.com/advertiser-api-async-analytics/stats_job_1120829647711653888.json.gz
```
Finalmente, descomprime el archivo de datos.
```text theme={null}
`$ gunzip stats_job_1120829647711653888.json.gz`
```
El contenido del archivo se muestra a continuación.
```json theme={null}
{
"data_type": "stats",
"time_series_length": 1,
"data": [
{
"id": "el32n",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
3482
],
"tweets_send": null,
"qualified_impressions": null,
"follows": null,
"app_clicks": null,
"retweets": [
102
],
"unfollows": null,
"likes": [
15
],
"engagements": [
171
],
"clicks": [
30
],
"card_engagements": null,
"poll_card_vote": null,
"replies": null,
"carousel_swipes": null
}
}
]
}
],
"request": {
"params": {
"start_time": "2026-03-12T00:00:00Z",
"segmentation_type": null,
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"platform": null,
"metric_groups": [
"ENGAGEMENT"
]
}
}
}
```
### Reach y frecuencia promedio
#### GET stats/accounts/:account\_id/reach/campaigns
Obtén analytics de reach y frecuencia promedio para las campañas especificadas.
### URL del recurso
`https://ads-api.x.com/stats/accounts/:account_id/reach/campaigns`
### Parámetros
| Nombre | Descripción |
| :------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *required* | El identificador de la cuenta utilizada. Aparece dentro de la ruta del recurso y generalmente es un parámetro obligatorio para todas las solicitudes de la Advertiser API, excepto [GET accounts](/x-ads-api/campaign-management/reference#accounts). La cuenta especificada debe estar asociada al usuario autenticado.
Tipo: string
Ejemplo: `18ce54d4x5t` |
| campaign\_ids *required* | Acota la respuesta solo a las campañas deseadas especificando una lista de identificadores separados por comas. Pueden proporcionarse hasta 20 IDs.
**Nota**: Pueden proporcionarse hasta 20 IDs de campaña.
Tipo: string
Ejemplo: `8fgzf` |
| end\_time *required* | Acota los datos obtenidos a la hora de fin especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-26T07:00:00Z` |
| start\_time *required* | Acota los datos obtenidos a la hora de inicio especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-19T07:00:00Z` |
### Solicitud de ejemplo
`GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/reach/campaigns?campaign_ids=8fgzf&start_time=2026-05-19&end_time=2026-05-26`
### Respuesta de ejemplo
```json theme={null}
{
"request": {
"params": {
"campaign_ids": [
"8fgzf"
],
"start_time": "2026-05-19T00:00:00Z",
"end_time": "2026-05-26T00:00:00Z",
"account_id": "18ce54d4x5t"
}
},
"data_type": "reach",
"data": [
{
"id": "8fgzf",
"total_audience_reach": 1217,
"average_frequency": 1.01
}
]
}
```
#### GET stats/accounts/:account\_id/reach/funding\_instruments
Obtén analytics de reach y frecuencia promedio para los instrumentos de financiación especificados.
### URL del recurso
`https://ads-api.x.com/stats/accounts/:account_id/reach/funding_instruments`
### Parámetros
| Nombre | Descripción |
| :----------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *required* | El identificador de la cuenta utilizada. Aparece dentro de la ruta del recurso y generalmente es un parámetro obligatorio para todas las solicitudes de la Advertiser API, excepto [GET accounts](/x-ads-api/campaign-management/reference#accounts). La cuenta especificada debe estar asociada al usuario autenticado.
Tipo: string
Ejemplo: `18ce54d4x5t` |
| funding\_instrument\_ids *required* | Acota la respuesta solo a los instrumentos de financiación deseados especificando una lista de identificadores separados por comas. Pueden proporcionarse hasta 20 IDs.
**Nota**: Pueden proporcionarse hasta 20 IDs de instrumentos de financiación.
Tipo: string
Ejemplo: `lygyi` |
| end\_time *required* | Acota los datos obtenidos a la hora de fin especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-26T07:00:00Z` |
| start\_time *required* | Acota los datos obtenidos a la hora de inicio especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-19T07:00:00Z` |
### Solicitud de ejemplo
```text theme={null}
GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/reach/funding_instruments?funding_instrument_ids=lygyi&start_time=2026-05-19&end_time=2026-05-26
```
### Respuesta de ejemplo
```json theme={null}
{
"request": {
"params": {
"funding_instrument_ids": [
"lygyi"
],
"start_time": "2026-05-19T00:00:00Z",
"end_time": "2026-05-26T00:00:00Z",
"account_id": "18ce54d4x5t"
}
},
"data_type": "reach",
"data": [
{
"id": "lygyi",
"total_audience_reach": 1217,
"average_frequency": 1.01
}
]
}
```
### Synchronous Analytics
#### GET stats/accounts/:account\_id
Obtén analytics síncronos para la cuenta actual. Se permite un rango de tiempo máximo (`end_time` - `start_time`) de 7 días.
### URL del recurso
`https://ads-api.x.com/12/stats/accounts/:account_id`
### Parámetros
| Nombre | Descripción |
| :------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *required* | El identificador de la cuenta utilizada. Aparece dentro de la ruta del recurso y generalmente es un parámetro obligatorio para todas las solicitudes de la Advertiser API, excepto [GET accounts](/x-ads-api/campaign-management/reference#accounts). La cuenta especificada debe estar asociada al usuario autenticado.
Tipo: string
Ejemplo: `18ce54d4x5t` |
| end\_time *required* | Acota los datos obtenidos a la hora de fin especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-26T07:00:00Z` |
| entity *required* | El tipo de entidad para el que se obtendrán los datos.
Tipo: enum
Valores posibles: `ACCOUNT`, `CAMPAIGN`, `FUNDING_INSTRUMENT`, `LINE_ITEM`, `PROMOTED_ACCOUNT`, `PROMOTED_TWEET` |
| entity\_ids *required* | Las entidades específicas para las que se obtendrán los datos. Especifica una lista de IDs de entidad separados por comas.
**Nota**: Pueden proporcionarse hasta 20 IDs de entidad.
Tipo: string
Ejemplo: `8u94t` |
| granularity *required* | Especifica qué tan granulares deben ser los datos obtenidos.
Tipo: enum
Valores posibles: `DAY`, `HOUR`, `TOTAL` |
| metric\_groups *required* | Las métricas específicas que deben devolverse. Especifica una lista de grupos de métricas separados por comas. Para más información, consulta [Metrics and Segmentation](/x-ads-api/analytics#metrics-and-segmentation).
**Nota**: Los datos de `MOBILE_CONVERSION` deben solicitarse por separado.
Tipo: enum
Valores posibles: `BILLING`, `ENGAGEMENT`, `LIFE_TIME_VALUE_MOBILE_CONVERSION`, `MOBILE_CONVERSION`, `VIDEO`, `WEB_CONVERSION` |
| placement *required* | Acota los datos obtenidos a un placement determinado.
**Nota**: Solo se acepta un único valor por solicitud. Para entidades que tengan placement tanto en X como en X Audience Platform, se requieren solicitudes separadas, una para cada valor de placement.
Tipo: enum
Valores posibles: `ALL_ON_TWITTER`, `SPOTLIGHT`, `TREND` |
| start\_time *required* | Acota los datos obtenidos a la hora de inicio especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-19T07:00:00Z` |
### Solicitud de ejemplo
```text theme={null}
GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=8u94t&start_time=2026-05-19&end_time=2026-05-26&granularity=TOTAL&placement=ALL_ON_TWITTER&metric_groups=ENGAGEMENT
```
### Respuesta de ejemplo
```json theme={null}
{
"data_type": "stats",
"time_series_length": 1,
"data": [
{
"id": "8u94t",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
1233
],
"tweets_send": null,
"qualified_impressions": null,
"follows": null,
"app_clicks": null,
"retweets": null,
"likes": [
1
],
"engagements": [
58
],
"clicks": [
58
],
"card_engagements": null,
"poll_card_vote": null,
"replies": null,
"carousel_swipes": null
}
}
]
}
],
"request": {
"params": {
"start_time": "2026-05-19T07:00:00Z",
"segmentation_type": null,
"entity_ids": [
"8u94t"
],
"end_time": "2026-05-26T07:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"platform": null,
"metric_groups": [
"ENGAGEMENT"
]
}
}
}
```
### Active Entities
#### GET stats/accounts/:account\_id/active\_entities
Obtén detalles sobre qué métricas de analytics de qué entidades han cambiado en un período de tiempo determinado.
Este endpoint debe usarse junto con nuestros endpoints de analytics. Los resultados de este endpoint indican para qué entidades de anuncios se debe solicitar analytics. Consulta nuestra [Guía de Active Entities](/x-ads-api/analytics#active-entities) para conocer las directrices de uso.
Los eventos de cambio están disponibles en buckets horarios.
* Los valores `start_time` y `end_time` especifican qué buckets horarios se consultan.
* El array `data` devuelto incluirá un objeto por cada entidad que deba incluirse en solicitudes de analytics posteriores.
* **IMPORTANTE**: Las fechas que deben especificarse en solicitudes de analytics posteriores deben determinarse en función de los valores `activity_start_time` y `activity_end_time`.
* Estos valores representan los rangos de tiempo a los que *aplican* los eventos de cambio almacenados. Esto se devuelve por entidad.
**Nota**: Se permite un rango de tiempo máximo (`end_time` - `start_time`) de 90 días.
### URL del recurso
`https://ads-api.x.com/12/stats/accounts/:account_id/active_entities`
### Parámetros
| Nombre | Descripción |
| :----------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *required* | El identificador de la cuenta utilizada. Aparece dentro de la ruta del recurso y generalmente es un parámetro obligatorio para todas las solicitudes de la Advertiser API, excepto [GET accounts](/x-ads-api/campaign-management/reference#accounts). La cuenta especificada debe estar asociada al usuario autenticado.
Tipo: string
Ejemplo: `18ce54d4x5t` |
| end\_time *required* | Acota los datos obtenidos a la hora de fin especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-26T07:00:00Z` |
| entity *required* | El tipo de entidad para el que se obtendrán los datos.
Tipo: enum
Valores posibles: `CAMPAIGN`, `FUNDING_INSTRUMENT`, `LINE_ITEM`, `PROMOTED_ACCOUNT`, `PROMOTED_TWEET` |
| start\_time *required* | Acota los datos obtenidos a la hora de inicio especificada, expresada en [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
**Nota**: Debe expresarse en horas completas (0 minutos y 0 segundos).
Tipo: string
Ejemplo: `2026-05-19T07:00:00Z` |
| campaign\_ids *optional* | Acota la respuesta solo a las entidades asociadas con las campañas deseadas, especificando una lista de identificadores separados por comas. Pueden proporcionarse hasta 200 IDs.
**Nota**: Excluyente con `funding_instrument_ids` y `line_item_ids`.
Tipo: string
Ejemplo: `8wku2` |
| funding\_instrument\_ids *optional* | Acota la respuesta solo a las entidades asociadas con los instrumentos de financiación deseados, especificando una lista de identificadores separados por comas. Pueden proporcionarse hasta 200 IDs.
**Nota**: Excluyente con `campaign_ids` y `line_item_ids`.
Tipo: string
Ejemplo: `lygyi` |
| line\_item\_ids *optional* | Acota la respuesta solo a las entidades asociadas con los line items deseados, especificando una lista de identificadores separados por comas. Pueden proporcionarse hasta 200 IDs.
**Nota**: Excluyente con `campaign_ids` y `line_item_ids`.
Tipo: string
Ejemplo: `8v7jo` |
### Solicitud de ejemplo
`GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/active_entities?entity=PROMOTED_TWEET&start_time=2026-02-28&end_time=2026-03-01`
### Respuesta de ejemplo
```json theme={null}
{
"request": {
"params": {
"account_id": "18ce54d4x5t",
"entity": "PROMOTED_TWEET",
"start_time": "2026-02-28T08:00:00Z",
"end_time": "2026-03-01T08:00:00Z"
}
},
"data": [
{
"entity_id": "2mvb28",
"activity_start_time": "2026-02-28T01:30:07Z",
"activity_end_time": "2026-03-01T07:42:55Z",
"placements": [
"ALL_ON_TWITTER"
]
},
{
"entity_id": "2mvb29",
"activity_start_time": "2026-02-27T11:30:07Z",
"activity_end_time": "2026-03-01T07:42:50Z",
"placements": [
"ALL_ON_TWITTER",
"PUBLISHER_NETWORK"
]
},
{
"entity_id": "2mvfan",
"activity_start_time": "2026-02-27T09:00:05Z",
"activity_end_time": "2026-03-01T06:06:36Z",
"placements": [
"PUBLISHER_NETWORK"
]
},
{
"entity_id": "2n17dx",
"activity_start_time": "2026-02-28T02:02:26Z",
"activity_end_time": "2026-03-01T07:52:44Z",
"placements": [
"ALL_ON_TWITTER",
"PUBLISHER_NETWORK"
]
}
]
}
```
# Guía paso a paso
Source: https://docs.x.com/es/x-ads-api/getting-started/step-by-step-guide
Guía paso a paso para empezar con la X Ads API: configurar la cuenta, crear la App, solicitar acceso y autenticar tus solicitudes a la API.
## Cómo obtener acceso a la Ads API
1. Regístrate para obtener una [cuenta de desarrollador](https://developer.x.com/en/apply-for-access).
2. Crea una [App de desarrollador](https://developer.x.com/app) y protege tu token.
3. Visita [ads.x.com/help](https://ads.x.com/help) para enviar una solicitud de acceso a la Ads API para cada una de tus apps de desarrollador.
**Nota:** Si ya estás creando en la X Developer Platform y tienes una cuenta de desarrollador, salta al paso tres.
### Paso uno: Regístrate para obtener una cuenta de desarrollador
Para realizar una solicitud a cualquiera de los productos de la API de X, primero debes registrarte para obtener una cuenta de desarrollador. Dentro de la Developer Console, crea una App y una App de desarrollador. Esto te proporcionará un conjunto de credenciales que utilizarás para autenticar todas las solicitudes a la API.
### Paso dos: Guarda las claves y tokens de tu App de forma segura
Dentro de tu App de desarrollador, se te proporcionará un conjunto de API Keys (también conocidas como Consumer Keys). También tendrás la oportunidad de generar un conjunto de Access Tokens que pueden usarse para realizar solicitudes en nombre de tu cuenta personal de X, y un Bearer Token que puede usarse para autenticar endpoints que requieren OAuth 2.0 Bearer Token. Como estas claves y tokens no caducan a menos que se regeneren, te sugerimos crear variables de entorno o usar un gestor de contraseñas seguro.
Toma nota también de tu App ID, que se puede encontrar en la URL de los detalles de tu App. Esto facilitará la solicitud de acceso a la Ads API en el siguiente paso.
**Nota:** Tus claves y tokens solo se mostrarán una vez en la Developer Console, por lo que es importante que almacenes estas credenciales en tu sistema de gestión de contraseñas tan pronto como las generes.
Si pierdes u olvidas las claves y tokens, deberás regenerarlos, lo que crea nuevas claves y tokens e invalida los antiguos. Esto significa que tendrás que actualizar cualquier integración que hayas configurado con tus credenciales anteriores.
Obtén más información sobre nuestras [mejores prácticas de autenticación](/fundamentals/authentication/guides/authentication-best-practices).
### Paso tres: Solicita acceso a la Ads API
En este punto tendrás acceso básico a la X API, pero no a la funcionalidad específica de la X Ads API. A continuación, deberás solicitar acceso y ser aprobado para el acceso a la Ads API. Visita [ads.x.com/help](https://ads.x.com/help) para enviar una solicitud de acceso a la Ads API para cada una de tus apps de desarrollador.
### Niveles de acceso
Como parte del proceso de solicitud, deberás especificar qué nivel de acceso necesitas. Obtén más información sobre los [permisos a nivel de App y a nivel de cuenta publicitaria](/x-ads-api/fundamentals/accessing-ads-accounts#levels-of-access).
#### Conversion Only
Acceso de lectura y escritura a los endpoints de Mobile y Web Conversion.
#### Standard Access
Acceso de lectura y escritura a los endpoints de Analytics, Campaign Management, Creatives, Custom Audiences y Conversion.
**Nota:** Después de que tu app sea aprobada para el acceso a la Ads API, deberás [regenerar cualquier token de acceso de usuario](/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) para realizar [solicitudes autenticadas correctamente a la Ads API](/x-ads-api/fundamentals/making-authenticated-requests).**Nota:** Los desarrolladores de la Ads API que solicitaron acceso antes de julio de 2023 pueden tener diferentes niveles de acceso y permisos, y pueden estar limitados a cinco tokens OAuth. Consulta nuestra guía sobre [cómo aumentar el acceso](/x-ads-api/getting-started/increasing-access) para acceder a endpoints adicionales o eliminar los límites de tokens en las aplicaciones existentes.
## Realiza tu primera solicitud
Para probar tu acceso a la Ads API, realiza una solicitud al endpoint [GET accounts](/x-ads-api/campaign-management/reference#get-accounts). Este endpoint devolverá las cuentas publicitarias a las que tiene acceso el usuario autorizado actualmente. Usa los ID de cuenta publicitaria de esta solicitud en posteriores solicitudes a la API para leer y escribir datos de una cuenta publicitaria específica. Usando [Twurl](https://github.com/twitter/twurl) en la línea de comandos, la solicitud se vería de la siguiente manera.
**Solicitud de ejemplo**
```bash theme={null}
twurl -H ads-api.x.com "/11/accounts"
```
**Respuesta de ejemplo**
```json theme={null}
{
"request": {
"params": {}
},
"data": [
{
"name": "Furni",
"business_name": null,
"timezone": "America/Los_Angeles",
"timezone_switch_at": "2016-04-06T07:00:00Z",
"id": "18ce54ayf0z",
"created_at": "2016-04-07T14:40:15Z",
"salt": "b88939e5cabbca720159cb3659d73c06",
"updated_at": "2017-02-08T08:49:53Z",
"business_id": null,
"approval_status": "ACCEPTED",
"deleted": false
}
]
}
```
## A continuación . . .
* Lee la [documentación de la Ads API](/x-ads-api/introduction) sobre fundamentos como el [versionado](/x-ads-api/fundamentals/versioning) y la [jerarquía](/x-ads-api/fundamentals/hierarchy-and-terminology).
* Consulta las distintas [herramientas y bibliotecas de la Ads API](/x-ads-api/tools-and-libraries) que te ayudarán en tu integración con la Ads API.
* Comprende los pasos para [aumentar el acceso a la Ads API](/x-ads-api/getting-started/increasing-access).
* Familiarízate con los [recursos de soporte](/support) disponibles.
* Sigue a [@API](https://x.com/API) para recibir actualizaciones en vivo sobre cambios en la API, problemas del servicio y mejoras en los productos promocionados de X.
# Introducción
Source: https://docs.x.com/es/x-api/activity/introduction
Resumen de la X Activity API para transmitir en tiempo real eventos de usuario como post.create, post.delete y actualizaciones de perfil en X.
El grupo de endpoints de la X Activity API (XAA) permite a los desarrolladores acceder a los eventos de actividad que ocurren en la plataforma X.
Un desarrollador puede suscribirse a los eventos que le interesen, como `profile.update.bio`, `post.create`, `post.delete`, etc., y filtrar por el User ID cuyos eventos quiera recibir. Los eventos coincidentes para ese User ID se entregarán a tu app con una latencia inferior a un segundo.
## Mecanismos de entrega
La X Activity API admite actualmente los siguientes mecanismos de entrega para enviar eventos a tu app:
* Stream HTTP persistente
* [Webhook](/x-api/webhooks/introduction)
## Tipos de eventos admitidos
Actualmente, la X Activity API admite los siguientes tipos de eventos, organizados por categoría:
### Eventos de Post
Los eventos de Post se activan cuando un usuario crea o elimina un Post.
| Event Name | Descripción | Filtros |
| --------------------- | ----------------------------------------------------------------- | --------- |
| `post.create` | Se activa cuando un usuario crea un Post | `user_id` |
| `post.delete` | Se activa cuando un usuario elimina un Post | `user_id` |
| `post.mention.create` | Se activa cuando alguien @menciona al usuario filtrado en un Post | `user_id` |
**Eventos de Post mediante XAA vs Filtered Stream:** La X Activity API admite los eventos `post.create` y `post.delete`. Suscríbete por `user_id` para recibir notificaciones en tiempo real cuando los usuarios creen o eliminen Posts.
Si necesitas filtrado dirigido por palabras clave, lógica booleana, segmentación geográfica, filtros de idioma o cualquiera de los demás operadores que admite el Filtered Stream, utiliza en su lugar el endpoint [Filtered Stream](/x-api/posts/filtered-stream/introduction).
### Eventos de seguimiento
Los eventos de seguimiento se activan cuando el usuario filtrado sigue a otro usuario, o cuando es seguido por otro usuario.
| Event Name | Descripción | Filtros |
| ----------------- | --------------------------------------------------------- | --------- |
| `follow.follow` | Se activa cuando un usuario sigue a otro usuario | `user_id` |
| `follow.unfollow` | Se activa cuando un usuario deja de seguir a otro usuario | `user_id` |
### Eventos de perfil
Los eventos de perfil se activan cuando un usuario realiza cambios en la información de su perfil.
| Event Name | Descripción | Filtros |
| -------------------------------- | ----------------------------------------------------------------------- | --------- |
| `profile.update.bio` | Se activa cuando un usuario actualiza la biografía de su perfil | `user_id` |
| `profile.update.profile_picture` | Se activa cuando un usuario actualiza su foto de perfil | `user_id` |
| `profile.update.banner_picture` | Se activa cuando un usuario actualiza el banner de su perfil | `user_id` |
| `profile.update.screenname` | Se activa cuando un usuario actualiza su nombre para mostrar | `user_id` |
| `profile.update.handle` | Se activa cuando un usuario actualiza su handle | `user_id` |
| `profile.update.geo` | Se activa cuando un usuario actualiza la ubicación de su perfil | `user_id` |
| `profile.update.url` | Se activa cuando un usuario actualiza la URL del sitio web de su perfil | `user_id` |
| `profile.update.verified_badge` | Se activa cuando un usuario actualiza su insignia de verificación | `user_id` |
| `profile.update.affiliate_badge` | Se activa cuando un usuario actualiza su insignia de afiliado | `user_id` |
### Eventos de chat
Los eventos de chat corresponden a la nueva pila de mensajería cifrada, o XChat.
| Event Name | Descripción | Filtros |
| ------------------------ | --------------------------------------------------------------------- | --------- |
| `chat.received` | Se activa cuando un usuario recibe un mensaje directo cifrado | `user_id` |
| `chat.sent` | Se activa cuando un usuario envía un mensaje directo cifrado | `user_id` |
| `chat.conversation_join` | Se activa cuando un usuario se une a una conversación de chat cifrado | `user_id` |
### Eventos heredados de DM
Los eventos heredados de DM corresponden al sistema heredado de DM sin cifrar.
| Event Name | Descripción | Filtros |
| -------------------- | ------------------------------------------------------------------------------------------------------------- | --------- |
| `dm.received` | Se activa cuando un usuario recibe un mensaje directo sin cifrar | `user_id` |
| `dm.sent` | Se activa cuando un usuario envía un mensaje directo sin cifrar | `user_id` |
| `dm.read` | Se activa cuando un usuario lee el mensaje de DM sin cifrar del usuario filtrado, o "confirmación de lectura" | `user_id` |
| `dm.indicate_typing` | Se activa cuando un usuario está escribiendo un mensaje al usuario filtrado | `user_id` |
### Eventos de noticias
Los eventos de noticias proporcionan actualizaciones sobre tendencias y titulares seleccionados por Grok.
| Event Name | Descripción | Filtros |
| ---------- | ---------------------------------------------------- | --------- |
| `news.new` | Nuevas tendencias y titulares seleccionados por Grok | `keyword` |
**Solo Enterprise:** El evento `news.new` solo está disponible actualmente para cuentas de los niveles Enterprise y Partner.
### Eventos de Spaces
Los eventos de Spaces se activan cuando un usuario inicia o finaliza un Space.
| Event Name | Descripción | Filtros |
| -------------- | --------------------------------------------- | --------- |
| `spaces.start` | Se activa cuando un usuario inicia un Space | `user_id` |
| `spaces.end` | Se activa cuando un usuario finaliza un Space | `user_id` |
En futuras versiones, XAA se ampliará para admitir más tipos de eventos, incluyendo interacciones sociales, interacción con contenido, funciones de monetización y mucho más. Seguiremos actualizando nuestra documentación cuando estén disponibles nuevos tipos de eventos.
## Privacidad de los eventos y autenticación
La X Activity API distingue entre **eventos públicos** y **eventos privados** con paridad respecto a la app de X, como se explica a continuación.
### Eventos públicos
Los eventos públicos son actividades que una cuenta de usuario pública realiza de forma pública y que son visibles para todos los usuarios de X. Estos eventos son visibles para todos los usuarios en la plataforma X y no requieren autenticación OAuth por parte del usuario para poder visualizarse.
**Eventos públicos actuales:**
* Actualizaciones de perfil (biografía, foto, banner, ubicación, URL, cambios de nombre de usuario)
* Creación de Posts (`post.create`) y eliminación (`post.delete`)
Para estos eventos públicos, puedes crear suscripciones especificando el ID de usuario en tu filtro y recibirlos mediante XAA.
### Eventos privados
Los eventos privados son actividades que requieren el consentimiento explícito del usuario mediante autenticación OAuth. El usuario debe autenticarse a través de X y dar permiso explícito a una app de desarrollador para acceder a estos eventos.
**Eventos privados actuales:**
* Me gusta (`like.create`)
* Chat cifrado recibido (`chat.received`)
* Chat cifrado enviado (`chat.sent`)
* DM recibido (`dm.received`)
* DM enviado (`dm.sent`)
* DM leído (`dm.read`)
* Indicador de escritura de DM (`dm.indicate_typing`)
* Menciones en Posts (`post.mention.create`)
**Requisitos de autenticación para eventos privados:**
* El usuario debe autenticar tu aplicación mediante OAuth 2.0
* Tu aplicación debe obtener los scopes de OAuth correspondientes
* El usuario debe otorgar permiso explícito para que tu app acceda a estos eventos
* Las suscripciones a eventos privados solo se pueden crear para usuarios que hayan autorizado tu aplicación
## Límites de suscripción
La X Activity API tiene distintos límites de suscripción según el nivel de tu cuenta:
| Nivel del paquete | Suscripciones máximas |
| ----------------- | --------------------- |
| Autoservicio | 1,500 |
| Enterprise | 75,000 |
| Partner | 150,000 |
## Endpoints
| Método | Endpoint | Descripción |
| :----- | :--------------------------------------------------------------------------------- | :------------------------------- |
| GET | [`/2/activity/stream`](/x-api/activity/activity-stream) | Conectarse al flujo de actividad |
| POST | [`/2/activity/subscriptions`](/x-api/activity/create-x-activity-subscription) | Crear una suscripción |
| GET | [`/2/activity/subscriptions`](/x-api/activity/get-x-activity-subscriptions) | Listar suscripciones |
| PUT | [`/2/activity/subscriptions/:id`](/x-api/activity/update-x-activity-subscription) | Actualizar una suscripción |
| DELETE | [`/2/activity/subscriptions/:id`](/x-api/activity/deletes-x-activity-subscription) | Eliminar una suscripción |
**Configuración de la cuenta**
Para acceder a estos endpoints, necesitarás:
* Una [cuenta de desarrollador](https://developer.x.com/en/portal/petition/essential/basic-info) aprobada.
* Autenticarte usando las claves y tokens de una [App de desarrollador](/fundamentals/developer-apps) que esté ubicada dentro de un Project.
Obtén más información sobre cómo obtener acceso a los endpoints de la X API v2 en nuestra [guía de inicio](/x-api/getting-started/getting-access).
# Introducción
Source: https://docs.x.com/es/x-api/articles/introduction
Usa los endpoints de Articles de la X API para crear borradores de publicaciones largas con texto enriquecido, medios y embebidos, y publicarlos en X.
Los endpoints de Articles permiten a los desarrolladores crear borradores de Articles y publicarlos en X de forma programática. Los Articles son publicaciones de formato largo que admiten formato de texto enriquecido, publicaciones incrustadas, enlaces e imágenes.
Estos endpoints requieren autenticación de usuario mediante OAuth 1.0a u OAuth 2.0 PKCE con los scopes `tweet.read`, `tweet.write` y `users.read`.
Actualmente, la API admite dos endpoints:
## Crear un borrador de Article
Los desarrolladores pueden crear un nuevo borrador de Article usando el endpoint `POST https://api.x.com/2/articles/draft`. El cuerpo de la solicitud contiene el título del artículo, el contenido del cuerpo como un estado de contenido [DraftJS](https://draftjs.org/docs/api-reference-content-state) de bloques de texto y entidades, y, opcionalmente, una imagen de portada cargada mediante los [endpoints de subida de medios](/x-api/media/introduction).
## Publicar un Article
Una vez que el borrador esté listo, los desarrolladores pueden hacerlo visible públicamente usando el endpoint `POST https://api.x.com/2/articles/{article_id}/publish`, donde `article_id` es el ID devuelto cuando se creó el borrador.
## Primeros pasos
Para usar los endpoints, necesitas un token de acceso de usuario. Para obtener más detalles sobre cómo generarlo, consulta la documentación del [flujo de código de autorización OAuth 2.0 con PKCE](/fundamentals/authentication/oauth-2-0/authorization-code).
Una vez que tengas el token de acceso, puedes crear un borrador de Article como se muestra a continuación:
```bash theme={null}
curl --request POST 'https://api.x.com/2/articles/draft' \
--header 'Authorization: Bearer XXXXX' \
--header 'Content-Type: application/json' \
--data '{
"title": "My first Article",
"content_state": {
"blocks": [
{
"text": "Hello from the Articles API!",
"type": "unstyled"
}
],
"entities": []
}
}'
```
Si la solicitud se realiza correctamente, deberías ver la respuesta JSON que se muestra a continuación:
```json theme={null}
{
"data": {
"id": "1146654567674912769",
"title": "My first Article"
}
}
```
Después puedes publicar el borrador usando el ID de Article devuelto:
```bash theme={null}
curl --request POST 'https://api.x.com/2/articles/1146654567674912769/publish' \
--header 'Authorization: Bearer XXXXX'
```
Si la solicitud se realiza correctamente, la respuesta contiene el ID de la publicación creada para el Article publicado:
```json theme={null}
{
"data": {
"post_id": "1346889436626259968"
}
}
```
# Enterprise
Source: https://docs.x.com/es/x-api/enterprise-gnip-2.0/enterprise-gnip
Resumen de las APIs enterprise de X y los productos Gnip, incluyendo PowerTrack, Decahose, Search, Engagement, Account Activity y Compliance Firehose.
Nuestras API enterprise ofrecen el nivel más alto de acceso y confiabilidad para quienes dependen de los datos de X. Ideal a medida que escalas más allá de premium y necesitas acceso más confiable, paquetes personalizados o contratos a más largo plazo. El acceso a las API enterprise incluye gerentes de cuenta dedicados y soporte técnico personalizado.
Si identificaste que el plan de autoservicio no es suficiente para tus necesidades, puedes solicitar acceso a los productos enterprise en el siguiente enlace:
## Endpoints disponibles
| Tiempo real | [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) | Ofrece cobertura completa de los Posts públicos a medida que ocurren, filtrables mediante una amplia gama de operadores y reglas. |
| :------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| [Decahose API](/x-api/enterprise-gnip-2.0/fundamentals/decahose-api) | Transmite una muestra aleatoria del 10% de todos los Posts públicos y sus Me gusta. | |
| :--- | :--- | :--- |
| [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) | Suscríbete a usuarios y recibe diversas actividades, incluidos Posts, mensajes directos, Me gusta, seguimientos y más. | |
| :--- | :--- | :--- |
| Histórico | [Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) | Busca en los últimos 30 días o en el archivo completo de Posts públicos usando herramientas avanzadas de filtrado. |
| [Historical PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) | Filtra el archivo completo de Posts públicos mediante un proceso de acceso por lotes y económico. | |
| Insights | [Engagement API](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api) | Mide el volumen de impresiones e interacciones de los Posts públicos. |
| Cumplimiento | [Compliance Firehose API](/x-api/enterprise-gnip-2.0/fundamentals/firehouse) | Transmite todos los eventos de cumplimiento. |
| Uso | [Usage API](/x-api/enterprise-gnip-2.0/fundamentals/usage) | Proporciona acceso programático al consumo de actividad en todos los productos enterprise. |
## Conceptos importantes
### Consola de Gnip
Puedes gestionar tus productos enterprise y el acceso de la cuenta a través de la [Consola de Gnip](/x-api/enterprise-gnip-2.0/fundamentals/overview).
### Enriquecimientos
Hemos añadido metadatos a la carga útil de respuesta de las API premium para los desarrolladores que utilizan un nivel de pago. Obtén más información sobre URL expandidas, datos de encuestas y geolocalización de perfiles visitando nuestra [sección de enriquecimientos](/x-api/enterprise-gnip-2.0/fundamentals/data-enrichments).
### Herramientas avanzadas de filtrado
La Premium Search API pone a disposición un conjunto avanzado de operadores que no están disponibles con el endpoint de búsqueda estándar. Muchos de estos operadores están disponibles para los usuarios de la sandbox gratuita, pero obtendrás un conjunto de operadores más robusto si utilizas un nivel de pago. Obtén más información visitando nuestra [sección de reglas y filtros](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering#getting-started-with-enterprise-rules-and-queries).
## Explorar la X API v2
¿Te interesa explorar lo que ya está disponible en v2? Consulta nuestra documentación para ver las novedades y visita el centro de migración para obtener recursos que te ayudarán a migrar a la X API v2. También puedes acceder a las guías de migración para cada endpoint listado en las nuevas secciones de endpoints de v2.
[Más información](/x-api/migrate/overview)
¿Necesitas ayuda?
Consulta nuestra sección de soporte o comunícate con tu gerente de cuenta para saber cómo ponerte en contacto con nuestro equipo de soporte.
[Soporte](https://developer.x.com/en/support/x-api))
# Acerca de la API de X
Source: https://docs.x.com/es/x-api/getting-started/about-x-api
La API de X ofrece acceso programático a la conversación pública. Recupera posts, analiza tendencias, crea integraciones y nuevas experiencias en X.
La API de X proporciona acceso programático a la conversación pública de X. Recupera publicaciones, analiza tendencias, crea integraciones y diseña nuevas experiencias en la plataforma.
***
## Qué puedes hacer
| Capacidad | Descripción |
| :----------------------- | :-------------------------------------------------------------- |
| **Leer publicaciones** | Busca, consulta y transmite publicaciones en tiempo real |
| **Publicar contenido** | Crea publicaciones, respuestas e hilos |
| **Administrar usuarios** | Consulta usuarios y gestiona seguimientos, bloqueos y silencios |
| **Analizar datos** | Accede a métricas, tendencias y análisis de interacción |
| **Crear integraciones** | Envía DMs, administra listas e interactúa con Spaces |
***
## Versiones de la API
La versión actual de la API de X con funciones modernas y precios flexibles.
**Por qué usar v2:**
* Precios de pago por uso
* Formato de respuesta JSON moderno
* [Fields](/x-api/fundamentals/fields) y [expansions](/x-api/fundamentals/expansions) flexibles
* Funciones avanzadas: anotaciones, seguimiento de conversaciones, historial de ediciones
* Todos los nuevos endpoints y funciones
**Primeros pasos:**
1. Regístrate en [console.x.com](https://console.x.com)
2. Crea una app y obtén tus credenciales
3. [Realiza tu primera solicitud](/x-api/getting-started/make-your-first-request)
La versión anterior de la API de X. Soporte limitado; usa v2 para nuevos proyectos.
**Aún disponible:**
* Algunos endpoints de carga de medios
* Streaming heredado (en desuso)
* Algunos endpoints especializados
**Migrar a v2:**
Consulta la [guía de migración](/x-api/migrate/overview) para conocer la asignación de endpoints y los cambios de formato de datos.
***
## Recursos disponibles
La API de X proporciona acceso a estos tipos de recursos:
Busca, recupera, crea y elimina publicaciones. Accede a líneas de tiempo, hilos y citas.
Consulta perfiles, gestiona relaciones y accede a datos de seguidores.
Descubre conversaciones de audio en vivo y sus participantes.
Envía y recibe mensajes privados entre usuarios.
Crea y administra listas seleccionadas de cuentas.
Accede a temas en tendencia por ubicación.
***
## Aspectos destacados de v2
Solicita únicamente los datos que necesitas. Usa los parámetros `fields` para seleccionar atributos específicos y `expansions` para incluir objetos relacionados.
```bash theme={null}
curl "https://api.x.com/2/tweets/123?tweet.fields=created_at,public_metrics&expansions=author_id&user.fields=username" \
-H "Authorization: Bearer $TOKEN"
```
[Más información sobre fields →](/x-api/fundamentals/fields)
Las publicaciones incluyen anotaciones semánticas que identifican personas, lugares, productos y temas. Filtra streams y búsquedas por tema.
[Más información sobre anotaciones →](/x-api/fundamentals/post-annotations)
Accede a métricas públicas (me gusta, reposts, respuestas) y a métricas privadas (impresiones, clics) de tus propias publicaciones.
[Más información sobre métricas →](/x-api/fundamentals/metrics)
Reconstruye hilos de conversación completos usando `conversation_id`. Realiza un seguimiento de las respuestas a lo largo de todo el hilo.
[Más información sobre el seguimiento de conversaciones →](/x-api/fundamentals/conversation-id)
Accede al historial de ediciones de las publicaciones, incluidas todas las versiones anteriores y los metadatos de edición.
[Más información sobre la edición de publicaciones →](/x-api/fundamentals/edit-posts)
***
## Precios
X API v2 utiliza precios de **pago por uso**:
| Beneficio | Descripción |
| :----------------------------- | :---------------------------------------------------------------------- |
| **Sin suscripciones** | Paga solo por lo que usas |
| **Basado en créditos** | Compra créditos que se descuentan por solicitud |
| **Seguimiento en tiempo real** | Monitorea el uso en la Developer Console |
| **Deduplicación** | El mismo recurso solicitado dos veces en 24 horas solo se cobra una vez |
[Ver detalles de precios →](/x-api/getting-started/pricing)
***
## Próximos pasos
Regístrate y crea tu primera app.
Llama a la API en minutos.
# Obtener acceso
Source: https://docs.x.com/es/x-api/getting-started/getting-access
Regístrate para obtener una cuenta de desarrollador, crea una app y guarda las API keys, el bearer token y las credenciales de OAuth que necesitas para empezar a llamar a la X API.
Empieza con la X API en tres pasos: regístrate, crea una app y guarda tus credenciales.
***
## Paso 1: Crea una cuenta de desarrollador
Visita [console.x.com](https://console.x.com) e inicia sesión con tu cuenta de X.
Revisa y acepta el Acuerdo y la Política del Desarrollador.
Proporciona información básica sobre cómo usarás la API.
***
## Paso 2: Crea una app
Después de registrarte, crea una app para obtener tus credenciales de API:
Desde el panel de la Developer Console, crea una nueva app.
Proporciona un nombre, descripción y caso de uso para tu app.
La consola generará tus API keys y tokens.
***
## Paso 3: Guarda tus credenciales
Recibirás varias credenciales dependiendo de tus necesidades de autenticación:
| Credencial | Propósito |
| :------------------------ | :------------------------------------------------------------------------------- |
| **API Key y Secret** | Identifican tu app. Se usan para generar tokens y firmar solicitudes OAuth 1.0a. |
| **Bearer Token** | Autenticación app-only para leer datos públicos. |
| **Access Token y Secret** | Realiza solicitudes en nombre de tu propia cuenta (OAuth 1.0a). |
| **Client ID y Secret** | Autenticación OAuth 2.0 para solicitudes con contexto de usuario. |
**Guárdalas inmediatamente.** Las credenciales solo se muestran una vez. Almacénalas en un gestor de contraseñas o una bóveda segura. Si las pierdes, tendrás que regenerarlas (lo que invalida las anteriores).
***
## ¿Qué credenciales necesitas?
Usa el **Bearer Token** para acceso simple, de solo lectura a datos públicos.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Ideal para: Buscar posts, consultar usuarios, leer tendencias.
Usa **OAuth 2.0** (recomendado) o **OAuth 1.0a** para actuar en nombre de los usuarios.
OAuth 2.0 ofrece scopes granulares: solicita solo los permisos que necesites.
Ideal para: Publicar, dar Like, seguir, acceder a DMs.
[Guía de OAuth 2.0 →](/resources/fundamentals/authentication/oauth-2-0/overview)
Usa tu **Access Token y Secret** para realizar solicitudes como tu propia cuenta.
Estos tokens representan la cuenta propietaria de la app.
Ideal para: Pruebas, bots personales, tu propia automatización.
***
## Mejores prácticas de seguridad de credenciales
Nunca incrustes credenciales en tu código fuente.
Añade los archivos de credenciales a `.gitignore`.
Regenera las credenciales periódicamente como medida de seguridad.
Solicita solo los permisos de OAuth que tu app necesita.
***
## Próximos pasos
Llama a la API con tus nuevas credenciales.
Comprende OAuth 1.0a y OAuth 2.0.
# Precios de la X API por uso y créditos
Source: https://docs.x.com/es/x-api/getting-started/pricing
La X API usa precios de pago por uso, sin suscripciones. Paga solo por lo que consumas y gana hasta un 20% de devolución en créditos gratuitos de la xAI API.
La X API utiliza precios de **pago por uso**. Sin suscripciones: paga solo por lo que usas.
***
## Cómo funciona
Compra créditos por adelantado en la Developer Console. Los créditos se deducen a medida que realizas solicitudes a la API.
Diferentes endpoints tienen distintos costos. Consulta las tarifas actuales en la Developer Console.
Sin contratos, suscripciones ni gasto mínimo. Comienza y detente cuando quieras.
Monitorea el uso y los costos en vivo desde la Developer Console.
Gana créditos gratuitos de la [xAI API](https://docs.x.ai) cuando compras créditos de la X API: hasta un 20% de devolución según tu gasto. [Más información](#free-xai-api-credits)
***
## Detalles de consumo de créditos
Todos los precios son por recurso obtenido (lecturas) o por solicitud (escrituras/acciones). [Compra créditos](https://console.x.com) en la Developer Console.
### Operaciones de lectura
Se cobra por cada recurso devuelto en la respuesta.
| Recurso | Costo unitario |
| :---------------------------- | :------------------ |
| **Posts: Read** | \$0.005 por recurso |
| **User: Read** | \$0.010 por recurso |
| **DM Event: Read** | \$0.010 por recurso |
| **Following/Followers: Read** | \$0.010 por recurso |
| **List: Read** | \$0.005 por recurso |
| **Space: Read** | \$0.005 por recurso |
| **Community: Read** | \$0.005 por recurso |
| **Note: Read** | \$0.005 por recurso |
| **Like: Read** | \$0.001 por recurso |
| **Mute: Read** | \$0.001 por recurso |
| **Block: Read** | \$0.001 por recurso |
| **Profile Update: Read** | \$0.005 por recurso |
Los planes de pago por uso están sujetos a un tope de **2 millones de lecturas de posts por ciclo de facturación mensual**. Si necesitas un volumen mayor, deberás actualizar a un [plan Enterprise](/forms/enterprise-api-interest).
### Operaciones de escritura
Se cobra por solicitud.
| Acción | Costo unitario |
| :--------------------------- | :-------------------- |
| **Post: Create** | \$0.015 por solicitud |
| **Post: Create (with URL)** | \$0.200 por solicitud |
| **Post: Create (summoned)** | \$0.010 por solicitud |
| **DM Interaction: Create** | \$0.015 por solicitud |
| **User Interaction: Create** | \$0.015 por solicitud |
| **Interaction: Delete** | \$0.010 por solicitud |
| **Content: Manage** | \$0.005 por solicitud |
| **List: Create** | \$0.010 por solicitud |
| **List: Manage** | \$0.005 por solicitud |
| **Bookmark** | \$0.005 por solicitud |
| **Media Metadata** | \$0.005 por solicitud |
| **Privacy: Update** | \$0.010 por solicitud |
| **Mute: Delete** | \$0.005 por solicitud |
| **Counts: Recent** | \$0.005 por solicitud |
| **Counts: All** | \$0.010 por solicitud |
| **Trends** | \$0.010 por solicitud |
Los precios están sujetos a cambios. Las tarifas actuales siempre están disponibles en la [Developer Console](https://console.x.com) y en la [página de precios de developer.x.com](https://developer.x.com/#pricing).
### Eventos de webhook
Los eventos de webhook entregados a través de la [X Activity API](/x-api/activity/introduction) se cobran por evento entregado, usando los mismos nombres de evento que se muestran en la documentación de la Activity API. Se te cobra una vez por cada evento facturable, deduplicado dentro de la misma ventana de 24 horas UTC que los demás recursos.
| Evento | Costo por evento |
| :----------------------- | :--------------- |
| `post.create` | \$0.005 |
| `post.delete` | No se cobra |
| `follow.follow` | \$0.010 |
| `follow.unfollow` | \$0.010 |
| `profile.update.*` | \$0.005 |
| `chat.received` | \$0.010 |
| `chat.sent` | No se cobra |
| `chat.conversation_join` | No se cobra |
| `dm.received` | \$0.010 |
| `dm.sent` | No se cobra |
| `dm.read` | No se cobra |
| `dm.indicate_typing` | No se cobra |
| `news.new` | \$0.005 |
| `spaces.start` | \$0.005 |
| `spaces.end` | \$0.005 |
***
## Owned Reads
Las Owned Reads son solicitudes realizadas por tu propia developer app para acceder a tus propios datos (posts, marcadores, seguidores, likes, listas y más). Estos endpoints tienen un precio de **\$0.001 por recurso** (1,000 recursos por \$1).
Los siguientes endpoints califican para los precios de Owned Read cuando `{id}` coincide con el usuario autenticado y ese usuario es el propietario de la developer app:
| Endpoint | Descripción |
| :----------------------------------- | :-------------------------- |
| `GET /2/users/{id}/tweets` | Tus propios posts |
| `GET /2/users/{id}/mentions` | Tus menciones |
| `GET /2/users/{id}/liked_tweets` | Posts a los que diste like |
| `GET /2/users/{id}/bookmarks` | Tus marcadores |
| `GET /2/users/{id}/followers` | Tus seguidores |
| `GET /2/users/{id}/following` | Cuentas que sigues |
| `GET /2/users/{id}/blocking` | Cuentas que bloqueaste |
| `GET /2/users/{id}/muting` | Cuentas que silenciaste |
| `GET /2/users/{id}/owned_lists` | Listas que posees |
| `GET /2/users/{id}/followed_lists` | Listas que sigues |
| `GET /2/users/{id}/list_memberships` | Listas a las que perteneces |
| `GET /2/users/{id}/pinned_lists` | Tus listas fijadas |
Las Owned Reads hacen que sea significativamente más económico construir aplicaciones que trabajen con los datos del propio usuario, como dashboards, analítica personal o herramientas de gestión de cuentas.
***
## Deduplicación
Todos los recursos se deduplican dentro de una **ventana de 24 horas UTC**. Si solicitas un recurso (como un Post) y se te cobra por él, volver a solicitar el mismo recurso dentro de esa ventana no generará un cargo adicional.
Esto significa que:
* Solicitar el mismo Post varias veces en un día cuenta como un solo cargo
* La ventana de deduplicación se reinicia a la medianoche UTC
* Esto aplica a todos los recursos facturables (Posts, usuarios, etc.)
La deduplicación es una **garantía blanda**. Si bien ocurre en la gran mayoría de los casos, pueden existir situaciones específicas, como interrupciones del servicio, en las que los recursos no se dedupliquen.
***
## Saldo de créditos
Tu saldo de créditos se muestra en la Developer Console. Los créditos se deducen en tiempo real a medida que realizas solicitudes a la API.
Monitorea tu saldo de créditos con regularidad para evitar interrupciones del servicio. Agrega créditos antes de que tu saldo llegue a cero para asegurar un acceso ininterrumpido a la API.
***Nota:** Es posible que el saldo de créditos de una cuenta se vuelva ligeramente negativo. En ese caso, las solicitudes a la API serán bloqueadas hasta que agregues créditos para cubrir el saldo negativo.*
### Recarga automática
Activa la recarga automática para reponer tu saldo de créditos de forma automática y evitar interrupciones del servicio. Configura esto en la Developer Console:
| Configuración | Descripción |
| :----------------------- | :----------------------------------------------------------------------------------------- |
| **Monto de recarga** | El monto que se agrega cuando se activa la recarga automática (p. ej., \$25) |
| **Umbral de activación** | La recarga automática se activa cuando tu saldo cae por debajo de este monto (p. ej., \$5) |
La recarga automática requiere un método de pago guardado como predeterminado. Puedes cancelarla en cualquier momento desde la Developer Console o contactando con soporte.
#### Salvaguardas de la recarga automática
Para protegerte de cargos descontrolados o inesperadamente grandes, la recarga automática incluye dos límites integrados:
* **Una recarga por ventana de 5 minutos.** Los cargos automáticos pueden activarse como máximo una vez cada 5 minutos, de modo que un pico repentino de uso no puede acumular varias recargas consecutivas.
* **Pausada con saldo cero o negativo.** La recarga automática no se ejecuta mientras el saldo de tu cuenta sea cero o negativo. Agrega créditos manualmente para reanudar las recargas automáticas.
Si tu uso es lo suficientemente intermitente como para agotar una recarga completa en menos de 5 minutos, aún podrías ver errores de "sin créditos" incluso con la recarga automática activada. Aumenta tu **Monto de recarga** para que una sola recarga supere cómodamente una ventana de 5 minutos de tu consumo máximo.
***
### Límites de gasto
Establece un monto máximo que puedes gastar por ciclo de facturación para controlar los costos. Cuando se alcanza el límite, las solicitudes a la API serán bloqueadas hasta el siguiente ciclo de facturación.
| Opción | Descripción |
| :------------------ | :------------------------------------------------------------------------------------- |
| **Límite de gasto** | Establece un monto en dólares específico como tu gasto máximo por ciclo de facturación |
Usa los límites de gasto para prevenir cargos inesperados, especialmente durante el desarrollo y las pruebas.
***
## Créditos gratuitos de la xAI API
Cuando compras créditos de la X API, puedes ganar créditos gratuitos de la [xAI API](https://docs.x.ai) en función de tu gasto acumulado durante un ciclo de facturación.
Para recibir créditos gratuitos de xAI, debes vincular tu equipo de xAI con tu cuenta de developer de X. Puedes hacerlo visitando la configuración de tu cuenta en la [developer console](https://console.x.com).
### Cómo funciona
Tu gasto acumulado se rastrea a lo largo de cada ciclo de facturación. A medida que cruzas los umbrales de gasto, desbloqueas tasas de recompensa más altas. Cuando comienza un nuevo ciclo de facturación, tu gasto acumulado se reinicia a \$0.
| Gasto acumulado | Tasa |
| :-------------- | :--- |
| \$0 – \$199 | 0% |
| \$200 – \$499 | 10% |
| \$500 – \$999 | 15% |
| \$1,000+ | 20% |
La tasa se aplica a tu **saldo acumulado completo**, pero solo recibes el delta: lo que se te debe nuevamente menos lo que ya se te acreditó.
### Ejemplo
Supón que realizas varias compras a lo largo de un ciclo de facturación:
| Compra | Tasa | Total adeudado | Ya acreditado | Recibes |
| :---------- | :--- | :------------- | :------------ | :---------- |
| \$100 | 0% | \$0 | \$0 | **\$0** |
| \$100 | 10% | \$20 | \$0 | **\$20** |
| \$150 | 10% | \$35 | \$20 | **\$15** |
| \$150 | 15% | \$75 | \$35 | **\$40** |
| \$250 | 15% | \$112.50 | \$75 | **\$37.50** |
| \$250 | 20% | \$200 | \$112.50 | **\$87.50** |
| | | | | |
| **\$1,000** | | | | **\$200** |
Esta es la misma cantidad que recibirías por una sola compra de \$1,000: el orden y el tamaño de las compras no afectan tus recompensas totales.
Consulta tu saldo de créditos de xAI y administra tu cuenta en [console.x.ai](https://console.x.ai). Para más detalles sobre la facturación de la xAI API, consulta la [documentación de facturación de xAI](https://docs.x.ai/docs/key-information/billing).
***
## Monitoreo del uso
Rastrea el uso de tu API de forma programática con el [endpoint de Usage](/x-api/usage/introduction):
```bash theme={null}
curl "https://api.x.com/2/usage/tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Esto devuelve los conteos diarios de consumo de Posts, ayudándote a:
* Rastrear el consumo en relación con tu presupuesto
* Configurar alertas cuando te acerques a los límites
* Identificar los endpoints con mayor consumo
* Generar informes de uso
***
## Próximos pasos
Compra créditos y consulta los precios actuales.
Monitorea el uso de forma programática.
# X API
Source: https://docs.x.com/es/x-api/introduction
Acceso programático a X con endpoints REST de v2 para Posts, usuarios, Spaces, listas, DMs y tendencias, con precios de pago por uso y SDKs modernos.
La X API te da acceso programático a la conversación pública de X. Lee posts, publica contenido, administra usuarios y analiza tendencias, todo a través de endpoints REST modernos con precios flexibles de pago por uso.
Crea una app y realiza tu primera solicitud en minutos.
Explora todos los endpoints disponibles.
Bibliotecas oficiales de Python y TypeScript.
***
## Qué puedes construir
Busca, recupera y publica posts. Accede a timelines, hilos y quote posts.
Busca usuarios, administra follows, bloqueos y silencios.
Encuentra conversaciones de audio en vivo y sus participantes.
Envía y recibe mensajes privados.
Crea y administra listas curadas de cuentas.
Accede a temas en tendencia por ubicación.
***
## Precios
La X API utiliza precios de **pago por uso**. Sin suscripciones: paga solo por lo que uses.
Empieza con algo pequeño y crece. Los costos escalan con tu uso real.
Sin contratos ni gasto mínimo. Detente cuando quieras.
Monitorea uso y costos en vivo desde la Developer Console.
Compra créditos por adelantado. Se descuentan a medida que usas la API.
Gana créditos gratuitos de la [xAI API](https://docs.x.ai) cuando compras créditos de la X API: hasta un 20% de devolución según tu gasto. [Más información](/x-api/getting-started/pricing#free-xai-api-credits)
***
## Funciones clave
### Objetos de datos enriquecidos
Accede a datos detallados y estructurados para posts, usuarios, medios y más:
* **Posts**: Texto completo, métricas, entidades, anotaciones, hilos de conversación
* **Usuarios**: Perfiles, conteo de seguidores, estado de verificación
* **Medios**: Imágenes, videos, GIFs con metadatos
* **Encuestas**: Opciones y conteo de votos
Personaliza las respuestas con [fields](/x-api/fundamentals/fields) y [expansions](/x-api/fundamentals/expansions) para obtener exactamente los datos que necesitas.
### Filtered stream
Recibe los posts entregados casi en tiempo real a medida que se publican. Define hasta 1,000 reglas de filtrado para recibir solo los posts coincidentes.
```bash theme={null}
# Agregar una regla
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $TOKEN" \
-d '{"add": [{"value": "from:xdevelopers"}]}'
# Conectarse al stream
curl "https://api.x.com/2/tweets/search/stream" \
-H "Authorization: Bearer $TOKEN"
```
[Más información sobre filtered stream →](/x-api/posts/filtered-stream/introduction)
### Búsqueda en archivo completo
Busca el historial completo de posts públicos, hasta 2006. Crea consultas con operadores para usuarios, palabras clave, fechas y más.
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?query=AI%20lang:en" \
-H "Authorization: Bearer $TOKEN"
```
### Métricas
Accede a métricas de interacción que incluyen impresiones, likes, reposts, respuestas y vistas de video.
[Más información sobre búsqueda →](/x-api/posts/search/introduction)
***
## Inicio rápido
Regístrate en [console.x.com](https://console.x.com) y crea una app.
Genera tu Bearer Token para solicitudes app-only.
Prueba buscando un usuario:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Herramientas y bibliotecas
Biblioteca oficial de Python con soporte async.
Biblioteca oficial de TypeScript/JavaScript.
Explorador interactivo de la API.
[Explora todas las bibliotecas →](/tools-and-libraries)
***
## Soporte
Obtén ayuda de la comunidad y del equipo de X.
Preguntas frecuentes y guías de solución de problemas.
# Descripción general de la X API
Source: https://docs.x.com/es/x-api/overview
Referencia completa de la X API v2 que cubre Posts, usuarios, Spaces, Mensajes Directos, listas, tendencias, medios, cumplimiento, streaming y endpoints de webhook.
La X API te da acceso programático a la conversación pública de X. Todos los endpoints a continuación están disponibles en los planes de [pago por uso](/x-api/introduction). Los endpoints marcados como Enterprise-only requieren un plan [Enterprise](/enterprise-api/introduction).
***
## Endpoints
Busca, obtén y publica posts. Accede a timelines, hilos y quote posts.
Consulta perfiles, gestiona seguimientos, bloqueos y silenciados.
Envía y recibe mensajes privados.
Encuentra conversaciones de audio en vivo y sus participantes.
Crea y gestiona listas curadas de cuentas.
Da y quita Like a posts. Consulta quién ha dado Like a un post.
Temas tendencia por ubicación y tendencias personalizadas.
Sube imágenes, videos y GIFs. Gestiona subtítulos y metadatos.
Consulta y busca communities.
Crea, evalúa y busca community notes.
Busca y obtén historias de noticias.
Trabajos de cumplimiento por lotes y streams de cumplimiento.
***
## Streaming y tiempo real
Recibe posts en tiempo real que coincidan con tus reglas de filtro.
Suscríbete a eventos de actividad en tiempo real como follows, likes y actualizaciones de perfil.
Recibe datos de eventos a través de callbacks HTTP.
***
## Solo Enterprise
Estos endpoints requieren un [plan Enterprise](/enterprise-api/introduction).
Firehose completo y streams específicos por idioma.
Transmite todos o una muestra de likes en tiempo real.
Streaming filtrado de alto rendimiento con operadores avanzados.
Métricas de interacción de posts y medios a escala.
Suscripciones a eventos de usuario en tiempo real.
Entrega de filtered stream a través de webhooks.
***
## Guía rápida
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Obtén tus credenciales y llama a la API en minutos.
Bibliotecas oficiales de Python y TypeScript.
# Operadores de Filtered Stream
Source: https://docs.x.com/es/x-api/posts/filtered-stream/integrate/operators
Referencia de operadores de Filtered Stream (X API v2): palabras clave, has:, is: y el operador embedding: exclusivo de Enterprise para reglas de stream.
Esta página proporciona una lista completa de los operadores disponibles al [crear reglas](/x-api/posts/filtered-stream/integrate/build-a-rule) para Filtered Stream.
## Descripción general
Los operadores se utilizan para coincidir con atributos específicos de las publicaciones. Hay dos tipos:
* **Operadores independientes** — Pueden usarse solos o junto con cualquier otro operador
* **Operadores que requieren conjunción** — Deben usarse con al menos un operador independiente
La mayoría de los operadores están disponibles tanto en Pay-per-use como en Enterprise. Algunos operadores avanzados (como el de embedding semántico) requieren Enterprise con acceso a un nivel adicional.
***
## Operadores de palabras clave y frases
| Operador | Tipo | Resumen | Ejemplo |
| :---------------------- | :------------ | :-------------------------------------------------------------------------------------- | :------------------------------------ |
| `keyword` | Independiente | Coincide con una palabra clave en el cuerpo de la publicación (coincidencia tokenizada) | `pepsi OR cola OR "coca cola"` |
| `emoji` | Independiente | Coincide con un emoji en el cuerpo de la publicación | `(😃 OR 😡) 😬` |
| `"exact phrase"` | Independiente | Coincide con la frase exacta en el cuerpo de la publicación | `("X API" OR #v2) -"filtered stream"` |
| `"keyword1 keyword2"~N` | Independiente | Coincidencia por proximidad — palabras clave dentro de N tokens entre sí (máximo N=6) | `"social media"~5` |
***
## Operadores de entidades
| Operador | Tipo | Resumen | Ejemplo |
| :------- | :------------ | :------------------------------------------------------------------------ | :--------------------------- |
| `#` | Independiente | Coincide con publicaciones que contienen un hashtag (coincidencia exacta) | `#thankunext #fanart` |
| `@` | Independiente | Coincide con publicaciones que mencionan un nombre de usuario | `(@XDevelopers OR @api) -@x` |
| `$` | Independiente | Coincide con publicaciones que contienen un cashtag | `$twtr OR @XDevelopers -$fb` |
***
## Operadores de usuario
| Operador | Tipo | Resumen | Ejemplo |
| :------------------- | :------------ | :---------------------------------------------------------------------------- | :------------------------------ |
| `from:` | Independiente | Coincide con publicaciones de un usuario específico | `from:XDevelopers OR from:api` |
| `to:` | Independiente | Coincide con publicaciones que responden a un usuario específico | `to:XDevelopers OR to:api` |
| `retweets_of:` | Independiente | Coincide con Retweets de un usuario específico | `retweets_of:XDevelopers` |
| `from_affiliate_of:` | Independiente | Coincide con publicaciones de afiliados de un usuario específico | `from_affiliate_of:XDevelopers` |
| `to_affiliate_of:` | Independiente | Coincide con publicaciones que responden a afiliados de un usuario específico | `to_affiliate_of:XDevelopers` |
***
## Operadores de URL
| Operador | Tipo | Resumen | Ejemplo |
| :----------------- | :------------ | :-------------------------------------------------------------------------------------- | :------------------------------ |
| `url:` | Independiente | Coincidencia tokenizada en la URL (coincide con los campos `url` o `expanded_url`) | `url:"https://developer.x.com"` |
| `url_title:` | — | Coincidencia de palabra clave en los metadatos del título HTML de la URL expandida | `url_title:snow` |
| `url_description:` | — | Coincidencia de palabra clave en los metadatos de la descripción de la página expandida | `url_description:weather` |
| `url_contains:` | — | Coincidencia literal con el contenido de la URL | `url_contains:photos` |
***
## Operadores de contexto y entidades
| Operador | Tipo | Resumen | Ejemplo |
| :----------------- | :------------ | :---------------------------------------------------------------------- | :----------------------------------------------- |
| `context:` | Independiente | Coincide con publicaciones con un par específico de dominio/entidad | `context:10.799022225751871488` o `context:47.*` |
| `entity:` | Independiente | Coincide con publicaciones con un valor de cadena de entidad específico | `entity:"Michael Jordan"` |
| `conversation_id:` | Independiente | Coincide con publicaciones en un hilo de conversación | `conversation_id:1334987486343299072` |
***
## Operadores de perfil de usuario
| Operador | Tipo | Resumen | Ejemplo |
| :-------------- | :------------ | :------------------------------------------------------------------------- | :--------------------------------------------- |
| `bio:` | Independiente | Coincide con una palabra clave en la biografía del autor de la publicación | `bio:developer OR bio:"data engineer"` |
| `bio_name:` | Independiente | Coincide con una palabra clave en el nombre del autor de la publicación | `bio_name:phd OR bio_name:md` |
| `bio_location:` | Independiente | Coincide con una palabra clave en la ubicación del autor de la publicación | `bio_location:"big apple" OR bio_location:nyc` |
***
## Operadores de ubicación
| Operador | Tipo | Resumen | Ejemplo |
| :--------------- | :------------ | :------------------------------------------------------------------ | :---------------------------------------------------------- |
| `place:` | Independiente | Coincide con publicaciones etiquetadas con una ubicación | `place:"new york city" OR place:seattle` |
| `place_country:` | Independiente | Coincide con publicaciones que tienen un código de país | `place_country:US OR place_country:MX` |
| `point_radius:` | Independiente | Coincide con publicaciones dentro de un radio alrededor de un punto | `point_radius:[2.355128 48.861118 16km]` |
| `bounding_box:` | Independiente | Coincide con publicaciones dentro de un cuadro delimitador | `bounding_box:[-105.301758 39.964069 -105.178505 40.09455]` |
***
## Operadores de tipo de publicación
| Operador | Tipo | Resumen | Ejemplo |
| :------------- | :------------------ | :--------------------------------------------------- | :------------------------------ |
| `is:retweet` | Requiere conjunción | Coincide con Retweets | `data @XDevelopers -is:retweet` |
| `is:reply` | Requiere conjunción | Coincide con respuestas | `from:XDevelopers is:reply` |
| `is:quote` | Requiere conjunción | Coincide con Quote Tweets | `"sentiment analysis" is:quote` |
| `is:verified` | Requiere conjunción | Coincide con publicaciones de autores verificados | `#nowplaying is:verified` |
| `-is:nullcast` | Requiere conjunción | Excluye publicaciones promocionales (debe ir negado) | `"mobile games" -is:nullcast` |
***
## Operadores de tipo de contenido
| Operador | Tipo | Resumen | Ejemplo |
| :--------------- | :------------------ | :----------------------------------------------------------------- | :----------------------------------- |
| `has:hashtags` | Requiere conjunción | Coincide con publicaciones que contienen hashtags | `from:XDevelopers -has:hashtags` |
| `has:cashtags` | Requiere conjunción | Coincide con publicaciones que contienen cashtags | `#stonks has:cashtags` |
| `has:links` | Requiere conjunción | Coincide con publicaciones que contienen enlaces | `from:XDevelopers has:links` |
| `has:mentions` | Requiere conjunción | Coincide con publicaciones que contienen menciones | `#nowplaying has:mentions` |
| `has:media` | Requiere conjunción | Coincide con publicaciones que contienen medios (foto, GIF, video) | `(kittens OR puppies) has:media` |
| `has:images` | Requiere conjunción | Coincide con publicaciones que contienen imágenes | `#meme has:images` |
| `has:video_link` | Requiere conjunción | Coincide con publicaciones con videos nativos de X | `#icebucketchallenge has:video_link` |
| `has:geo` | Requiere conjunción | Coincide con publicaciones que contienen datos de geolocalización | `recommend #paris has:geo` |
***
## Operadores de muestreo e idioma
| Operador | Tipo | Resumen | Ejemplo |
| :-------- | :------------------ | :-------------------------------------------------------------- | :------------------------------- |
| `sample:` | Requiere conjunción | Devuelve una muestra aleatoria por porcentaje (1-100) | `#nowplaying @spotify sample:15` |
| `lang:` | Requiere conjunción | Coincide con publicaciones clasificadas en un idioma específico | `recommend #paris lang:en` |
***
## Operadores de métricas de usuario
| Operador | Tipo | Resumen | Ejemplo |
| :----------------- | :--- | :-------------------------------------------------------------------------------------------- | :---------------------------- |
| `min_followers:` | — | Coincide con publicaciones de usuarios con al menos el número especificado de seguidores | `min_followers:1000` |
| `followers_count:` | — | Coincide con publicaciones de usuarios cuyo número de seguidores esté en el rango indicado | `followers_count:1000..10000` |
| `tweets_count:` | — | Coincide con publicaciones de usuarios cuyo número de publicaciones esté en el rango indicado | `tweets_count:1000..10000` |
| `following_count:` | — | Coincide con publicaciones de usuarios cuyo número de seguidos esté en el rango indicado | `following_count:1000..10000` |
| `listed_count:` | — | Coincide con publicaciones de usuarios incluidos en el número especificado de Listas | `listed_count:10..100` |
***
## Operadores de referencia de publicación
| Operador | Tipo | Resumen | Ejemplo |
| :---------------------- | :--- | :----------------------------------------------------------------------------- | :----------------------------------------- |
| `in_reply_to_tweet_id:` | — | Coincide con respuestas a una publicación específica | `in_reply_to_tweet_id:1539382664746020864` |
| `retweets_of_tweet_id:` | — | Coincide con Retweets de una publicación específica | `retweets_of_tweet_id:1539382664746020864` |
| `source:` | — | Coincide con publicaciones provenientes de una aplicación de origen específica | `source:"X for iPhone"` |
***
## Operadores lógicos
| Operador | Resumen | Ejemplo |
| :------------ | :------------------------------------ | :--------------------------- |
| `OR` | OR lógico entre expresiones | `cat OR dog` |
| Espacio (AND) | AND lógico entre expresiones | `cat dog` (ambos requeridos) |
| `()` | Agrupación para expresiones complejas | `(cat OR dog) -is:retweet` |
| `-` | Negación/exclusión | `cat -grumpy` |
***
## Operadores de embedding
**Solo Enterprise — Se requiere el nivel Embedding**
Los operadores `embedding:` y `embedding_threshold:` solo están disponibles en cuentas Enterprise aprovisionadas con acceso al nivel Embedding para Filtered Stream. En niveles no compatibles, la creación de reglas se rechazará con un error de "operador no disponible". Comunícate con tu representante de cuenta para habilitarlo.
Estos operadores utilizan un modelo de embedding neuronal para coincidir con publicaciones por *similitud semántica* con una consulta, en lugar de requerir coincidencias exactas de palabras clave.
| Operador | Tipo | Resumen | Ejemplo |
| :------------------------- | :------------------ | :---------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------- |
| `embedding:"query"` | Independiente | Coincide con publicaciones semánticamente similares a la consulta. Las consultas con varias palabras deben ir entre comillas. | `embedding:"climate change policy"` |
| `embedding_threshold:X.XX` | Requiere conjunción | Similitud coseno mínima para una coincidencia (0.0–1.0). El valor predeterminado es `0.3`. Usa valores entre 0.3 y 0.6. | `embedding:"cryptocurrency regulation" embedding_threshold:0.45` |
### Requisitos y notas clave
* `embedding_threshold:` **no puede** ser el único operador en una regla. Combínalo con `embedding:` (u otro operador independiente).
* **No niegues** `embedding:` (por ejemplo, `-embedding:"..."` no es compatible).
* Las consultas en lenguaje natural más largas y descriptivas producen mejores resultados que las palabras clave cortas.
* El procesamiento de las consultas de embedding es asíncrono — las reglas recién creadas pueden tardar unos segundos antes de comenzar a coincidir.
* Cuando una publicación coincide mediante una regla de embedding, las entradas `matching_rules` del payload entregado contendrán `embedding_similarity` y `embedding_threshold` (consulta [Asociar publicaciones a reglas](/x-api/posts/filtered-stream/integrate/matching-returned-tweets)).
**Reglas de ejemplo:**
* `embedding:"electric vehicle announcements" lang:en -is:retweet has:links`
* `embedding:"natural disaster relief" embedding_threshold:0.45 has:media`
* `embedding:"renewable energy" embedding_threshold:0.4 OR embedding:"solar power investment"`
***
## Idiomas admitidos
El operador `lang:` admite estos códigos de idioma BCP 47:
| Idioma | Código | Idioma | Código | Idioma | Código |
| :--------- | :----- | :-------- | :----- | :----------------- | :------ |
| Amárico | `am` | Griego | `el` | Portugués | `pt` |
| Árabe | `ar` | Guyaratí | `gu` | Rumano | `ro` |
| Armenio | `hy` | Hebreo | `iw` | Ruso | `ru` |
| Euskera | `eu` | Hindi | `hi` | Serbio | `sr` |
| Bengalí | `bn` | Húngaro | `hu` | Chino simplificado | `zh-CN` |
| Búlgaro | `bg` | Indonesio | `in` | Eslovaco | `sk` |
| Catalán | `ca` | Italiano | `it` | Esloveno | `sl` |
| Croata | `hr` | Japonés | `ja` | Español | `es` |
| Checo | `cs` | Canarés | `kn` | Sueco | `sv` |
| Danés | `da` | Coreano | `ko` | Tamil | `ta` |
| Neerlandés | `nl` | Letón | `lv` | Telugu | `te` |
| Inglés | `en` | Lituano | `lt` | Tailandés | `th` |
| Estonio | `et` | Malayalam | `ml` | Chino tradicional | `zh-TW` |
| Finés | `fi` | Maratí | `mr` | Turco | `tr` |
| Francés | `fr` | Noruego | `no` | Ucraniano | `uk` |
| Alemán | `de` | Persa | `fa` | Urdu | `ur` |
| Georgiano | `ka` | Polaco | `pl` | Vietnamita | `vi` |
***
## Próximos pasos
Aprende la sintaxis de las reglas y sus mejores prácticas
Comienza con Filtered Stream
Maneja desconexiones de streaming
# Manual básico de criptografía
Source: https://docs.x.com/es/xchat/cryptography-primer
Aprende los conceptos de ECDH, cifrado con clave pública y firmas digitales detrás del cifrado de extremo a extremo de X Chat, sin implementación.
Este manual explica las ideas criptográficas detrás de X Chat a nivel conceptual. No necesitas esta profundidad para construir—el [Chat XDK](/xchat/xchat-xdk) realiza el cifrado, descifrado, firma y almacenamiento de claves por ti—pero el modelo mental ayuda cuando diseñas tu app o depuras su comportamiento.
Cuando estés listo para implementar, usa [Primeros pasos](/xchat/getting-started) para un recorrido completo y la [referencia de la API](/x-api/chat/get-chat-conversations) en la barra lateral para rutas individuales.
**Tú no implementas esta criptografía por tu cuenta.** El Chat XDK se encarga. Esta página es para entender, no una lista de verificación de la API.
***
## El panorama general
X Chat usa un sistema de cifrado por capas donde:
1. Los **mensajes** se cifran con una **clave de conversación** (cifrado simétrico rápido)
2. Las **claves de conversación** se cifran para cada participante usando su **clave pública de identidad** (intercambio asimétrico de claves)
3. Los **mensajes se firman** con la **clave de firma** para que los destinatarios puedan verificar quién los envió y que nada fue alterado
El cifrado simétrico es eficiente para mucho tráfico de mensajes; el cifrado asimétrico se usa principalmente para **distribuir** las claves de conversación de forma segura.
```mermaid theme={null}
flowchart TB
subgraph "Message Encryption"
A[Your Message] --> B[Encrypt with Conversation Key]
B --> C[Encrypted Message]
end
subgraph "Key Distribution"
D[Conversation Key] --> E[Encrypt with Recipient's Public Key]
E --> F[Encrypted Key for Recipient]
end
subgraph "Authentication"
C --> G[Sign with Your Private Key]
G --> H[Signature]
end
```
En el flujo del producto, X transporta **texto cifrado y sobres de claves**—no contenido legible de mensajes ni la clave de conversación en bruto. Tu app usa el Chat XDK para la criptografía y la [Chat API](/xchat/introduction) (mediante el XDK en Python/TypeScript, o HTTPS) para registrar claves y enviar o recibir esas cargas cifradas. Consulta [Primeros pasos](/xchat/getting-started) para ver cómo encajan esas piezas.
***
## Tipos de claves explicados
X Chat usa tres tipos de material de claves, cada uno con un propósito específico.
### 1. Par de claves de identidad
**Propósito:** Intercambiar de forma segura claves de conversación entre usuarios
| Componente | Descripción |
| :----------------------------- | :--------------------------------------------------------------------------------------- |
| **Clave pública de identidad** | Se comparte con otros; se usa para cifrar claves de conversación *dirigidas a* ti |
| **Clave privada de identidad** | Se mantiene en secreto; se usa para descifrar las claves de conversación enviadas *a* ti |
Cuando alguien te agrega a una conversación, cifra la clave de conversación usando tu clave pública de identidad. Solo tu clave privada de identidad puede descifrarla.
Las mitades públicas se registran y descubren a través de las APIs de **claves públicas** de la plataforma (consulta Encryption keys en la referencia de la API). Las mitades privadas permanecen dentro del Chat XDK (por ejemplo, mediante la [copia de seguridad segura de claves](#copia-de-seguridad-segura-de-claves-almacenamiento-distribuido-de-claves) o un blob de claves cuidadosamente protegido).
### 2. Par de claves de firma
**Propósito:** Demostrar que fuiste tú quien creó un mensaje
| Componente | Descripción |
| :------------------------- | :------------------------------------------------------ |
| **Clave pública de firma** | Se comparte con otros; se usa para verificar tus firmas |
| **Clave privada de firma** | Se mantiene en secreto; se usa para firmar tus mensajes |
Cuando envías un mensaje, se firma con tu clave privada de firma. Los destinatarios verifican usando tu clave pública de firma (también publicada mediante las APIs de claves públicas). El Chat XDK firma como parte del cifrado de un mensaje y puede verificar al descifrar cuando proporcionas el material de clave pública del remitente.
### 3. Clave de conversación
**Propósito:** Cifrar y descifrar mensajes (y multimedia) dentro de una conversación específica
| Propiedad | Descripción |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------- |
| **Simétrica** | La misma clave cifra y descifra |
| **Por conversación** | Cada conversación tiene su propia clave |
| **Compartida entre participantes** | Todos los participantes que deberían leer la conversación tienen una copia |
| **Versionada** | Las claves pueden rotarse; las apps deberían llevar registro de las versiones a lo largo del tiempo |
Las claves de conversación se generan cuando se configura una conversación o cuando las claves rotan. Cada participante recibe una **copia cifrada** de la clave, producida con su clave pública de identidad. Después de descifrar tu copia una vez, conservas la clave de conversación **en bruto** y la usas para cifrar mensajes (y [multimedia](/xchat/media)) de forma rápida. La configuración de esas copias para una conversación se hace mediante el Chat XDK junto con los endpoints de **claves** de conversación—se recorre en [Primeros pasos](/xchat/getting-started#4-set-up-conversation-keys).
***
## Cómo funciona el cifrado (conceptualmente)
### Enviar un mensaje
Escribes: "Hola, ¿cómo estás?"
Tu app usa la clave de conversación en bruto para este chat (obtenida de la configuración o de un evento previo de distribución de claves), para la versión correcta.
El Chat XDK cifra tu mensaje con la clave de conversación. El resultado es texto cifrado inútil sin esa clave.
El Chat XDK firma la carga cifrada con tu clave privada de firma, demostrando que tú creaste exactamente ese contenido.
Tu app envía la carga cifrada y la firma a X a través del endpoint **send message** de la Chat API. X almacena y entrega bytes que no puede leer como texto plano.
### Recibir un mensaje
Tu app recibe texto cifrado desde X—vía [webhooks o un activity stream](/xchat/real-time-events), o leyendo los **events** de la conversación para el historial.
Usa tu clave en bruto en caché, u obtenla descifrando tu copia desde un evento de distribución de claves (cambio de clave) si es nueva o rotada.
El Chat XDK comprueba la firma usando la clave pública de firma del remitente (y el vínculo de identidad correspondiente), de modo que sepas quién lo envió y que no fue modificado.
El Chat XDK descifra con la clave de conversación. Ahora puedes leer: "Hola, ¿cómo estás?"
La implementación de cifrar, enviar, recibir y descifrar está en [Primeros pasos](/xchat/getting-started) y en la referencia del [Chat XDK](/xchat/xchat-xdk).
***
## Distribución de claves explicada
Un desafío central del cifrado de extremo a extremo es la **distribución de claves**: cómo los participantes obtienen la clave de conversación **sin** que X (u otro observador) vea esa clave en claro.
### Configuración inicial de claves
Cuando se prepara una conversación para mensajería:
1. Se genera una clave de conversación aleatoria (en el Chat XDK)
2. Para **cada participante**, esa clave se cifra dirigida a su **clave pública de identidad**
3. Esas copias cifradas se almacenan y entregan mediante las APIs de Chat de X
4. Cada participante descifra **su** copia con su clave privada de identidad (en el Chat XDK)
X solo manipula las copias **envueltas**, nunca la clave de conversación en bruto.
### Eventos de cambio de clave
Cuando la clave de conversación se rota (por ejemplo, al cambiar la membresía), los participantes reciben un evento de **cambio de clave** con nuevas copias cifradas para cada miembro.
Tu app debería:
1. Detectar material de cambio de clave en los eventos en vivo o en el historial de la conversación
2. Descifrar y almacenar la nueva clave de conversación (y su versión)
3. Usar la versión más reciente para envíos posteriores
[Primeros pasos](/xchat/getting-started#6-receive-and-decrypt) y [Eventos en tiempo real](/xchat/real-time-events) describen dónde aparecen esos eventos en la práctica.
***
## Copia de seguridad segura de claves: almacenamiento distribuido de claves
Tus claves **privadas** de identidad y firma deben almacenarse con cuidado. X Chat incluye un sistema de **copia de seguridad segura de claves** (implementado con Juicebox) para que las claves puedan recuperarse con un código de acceso entre dispositivos sin darle a ningún servidor el secreto completo.
### El problema con el almacenamiento tradicional de claves
| Enfoque | Problema |
| :-------------------------------------------- | :--------------------------------------------------------------------------------- |
| Almacenar solo en el dispositivo | Perder el dispositivo = perder las claves = perder acceso al historial de mensajes |
| Almacenar en un respaldo ordinario en la nube | El proveedor podría acceder al material de la clave |
| Recordar una clave larga | Las personas no pueden memorizar de forma confiable claves de alta entropía |
### Cómo lo resuelve la copia de seguridad segura de claves
La copia de seguridad segura de claves combina **secret sharing** con **protección por código de acceso**:
1. Las claves privadas se **dividen en partes (shares)**
2. Los shares están en poder de **realms independientes** (servidores separados)
3. **Ningún realm individual** tiene suficiente información para reconstruir las claves por sí solo
4. La recuperación requiere tu **código de acceso** y la cooperación de **suficientes realms**
5. Los códigos de acceso incorrectos están **limitados por tasa** para ralentizar los intentos
```mermaid theme={null}
flowchart LR
A[Your Private Keys] --> B[Split into Shares]
B --> C[Realm 1 Share A]
B --> D[Realm 2 Share B]
B --> E[Realm 3 Share C]
subgraph Recovery
F[Your Passcode + Multiple Realms] --> G[Reconstruct Keys]
end
```
Obtienes recuperabilidad (nuevo dispositivo + código de acceso) sin que una sola parte tenga el secreto completo.
No configuras servidores de copia de seguridad de claves a mano para el flujo normal. El Chat XDK incluye el cliente de copia de seguridad; la configuración de realms proviene de la X API como **`juicebox_config`** en tu registro de clave pública (el campo lleva el nombre de Juicebox, la implementación subyacente). El almacenamiento del código de acceso por primera vez y el desbloqueo posterior son llamadas del Chat XDK—consulta [inicializar con claves existentes](/xchat/getting-started#2-initialize-the-chat-xdk-with-existing-keys) y [crear y registrar las claves](/xchat/getting-started#3-create-and-register-keys-first-time-setup) en Primeros pasos. Algunas apps (especialmente servidores y bots) usan un blob de claves exportado en lugar de la copia de seguridad segura de claves; protege ese material como una contraseña.
***
## Firmas explicadas
Cada mensaje de X Chat incluye una **firma digital** que respalda:
1. **Autenticidad** — fue producido con la clave privada de firma del remitente
2. **Integridad** — el contenido cifrado no fue modificado después de firmarse
### Cómo funcionan las firmas (conceptualmente)
| Acción | Clave utilizada | Resultado |
| :------------ | :----------------------------------- | :------------------------------------------------------- |
| **Firmar** | Clave privada de firma del remitente | Una firma vinculada exactamente a este mensaje cifrado |
| **Verificar** | Clave pública de firma del remitente | Confirma que la firma coincide con el mensaje y la clave |
Si algo cambia en el material firmado, la verificación falla. Solo alguien con la clave privada de firma puede producir una firma válida para esa clave.
### En tu app
El Chat XDK firma cuando cifras mensajes salientes y verifica cuando descifras mensajes entrantes contra el material de clave pública del remitente (obtenido de las APIs de claves públicas). La verificación es **obligatoria por defecto**: el SDK rechaza los eventos firmados no verificados a menos que desactives explícitamente la comprobación (no recomendado). Los detalles están en la referencia del [Chat XDK](/xchat/xchat-xdk).
### Cambios de estado firmados (firmas de acción)
Los mensajes no son el único material firmado. Cada llamada que cambia el estado de una conversación—agregar o rotar claves de conversación, crear un grupo, agregar miembros—debe llevar una o más **firmas de acción**: el remitente firma una carga que describe exactamente lo que hace el cambio (para un cambio de clave, esa carga incluye la nueva clave de conversación en sí), y la API rechaza la solicitud si las firmas están ausentes o mal formadas.
Como el servidor nunca posee la clave de conversación en texto plano, no puede comprobar criptográficamente la firma de un cambio de clave; valida que la descripción firmada y codificada del cambio coincida con la solicitud que recibió. La comprobación **criptográfica** ocurre en los extremos: el Chat XDK de cada destinatario verifica la firma contra la clave pública de firma del remitente cuando descifra el evento de cambio de clave. Los métodos `prepare` del Chat XDK producen estas firmas por ti—los group creates y los member adds devuelven **dos** (el cambio de clave más la acción de grupo), y ambos deben enviarse.
Las firmas están vinculadas al contenido del evento y son inmutables: un evento cuya firma no verifica nunca podrá volverse válido más adelante. Consulta [Solución de problemas](/xchat/troubleshooting) para saber cómo tratarlos.
***
## Propiedades de seguridad
### Contra qué protege X Chat
| Amenaza | Protección |
| :-------------------------------------------------------------------------------- | :-------------------------------------------------------------------- |
| **Que X lea el cuerpo de los mensajes** | El contenido se cifra antes de enviarse a X |
| **Espionaje de red** | Seguridad de transporte más contenido cifrado de extremo a extremo |
| **Manipulación de mensajes** | Las firmas detectan la modificación |
| **Suplantación trivial del remitente** | Las firmas válidas requieren la clave privada de firma del remitente |
| **Robo de claves en un único servidor (con copia de seguridad segura de claves)** | Los shares se dividen entre realms y se protegen con código de acceso |
### Contra qué **no** protege X Chat
| Amenaza | Por qué no |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------ |
| **Dispositivo comprometido** | El texto plano y las claves pueden quedar expuestos en un cliente desbloqueado |
| **Metadatos** | X puede saber quién envió un mensaje a quién y cuándo—no el texto del mensaje |
| **Forward secrecy** | El compromiso de las claves de identidad puede exponer las claves de conversación envueltas hacia esas claves |
| **Post-compromise security** | Rotar las claves no reescribe el historial |
***
## Glosario
| Término | Definición |
| :------------------------ | :-------------------------------------------------------------------------------------------------------------- |
| **Cifrado simétrico** | Misma clave cifra y descifra (se usa para mensajes y flujos de multimedia) |
| **Cifrado asimétrico** | Claves distintas para cifrar y descifrar (se usa para envolver claves de conversación) |
| **Clave pública** | Es seguro compartirla; se usa para cifrar *hacia* alguien o verificar sus firmas |
| **Clave privada** | Debe permanecer secreta; se usa para descifrar o firmar |
| **Par de claves** | Una clave pública y una clave privada vinculadas |
| **ECDH / ECIES** | Algoritmos usados al envolver claves de conversación hacia claves de identidad |
| **ECDSA** | Algoritmo de firma usado para la autoría de mensajes |
| **P-256** | Curva elíptica usada en X Chat (secp256r1) |
| **Clave de conversación** | Clave simétrica compartida por los participantes en una conversación (versionada a lo largo del tiempo) |
| **Secret sharing** | División de un secreto para que se necesiten varias piezas para reconstruirlo |
| **Realm** | Un servidor independiente de copia de seguridad segura de claves que mantiene un share de tu material de claves |
***
## Próximos pasos
Implementa claves, envío y recepción paso a paso
Métodos y tipos del SDK de cifrado
Descripción general del producto y arquitectura
Cómo se entregan los eventos cifrados
# Primeros pasos con la Chat API
Source: https://docs.x.com/es/xchat/getting-started
Tutorial paso a paso para crear mensajería X Chat cifrada de extremo a extremo con el Chat XDK en Python, TypeScript, Go, Rust, C# o Java.
Envía y recibe mensajes directos cifrados de extremo a extremo en X: configura claves, inicializa una conversación, envía un mensaje y descifra el tráfico entrante.
Las apps de X Chat usan dos piezas juntas:
| Componente | Función |
| :------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **[Chat XDK](/xchat/xchat-xdk)** | Cifrado, descifrado, firma y almacenamiento de claves privadas (copia de seguridad segura de claves o un blob de claves) |
| **X API** | Claves públicas, claves de conversación, mensajes y eventos—vía el XDK de [Python](/xdks/python/overview) o [TypeScript](/xdks/typescript/overview), o HTTPS con un token de acceso de usuario |
**Requisitos previos**
* [Cuenta de desarrollador](https://developer.x.com/en/portal/petition/essential/basic-info) y una app configurada para OAuth 2.0
* Token de acceso de usuario con `dm.read`, `dm.write`, `tweet.read` y `users.read`
***
## 1. Instala las dependencias
```bash theme={null}
pip install chatxdk xdk
```
El paquete de PyPI es `chatxdk`; impórtalo como `chat_xdk`. Requiere Python 3.10+.
```bash theme={null}
npm install @xdevplatform/chat-xdk @xdevplatform/xdk
npm install juicebox-sdk # optional peer dependency — required for setup()/unlock() secure key backup
```
El motor WASM compilado viene dentro de `@xdevplatform/chat-xdk`: no hay paso de build. Requiere Node.js 18+.
```toml theme={null}
[dependencies]
# chat-xdk-core is not yet on crates.io — use the git dependency
chat-xdk-core = { git = "https://github.com/xdevplatform/chat-xdk", tag = "v0.2.1" }
reqwest = { version = "0.12", features = ["blocking", "json"] }
serde_json = "1"
base64 = "0.22"
uuid = { version = "1", features = ["v4"] }
# Required until thrift 0.24 is released on crates.io
[patch.crates-io]
thrift = { git = "https://github.com/apache/thrift.git", rev = "deb36fa409849de45973b04ffc3ce49d277ca90a" }
```
```bash theme={null}
go get github.com/xdevplatform/chat-xdk/go/chatxdk
```
Se incluyen bibliotecas estáticas precompiladas (macOS arm64/amd64, Linux amd64 glibc/musl): necesitas un compilador de C, pero no Rust. Requiere Go 1.21+.
```bash theme={null}
dotnet add package XDevPlatform.ChatXdk
```
El paquete es autónomo: incluye las bibliotecas nativas para macOS (arm64, x64), Linux (x64) y Windows (x64). Requiere .NET 8+.
```xml theme={null}
com.xchatxdk0.2.1
```
Disponible en Maven Central. El jar incluye la biblioteca nativa para macOS (arm64, x64), Linux (x64) y Windows (x64): no necesitas configurar `jna.library.path`. Importa desde `com.x.chatxdk`. Requiere JDK 17+.
Crea un cliente de API con tu token de acceso OAuth 2.0 de **usuario**:
```python theme={null}
from xdk import Client
client = Client(access_token="YOUR_OAUTH2_USER_TOKEN")
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ accessToken: 'YOUR_OAUTH2_USER_TOKEN' });
```
```rust theme={null}
let access_token = std::env::var("X_ACCESS_TOKEN")?;
let http = reqwest::blocking::Client::new();
let auth = format!("Bearer {access_token}");
```
```go theme={null}
accessToken := os.Getenv("X_ACCESS_TOKEN")
httpClient := &http.Client{Timeout: 30 * time.Second}
```
```csharp theme={null}
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", Environment.GetEnvironmentVariable("X_ACCESS_TOKEN"));
```
```java theme={null}
String accessToken = System.getenv("X_ACCESS_TOKEN");
HttpClient http = HttpClient.newHttpClient();
```
***
## 2. Inicializa el Chat XDK con claves existentes
Este paso **carga claves que ya tienes**—úsalo cuando esta identidad ya completó la configuración inicial:
* **Copia de seguridad segura de claves:** construye el SDK con el `juicebox_config` de tu registro de clave pública y luego usa `unlock` con tu código de acceso para recuperar las claves privadas (por ejemplo, en un dispositivo nuevo).
* **Blob de claves:** `import_keys` con un blob que exportaste previamente mediante `export_keys`.
Después establece la versión de tu clave pública registrada (`public_key_version` en tu registro).
**¿Configuras por primera vez?** Construye el SDK de la misma forma pero omite `unlock`/`import_keys` y continúa en el [paso 3](#3-crea-y-registra-las-claves-configuracion-inicial) para crear, respaldar y registrar tus claves.
```python theme={null}
import json
from chat_xdk import Chat
resp = client.chat.get_user_public_keys(
"YOUR_USER_ID",
public_key_fields=[
"public_key_version", "public_key", "signing_public_key",
"identity_public_key_signature", "juicebox_config",
],
)
record = resp.data[0]
signing_key_version = str(record["public_key_version"])
chat = Chat(json.dumps(record["juicebox_config"]))
chat.unlock("YOUR_PASSCODE") # recovers keys stored by setup() during first-time setup (step 3)
chat.set_key_version(signing_key_version)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const resp = await client.chat.getUserPublicKeys('YOUR_USER_ID', {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key',
'identity_public_key_signature', 'juicebox_config',
],
});
const record = resp.data[0];
const signingKeyVersion = String(record.public_key_version);
const chat = await createChat({
juiceboxConfig: JSON.stringify(record.juicebox_config),
getAuthToken: async (realmId) => getRealmTokenFromYourBackend(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(signingKeyVersion);
```
```rust theme={null}
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use chat_xdk_core::ChatCore;
let mut chat = ChatCore::new();
let blob = B64.decode(std::env::var("PRIVATE_KEYS_B64")?)?;
let signing_key_version = std::env::var("SIGNING_KEY_VERSION").unwrap_or_else(|_| "1".into());
chat.import_keys(&blob)?;
chat.set_key_version(&signing_key_version);
```
```go theme={null}
import "github.com/xdevplatform/chat-xdk/go/chatxdk"
chat := chatxdk.New()
defer chat.Close()
blob, err := chatxdk.Base64ToBytes(os.Getenv("PRIVATE_KEYS_B64"))
if err != nil {
log.Fatal(err)
}
if err := chat.ImportKeys(blob); err != nil {
log.Fatal(err)
}
signingKeyVersion := os.Getenv("SIGNING_KEY_VERSION")
if signingKeyVersion == "" {
signingKeyVersion = "1"
}
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
using ChatXdk;
using var chat = new Chat();
var signingKeyVersion = Environment.GetEnvironmentVariable("SIGNING_KEY_VERSION") ?? "1";
chat.ImportKeys(Convert.FromBase64String(
Environment.GetEnvironmentVariable("PRIVATE_KEYS_B64")!));
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
import com.x.chatxdk.Chat;
String signingKeyVersion = Optional.ofNullable(System.getenv("SIGNING_KEY_VERSION")).orElse("1");
try (Chat chat = new Chat()) {
chat.importKeys(Base64.getDecoder().decode(System.getenv("PRIVATE_KEYS_B64")));
chat.setKeyVersion(signingKeyVersion);
}
```
Los ejemplos para servidor y bot suelen usar un **blob de claves** (`export_keys` / `import_keys`). Las apps cliente suelen usar la **copia de seguridad segura de claves** (`setup` / `unlock` con un código de acceso). Consulta la referencia del [Chat XDK](/xchat/xchat-xdk) para ambos caminos.
**¿Traes tus propias claves?** `import_keys` solo acepta el blob opaco que produce `export_keys` del Chat XDK—es una serialización privada y versionada del estado completo de las claves, no claves P-256 en bruto ni codificadas en PEM. No puedes construir este blob por tu cuenta: genera las claves con `generate_keypairs` ([paso 3](#3-crea-y-registra-las-claves-configuracion-inicial)), exporta el blob una vez y guárdalo codificado en base64. Los blobs hechos a mano o modificados fallan al importarse.
***
## 3. Crea y registra las claves (configuración inicial)
Omite este paso si cargaste claves existentes en el [paso 2](#2-inicializa-el-chat-xdk-con-claves-existentes). De lo contrario, la configuración inicial de una identidad nueva hace **tres cosas**:
1. **Crear los pares de claves** — `generate_keypairs` produce los pares de claves de identidad y de firma.
2. **Registrar las claves públicas** — envía el payload de registro con POST al endpoint add-public-key para que otros puedan cifrar hacia ti y verificar tus firmas.
3. **Guardar las claves privadas** — `setup` con un código de acceso las escribe en la copia de seguridad segura de claves (clientes), o `export_keys` devuelve un blob de claves para que lo guardes de forma segura (servidores y bots).
```python theme={null}
from xdk.chat.models import AddUserPublicKeyRequest
registration = chat.generate_keypairs()
pk = registration.public_key
client.chat.add_user_public_key(
"YOUR_USER_ID",
AddUserPublicKeyRequest(
public_key={
"identity_public_key_signature": pk.identity_public_key_signature,
"public_key": pk.public_key,
"public_key_fingerprint": pk.public_key_fingerprint,
"registration_method": pk.registration_method,
"signing_public_key": pk.signing_public_key,
"signing_public_key_signature": pk.signing_public_key_signature,
},
version=registration.version,
generate_version=registration.generate_version,
),
)
chat.setup("YOUR_PASSCODE")
chat.set_key_version(str(registration.version or signing_key_version))
```
```typescript theme={null}
const registration = chat.generateKeypairs();
const pk = registration.publicKey;
await client.chat.addUserPublicKey('YOUR_USER_ID', {
public_key: {
identity_public_key_signature: pk.identityPublicKeySignature,
public_key: pk.publicKey,
public_key_fingerprint: pk.publicKeyFingerprint,
registration_method: pk.registrationMethod,
signing_public_key: pk.signingPublicKey,
signing_public_key_signature: pk.signingPublicKeySignature,
},
version: registration.version,
generate_version: registration.generateVersion,
});
await chat.setup('YOUR_PASSCODE');
chat.setKeyVersion(String(registration.version ?? signingKeyVersion));
```
```rust theme={null}
let registration = chat.generate_keypairs()?;
let body = serde_json::to_value(®istration)?;
let resp = http
.post(format!("https://api.x.com/2/users/{user_id}/public_keys"))
.header("Authorization", &auth)
.json(&body)
.send()?;
if !resp.status().is_success() {
anyhow::bail!("register keys: {}", resp.text()?);
}
let _blob = chat.export_keys()?; // store securely
```
```go theme={null}
registration, err := chat.GenerateKeypairs()
if err != nil {
log.Fatal(err)
}
regJSON, _ := json.Marshal(registration)
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/users/"+userID+"/public_keys",
bytes.NewReader(regJSON))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
privateKeysB64, _ := chat.ExportKeys() // store securely
_ = privateKeysB64
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
var registration = chat.GenerateKeypairs();
var regJson = System.Text.Json.JsonSerializer.Serialize(registration);
using var content = new StringContent(regJson, Encoding.UTF8, "application/json");
using var regResp = await http.PostAsync(
$"https://api.x.com/2/users/{Uri.EscapeDataString(userId)}/public_keys", content);
regResp.EnsureSuccessStatusCode();
var blob = chat.ExportKeys(); // store securely
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
var registration = chat.generateKeypairs();
String regJson = new ObjectMapper().writeValueAsString(registration);
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/users/" + userId + "/public_keys"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(regJson))
.build();
HttpResponse regResp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (regResp.statusCode() >= 300) {
throw new RuntimeException("register keys: " + regResp.body());
}
byte[] blob = chat.exportKeys(); // store securely
chat.setKeyVersion(signingKeyVersion);
```
Usa un código de acceso fuerte para la copia de seguridad segura de claves. Perder el código de acceso o un blob de claves desprotegido puede impedir el descifrado de mensajes anteriores.
***
## 4. Configura las claves de conversación
Llama a **`prepare_conversation_key_change`** con tu ID de usuario, tu versión de clave de firma y la clave pública de identidad de cada participante. Una sola llamada genera una nueva clave de conversación, la cifra para cada participante y firma el cambio. Envía el resultado con POST al endpoint **add conversation keys** (`POST /2/chat/conversations/{id}/keys`)—el cuerpo necesita `conversation_key_version`, `conversation_participant_keys` (SDK `encrypted_key` → API `encrypted_conversation_key`) y **`action_signatures`** (obligatorio; la API rechaza la llamada sin ellas). Conserva la clave de conversación **en bruto** para enviar.
La respuesta devuelve el id canónico de la conversación (`data.conversation_id`—el par unido con guión para un 1:1, o el id con prefijo `g` para un grupo) y el `data.sequence_id` del cambio de clave. Usa ese id devuelto para solicitudes posteriores en lugar de reconstruirlo en el cliente. La misma llamada también **rota** las claves más adelante: pasa el id de conversación existente a `prepare_conversation_key_change` y haz POST con la versión de clave más reciente. Rota cuando sospeches que la clave de conversación quedó expuesta—la rotación protege **mensajes futuros** únicamente; los mensajes cifrados bajo versiones anteriores de la clave siguen siendo legibles para cualquiera que tenga esas versiones.
**Verifica las claves recuperadas antes de envolverlas.** `prepare_conversation_key_change` cifra la nueva clave de conversación hacia cualesquiera claves públicas que le pases. Comprueba primero cada registro obtenido con `verify_key_binding(identity, signing, signature)`—pasando los campos `public_key`, `signing_public_key` y `identity_public_key_signature` del registro obtenidos de la API de claves públicas—para que una clave de identidad sustituida no pueda recibir la clave de conversación.
```python theme={null}
def public_key_input(user_id: str) -> dict:
r = client.chat.get_user_public_keys(
user_id, public_key_fields=["public_key_version", "public_key"]
).data[0]
return {"user_id": user_id, "public_key": r["public_key"], "key_version": r["public_key_version"]}
prepared = chat.prepare_conversation_key_change(
"YOUR_USER_ID",
signing_key_version,
[public_key_input("YOUR_USER_ID"), public_key_input("RECIPIENT_USER_ID")],
# conversation_id=None for a new 1:1; pass the id to rotate later
)
resp = client.chat.add_conversation_keys(
"RECIPIENT_USER_ID",
{
"conversation_key_version": prepared["conversation_key_version"],
"conversation_participant_keys": [
{
"user_id": pk["user_id"],
"encrypted_conversation_key": pk["encrypted_key"],
"public_key_version": pk["public_key_version"],
}
for pk in prepared["participant_keys"]
],
"action_signatures": [
{
"message_id": sig["message_id"],
"encoded_message_event_detail": sig["encoded_message_event_detail"],
"message_event_signature": {
"signature": sig["signature"],
"public_key_version": sig["public_key_version"],
"signature_version": sig["signature_version"],
},
}
for sig in prepared["action_signatures"]
],
},
)
conversation_id = resp.data["conversation_id"] # canonical id for later requests
sequence_id = resp.data["sequence_id"]
conv_key = prepared["conversation_key"]
conv_key_version = prepared["conversation_key_version"]
```
```typescript theme={null}
async function publicKeyInput(userId: string) {
const r = (await client.chat.getUserPublicKeys(userId, {
publicKeyFields: ['public_key_version', 'public_key'],
})).data[0];
return { userId, publicKey: r.public_key, keyVersion: r.public_key_version };
}
// Omit conversationId for a new 1:1; pass the id to rotate later
const prepared = chat.prepareConversationKeyChange({
senderId: 'YOUR_USER_ID',
signingKeyVersion,
publicKeys: [
await publicKeyInput('YOUR_USER_ID'),
await publicKeyInput('RECIPIENT_USER_ID'),
],
});
const resp = await client.chat.addConversationKeys('RECIPIENT_USER_ID', {
conversation_key_version: prepared.conversationKeyVersion,
conversation_participant_keys: prepared.participantKeys.map((pk) => ({
user_id: pk.userId,
encrypted_conversation_key: pk.encryptedKey,
public_key_version: pk.publicKeyVersion,
})),
action_signatures: prepared.actionSignatures.map((sig) => ({
message_id: sig.messageId,
encoded_message_event_detail: sig.encodedMessageEventDetail,
message_event_signature: {
signature: sig.signature,
public_key_version: sig.publicKeyVersion,
signature_version: sig.signatureVersion,
},
})),
});
const conversationId = resp.data.conversation_id; // canonical id for later requests
const sequenceId = resp.data.sequence_id;
const convKey = prepared.conversationKey;
const convKeyVersion = prepared.conversationKeyVersion;
```
```rust theme={null}
// public_key_inputs: Vec from GET public keys
// (user_id, public_key, key_version ← public_key_version)
// new 1:1; set params.conversation_id = Some(id) to rotate later
let prepared = chat.prepare_conversation_key_change(
ConversationKeyChangeParams::new(&sender_id, &signing_key_version, public_key_inputs),
)?;
let participant_keys: Vec<_> = prepared
.participant_keys
.iter()
.map(|pk| {
serde_json::json!({
"user_id": pk.user_id,
"encrypted_conversation_key": pk.encrypted_key,
"public_key_version": pk.public_key_version,
})
})
.collect();
let action_signatures: Vec<_> = prepared
.action_signatures
.iter()
.map(|sig| {
serde_json::json!({
"message_id": sig.message_id,
"encoded_message_event_detail": sig.encoded_message_event_detail,
"message_event_signature": {
"signature": sig.signature,
"public_key_version": sig.public_key_version,
"signature_version": sig.signature_version,
},
})
})
.collect();
let body = serde_json::json!({
"conversation_key_version": prepared.conversation_key_version,
"conversation_participant_keys": participant_keys,
"action_signatures": action_signatures,
});
let resp: serde_json::Value = http
.post(format!("https://api.x.com/2/chat/conversations/{recipient_id}/keys"))
.header("Authorization", &auth)
.json(&body)
.send()?
.json()?;
// Canonical id for later requests
let conversation_id = resp["data"]["conversation_id"].as_str().unwrap().to_string();
// conversation_key is Option; encrypt_message wants owned bytes
let conv_key = prepared.conversation_key.expect("key present").to_bytes();
let conv_key_version = prepared.conversation_key_version;
```
```go theme={null}
// KeyVersion comes from the public_key_version field on each record
prepared, err := chat.PrepareConversationKeyChange(chatxdk.ConversationKeyChangeParams{
SenderID: myUserID,
SigningKeyVersion: signingKeyVersion,
PublicKeys: []chatxdk.PublicKeyInput{
{UserID: myUserID, PublicKey: myIdentityPubB64, KeyVersion: myKeyVersion},
{UserID: recipientID, PublicKey: theirIdentityPubB64, KeyVersion: theirKeyVersion},
},
// ConversationID empty for a new 1:1; pass the id to rotate later
})
var parts []map[string]string
for _, pk := range prepared.ParticipantKeys {
parts = append(parts, map[string]string{
"user_id": pk.UserID,
"encrypted_conversation_key": pk.EncryptedKey,
"public_key_version": pk.PublicKeyVersion,
})
}
var sigs []map[string]any
for _, sig := range prepared.ActionSignatures {
sigs = append(sigs, map[string]any{
"message_id": sig.MessageID,
"encoded_message_event_detail": sig.EncodedMessageEventDetail,
"message_event_signature": map[string]string{
"signature": sig.Signature,
"public_key_version": sig.PublicKeyVersion,
"signature_version": sig.SignatureVersion,
},
})
}
body, _ := json.Marshal(map[string]any{
"conversation_key_version": prepared.ConversationKeyVersion,
"conversation_participant_keys": parts,
"action_signatures": sigs,
})
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/chat/conversations/"+recipientID+"/keys",
bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
// Response data.conversation_id is the canonical id for later requests
// prepared.ConversationKey feeds EncryptMessage
_ = resp
```
```csharp theme={null}
// KeyVersion comes from the public_key_version field on each record
var prepared = chat.PrepareConversationKeyChange(new ConversationKeyChangeParams {
SenderId = myUserId,
SigningKeyVersion = signingKeyVersion,
PublicKeys = new[] {
new PublicKeyInput { UserId = myUserId, PublicKey = myPk, KeyVersion = myVer },
new PublicKeyInput { UserId = recipientId, PublicKey = theirPk, KeyVersion = theirVer },
},
}); // ConversationId null for a new 1:1; pass the id to rotate later
var keysBody = new {
conversation_key_version = prepared.ConversationKeyVersion,
conversation_participant_keys = prepared.ParticipantKeys.Select(pk => new {
user_id = pk.UserId,
encrypted_conversation_key = pk.EncryptedKey,
public_key_version = pk.PublicKeyVersion,
}),
action_signatures = prepared.ActionSignatures.Select(sig => new {
message_id = sig.MessageId,
encoded_message_event_detail = sig.EncodedMessageEventDetail,
message_event_signature = new {
signature = sig.Signature,
public_key_version = sig.PublicKeyVersion,
signature_version = sig.SignatureVersion,
},
}),
};
var json = System.Text.Json.JsonSerializer.Serialize(keysBody);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await http.PostAsync(
$"https://api.x.com/2/chat/conversations/{Uri.EscapeDataString(recipientId)}/keys",
content);
resp.EnsureSuccessStatusCode();
var data = System.Text.Json.JsonDocument.Parse(await resp.Content.ReadAsStringAsync())
.RootElement.GetProperty("data");
string conversationId = data.GetProperty("conversation_id").GetString()!; // canonical id
byte[] convKey = prepared.ConversationKey!;
string convKeyVersion = prepared.ConversationKeyVersion;
```
```java theme={null}
// keyVersion comes from the public_key_version field on each record
PublicKeyInput mine = new PublicKeyInput();
mine.userId = myUserId; mine.publicKey = myIdentityPubB64; mine.keyVersion = myKeyVersion;
PublicKeyInput theirs = new PublicKeyInput();
theirs.userId = recipientId; theirs.publicKey = theirIdentityPubB64; theirs.keyVersion = theirKeyVersion;
ConversationKeyChangeParams keyParams = new ConversationKeyChangeParams();
keyParams.senderId = myUserId;
keyParams.signingKeyVersion = signingKeyVersion;
keyParams.publicKeys = List.of(mine, theirs);
// keyParams.conversationId null for a new 1:1; set the id to rotate later
PreparedConversationChange prepared = chat.prepareConversationKeyChange(keyParams);
List
***
## 5. Envía un mensaje
Cifra con los bytes **en bruto** de la clave de conversación. En la solicitud de envío, mapea:
| Campo del Chat XDK | Campo del cuerpo de la solicitud |
| :---------------------------------------------------------------------------- | :-------------------------------- |
| `encrypted_content` / `encryptedContent` / `EncryptedContent` | `encoded_message_create_event` |
| `encoded_event_signature` / `encodedEventSignature` / `EncodedEventSignature` | `encoded_message_event_signature` |
| Tu id generado | `message_id` |
Usa un id de conversación con **guión** en la ruta URL cuando la API lo requiera (`:` → `-`). El propio SDK es flexible: `encrypt_message` y `encrypt_reply` aceptan el id en cualquier forma que tengas—`A:B` de eventos, `A-B` de listados o rutas URL (en cualquier orden), o solo el id de usuario del destinatario—y lo canonicalizan antes de firmar. Los ids de grupo (con prefijo `g`) pasan sin cambios.
```python theme={null}
import uuid
from xdk.chat.models import SendMessageRequest
message_id = str(uuid.uuid4())
payload = chat.encrypt_message(
message_id,
"YOUR_USER_ID",
"CONVERSATION_ID",
conv_key,
"Hello!",
conv_key_version,
signing_key_version,
)
client.chat.send_message(
"RECIPIENT_USER_ID",
SendMessageRequest(
message_id=message_id,
encoded_message_create_event=payload.encrypted_content,
encoded_message_event_signature=payload.encoded_event_signature,
),
)
```
```typescript theme={null}
import { randomUUID } from 'crypto';
const messageId = randomUUID();
const payload = chat.encryptMessage({
messageId,
senderId: 'YOUR_USER_ID',
conversationId: 'CONVERSATION_ID',
conversationKey: convKey,
text: 'Hello!',
conversationKeyVersion: convKeyVersion,
signingKeyVersion,
});
await client.chat.sendMessage('RECIPIENT_USER_ID', {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
});
```
```rust theme={null}
use chat_xdk_core::EncryptMessageParams;
let message_id = uuid::Uuid::new_v4().to_string();
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id,
&sender_id,
&conversation_id,
conv_key,
"Hello!",
&conv_key_version,
&signing_key_version,
))?;
let body = serde_json::json!({
"message_id": message_id,
"encoded_message_create_event": payload.encrypted_content,
"encoded_message_event_signature": payload.encoded_event_signature,
});
let path_id = conversation_id.replace(':', "-");
http.post(format!("https://api.x.com/2/chat/conversations/{path_id}/messages"))
.header("Authorization", &auth)
.json(&body)
.send()?;
```
```go theme={null}
messageID := uuid.NewString()
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID,
SenderID: senderID,
ConversationID: conversationID,
ConversationKey: convKey,
Text: "Hello!",
ConversationKeyVersion: convKeyVersion,
SigningKeyVersion: signingKeyVersion,
})
body, _ := json.Marshal(map[string]string{
"message_id": messageID,
"encoded_message_create_event": payload.EncryptedContent,
"encoded_message_event_signature": payload.EncodedEventSignature,
})
pathID := strings.ReplaceAll(conversationID, ":", "-")
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/chat/conversations/"+pathID+"/messages",
bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
_ = resp
```
```csharp theme={null}
var messageId = Guid.NewGuid().ToString();
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId,
SenderId = senderId,
ConversationId = conversationId,
ConversationKey = convKey,
Text = "Hello!",
ConversationKeyVersion = convKeyVersion,
SigningKeyVersion = signingKeyVersion,
});
var sendJson = System.Text.Json.JsonSerializer.Serialize(new Dictionary {
["message_id"] = messageId,
["encoded_message_create_event"] = payload.EncryptedContent,
["encoded_message_event_signature"] = payload.EncodedEventSignature,
});
using var content = new StringContent(sendJson, Encoding.UTF8, "application/json");
var pathId = conversationId.Replace(':', '-');
using var resp = await http.PostAsync(
$"https://api.x.com/2/chat/conversations/{Uri.EscapeDataString(pathId)}/messages",
content);
resp.EnsureSuccessStatusCode();
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = UUID.randomUUID().toString();
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = convKey;
params.text = "Hello!";
params.conversationKeyVersion = convKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
String pathId = conversationId.replace(':', '-');
String sendJson = new ObjectMapper().writeValueAsString(Map.of(
"message_id", params.messageId,
"encoded_message_create_event", payload.encryptedContent,
"encoded_message_event_signature", payload.encodedEventSignature));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/conversations/" + pathId + "/messages"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(sendJson))
.build();
http.send(req, HttpResponse.BodyHandlers.ofString());
```
***
## 6. Recibe y descifra
Usa [webhooks o el activity stream](/xchat/real-time-events) para el tráfico en vivo, o pagina los **events** de la conversación para el historial.
* Campos de payload en vivo: `encoded_event`, `conversation_key_change_event` opcional
* Historial: `GET /2/chat/conversations/{id}/events` — prefiere **`decrypt_events`** sobre todos los eventos más `meta.conversation_key_events`
* Pasa las claves públicas del remitente al descifrar para la verificación de la firma (mapea los campos de la API a `SigningKeyEntry`; consulta [Chat XDK](/xchat/xchat-xdk))
* JavaScript usa tipos de evento en camelCase (`message`); los demás lenguajes usan `"Message"` y campos snake\_case en JSON
```python theme={null}
conversation_keys = {} # conversation_id -> { version: key_bytes }
def signing_keys_for(user_id: str) -> list[dict]:
resp = client.chat.get_user_public_keys(
user_id,
public_key_fields=[
"public_key_version", "public_key", "signing_public_key", "identity_public_key_signature",
],
)
return [
{
"user_id": user_id,
"public_key_version": r["public_key_version"],
"public_key": r["signing_public_key"],
"identity_public_key": r["public_key"],
"identity_public_key_signature": r["identity_public_key_signature"],
}
for r in resp.data
]
def handle_payload(payload: dict):
cid = payload["conversation_id"]
if payload.get("conversation_key_change_event"):
conversation_keys[cid] = chat.extract_conversation_keys(
[payload["conversation_key_change_event"]]
)["keys"]
event = chat.decrypt_event(
payload["encoded_event"],
conversation_keys.get(cid, {}),
signing_keys_for(payload["sender_id"]),
)
if event.get("type") == "Message" and event.get("content", {}).get("content_type") == "Text":
print(event["sender_id"], event["content"]["text"], event.get("verified"))
```
```typescript theme={null}
const conversationKeys = new Map>();
async function signingKeysFor(userId: string) {
const resp = await client.chat.getUserPublicKeys(userId, {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key', 'identity_public_key_signature',
],
});
return resp.data.map((r: {
public_key_version: string;
public_key: string;
signing_public_key: string;
identity_public_key_signature: string;
}) => ({
userId,
publicKeyVersion: r.public_key_version,
publicKey: r.signing_public_key,
identityPublicKey: r.public_key,
identityPublicKeySignature: r.identity_public_key_signature,
}));
}
async function handlePayload(payload: {
conversation_id: string;
encoded_event: string;
sender_id: string;
conversation_key_change_event?: string;
}) {
const cid = payload.conversation_id;
if (payload.conversation_key_change_event) {
conversationKeys.set(
cid,
chat.extractConversationKeys([payload.conversation_key_change_event]).keys,
);
}
const event = chat.decryptEvent(
payload.encoded_event,
conversationKeys.get(cid) ?? {},
await signingKeysFor(payload.sender_id),
);
if (event.type === 'message' && event.content?.contentType === 'text') {
console.log(event.senderId, event.content.text, event.verified);
}
}
```
```rust theme={null}
// Build Vec from GET /2/users/{id}/public_keys
// (public_key_version, public_key, signing_public_key, identity_public_key_signature)
if let Some(kc) = key_change_b64.as_deref() {
let extracted = chat.extract_conversation_keys(&[kc]);
conv_keys.extend(extracted.keys);
}
let event = chat.decrypt_event(&encoded_event, &conv_keys, &sender_signing_keys)?;
```
```go theme={null}
if keyChange != "" {
extracted, _ := chat.ExtractConversationKeys([]string{keyChange})
for v, k := range extracted.Keys {
convKeys[v] = k
}
}
event, err := chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys)
if err == nil && event.Type == "Message" {
fmt.Println(event.AsMessage().Text())
}
```
```csharp theme={null}
if (!string.IsNullOrEmpty(keyChangeB64))
{
var extracted = chat.ExtractConversationKeys(new[] { keyChangeB64 });
foreach (var kv in extracted.Keys)
convKeys[kv.Key] = kv.Value;
}
var evt = chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys);
if (evt.GetProperty("type").GetString() == "Message")
Console.WriteLine(evt.GetProperty("content").GetProperty("text").GetString());
```
```java theme={null}
if (keyChangeB64 != null && !keyChangeB64.isEmpty()) {
var extracted = chat.extractConversationKeys(List.of(keyChangeB64));
convKeys.putAll(extracted.keys);
}
JsonNode evt = chat.decryptEvent(encodedEvent, convKeys, senderSigningKeys);
if ("Message".equals(evt.path("type").asText())) {
System.out.println(evt.path("content").path("text").asText());
}
```
Bots completos de poll-and-reply para todos los lenguajes: [chat-xdk/examples](https://github.com/xdevplatform/chat-xdk/tree/main/examples).
***
## Buenas prácticas
* Cachea las claves de conversación en bruto y las claves públicas de los remitentes; refréscalas ante fallos de verificación de firma
* Deduplica las entregas en vivo con `event_uuid`
* Pagina el historial de eventos hasta completar la paginación para no perder metadatos de cambio de clave
* No registres códigos de acceso, claves privadas ni el texto plano de mensajes en producción
* En apps web, mantén los tokens de OAuth (y la emisión de tokens de realm de la copia de seguridad de claves) en un servidor; procura mantener las claves privadas solo en el Chat XDK del cliente
***
## Próximos pasos
Métodos y tipos para todos los bindings de lenguaje
Imágenes y archivos adjuntos cifrados
Conversaciones y metadatos con múltiples participantes
Webhooks y entrega de actividad
# Conversaciones de grupo
Source: https://docs.x.com/es/xchat/groups
Crea conversaciones de grupo de X Chat con varios participantes, claves de conversación compartidas, títulos cifrados y mensajes firmados.
Los chats de grupo usan el **mismo modelo de cifrado** que un X Chat 1:1: una **clave de conversación** compartida por los miembros, envuelta hacia la **clave pública de identidad** de cada miembro, con mensajes cifrados y firmados por el Chat XDK. Lo que cambia es la **membresía**, **cómo creas la conversación** y, a menudo, los campos de **título/avatar cifrados** en la conversación.
Los flujos 1:1 están en [Primeros pasos](/xchat/getting-started). Los detalles de los endpoints están bajo **API reference → Conversations and messages**.
***
## En qué se diferencian los grupos de los 1:1
| Tema | 1:1 | Grupo |
| :----------------- | :-------------------------------------------------------------------- | :---------------------------------------------------------------------------------------- |
| Identidad | Frecuentemente direccionado por el id de usuario del par en las rutas | El id de conversación normalmente comienza con `g` |
| Crear | Claves + mensajería a un usuario | APIs de crear / inicializar grupo, luego claves |
| Participantes | Tú + un par | Muchos usuarios; la membresía puede cambiar |
| Metadatos | Mínimos | Nombre, avatar, etc. pueden ser **texto cifrado** (descifra con la clave de conversación) |
| Rotación de claves | Menos frecuente | Común cuando entra o sale gente |
La criptografía sigue siendo: **Chat XDK** para claves y cargas útiles; **X API** para crear el grupo, publicar los envoltorios de clave para los participantes, enviar mensajes y cargar eventos.
***
## Crea el grupo y establece las claves
1. Genera el id de grupo con `POST /2/chat/conversations/group/initialize` — el `data.conversation_id` de la respuesta es el id con prefijo `g` que usas en todo lo que sigue.
2. Carga la clave pública de identidad y el `public_key_version` de cada miembro (rutas `GET` de claves públicas bajo **Encryption keys**; [`GET /2/users/public_keys`](/x-api/users/get-public-keys-for-multiple-users) obtiene varios usuarios en una sola solicitud). Verifica cada registro con `verify_key_binding` antes de usarlo (consulta la advertencia en [Primeros pasos](/xchat/getting-started#4-set-up-conversation-keys)).
3. Ejecuta **`prepare_group_create`** una vez, con **todos** los miembros (incluyéndote a ti mismo), el id con prefijo `g` y las listas de ids de miembros/administradores. Una sola llamada genera la clave de conversación, la envuelve para cada miembro y firma la creación — devuelve **dos** firmas de acción (el cambio de clave de conversación y la creación del grupo).
4. `POST /2/chat/conversations/group` con los miembros/administradores del grupo, `conversation_key_version`, `conversation_participant_keys` (SDK **`encrypted_key`** → API **`encrypted_conversation_key`**) y **ambas** `action_signatures`. Los fallos de validación regresan como mensajes estables y legibles, por ejemplo `"Too many members: adding these members would exceed the allowed group size."` o `"Cannot add all members: one or more of the requested members cannot be added to this conversation."`.
5. Conserva la clave de conversación **en bruto** y la **versión** para cifrar/descifrar.
El `title` y el `avatar_url` que pasas a `prepare_group_create` se firman y se incrustan textualmente en el evento de creación del grupo, y el servidor los compara con la solicitud — así que los valores `group_name` / `group_avatar_url` en el cuerpo del POST deben ser **byte a byte idénticos** a lo que pasaste al SDK, o la llamada falla la validación de firma.
```python theme={null}
prepared = chat.prepare_group_create(
"YOUR_USER_ID", signing_key_version, member_public_keys,
group_id, # g-prefixed id from POST /2/chat/conversations/group/initialize
member_ids, admin_ids, title="Project team",
)
# POST /2/chat/conversations/group with group_members, group_admins,
# conversation_key_version, conversation_participant_keys, and BOTH
# entries of prepared["action_signatures"]
```
```typescript theme={null}
const prepared = chat.prepareGroupCreate({
senderId: myUserId, signingKeyVersion, publicKeys: memberPublicKeys,
conversationId: groupId, // g-prefixed id from POST /2/chat/conversations/group/initialize
memberIds, adminIds, title: 'Project team',
});
// prepared.actionSignatures has two entries — send both
```
```rust theme={null}
let mut params = GroupCreateParams::new(
&sender_id, &signing_key_version, member_public_keys,
&group_id, member_ids, admin_ids,
);
params.title = Some("Project team".into());
let prepared = chat.prepare_group_create(params)?;
// prepared.action_signatures has two entries — send both
```
```go theme={null}
prepared, err := chat.PrepareGroupCreate(chatxdk.GroupCreateParams{
SenderID: myUserID, SigningKeyVersion: signingKeyVersion,
PublicKeys: memberPublicKeys, ConversationID: groupID,
MemberIDs: memberIDs, AdminIDs: adminIDs, Title: "Project team",
})
// prepared.ActionSignatures has two entries — send both
_ = prepared
_ = err
```
```csharp theme={null}
var prepared = chat.PrepareGroupCreate(new GroupCreateParams {
SenderId = myUserId, SigningKeyVersion = signingKeyVersion,
PublicKeys = memberPublicKeys, ConversationId = groupId,
MemberIds = memberIds, AdminIds = adminIds, Title = "Project team",
});
// prepared.ActionSignatures has two entries — send both
```
```java theme={null}
GroupCreateParams params = new GroupCreateParams();
params.senderId = myUserId;
params.signingKeyVersion = signingKeyVersion;
params.publicKeys = memberPublicKeys;
params.conversationId = groupId;
params.memberIds = memberIds;
params.adminIds = adminIds;
params.title = "Project team";
PreparedConversationChange prepared = chat.prepareGroupCreate(params);
// prepared.actionSignatures has two entries — send both
```
El mapeo del cuerpo para las claves de participantes y las firmas de acción (`message_id`, `encoded_message_event_detail`, `message_event_signature` anidado) es el mismo que el POST de claves en [Primeros pasos — claves de conversación](/xchat/getting-started#4-set-up-conversation-keys).
Cuando cambia la membresía, llama a **`prepare_group_members_change`** con los nuevos ids de miembros más el roster actual (miembros, administradores, miembros pendientes y el título/avatar/TTL actual si está configurado). Rota la clave de conversación y, al igual que la creación de grupo, devuelve **dos** firmas de acción — envía todo con POST a **add members** (`POST /2/chat/conversations/{id}/members`). Después espera tráfico de **cambio de clave**: trátalo como la [rotación de claves en Primeros pasos](/xchat/getting-started#6-receive-and-decrypt) (`extract_conversation_keys` / `decrypt_events`, luego cifra con la versión más reciente).
Como `prepare_group_members_change` genera una clave de conversación **nueva** envuelta solo para el roster que pasas, los nuevos miembros reciben la nueva versión de la clave y no pueden descifrar los mensajes enviados bajo versiones anteriores. Lo inverso no es cierto: la rotación nunca revoca el acceso a **versiones anteriores** — cualquiera que ya tenga una clave vieja puede seguir leyendo los mensajes cifrados con ella. Si sospechas que una clave de conversación fue expuesta, rota con `prepare_conversation_key_change`; esto protege únicamente los mensajes futuros.
***
## Metadatos de grupo cifrados
Algunos campos de conversación (por ejemplo el **nombre** para mostrar o la **URL del avatar**) pueden llegar **cifrados** con la clave de conversación. Eso **no** es `encrypt_message`; es el par genérico **`encrypt` / `decrypt`** del Chat XDK (cadena UTF-8 de entrada, texto cifrado base64 de salida, con la clave de conversación **en bruto**).
Si un campo dado se almacena cifrado lo decide el cliente que lo escribe: `prepare_group_create` firma y envía el título exactamente como se lo proporcionas (la clave de conversación no existe hasta que esa llamada la genera, así que un título en el momento de la creación no puede cifrarse con ella). Cuando lees una conversación cuyos campos son texto cifrado, descífralos con `decrypt` y la versión de clave que estaba activa cuando el campo se escribió.
```python theme={null}
# Decrypt a field from the conversation object (name may vary by API shape)
group_name = chat.decrypt(conversation["group_name"], raw_conv_key)
# Encrypt before update if your API accepts ciphertext metadata
encrypted_name = chat.encrypt("Project team", raw_conv_key)
```
```typescript theme={null}
const groupName = chat.decrypt(conversation.groupName, rawConvKey);
const encryptedName = chat.encrypt('Project team', rawConvKey);
```
```rust theme={null}
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let group_name = chat.decrypt(&conversation_group_name_b64, &conv_key)?;
let encrypted_name = chat.encrypt("Project team", &conv_key)?;
```
```go theme={null}
groupName, err := chat.Decrypt(conversationGroupNameB64, rawConvKey)
encryptedName, err := chat.Encrypt("Project team", rawConvKey)
_ = groupName
_ = encryptedName
```
```csharp theme={null}
string groupName = chat.Decrypt(conversationGroupNameB64, rawConvKey);
string encryptedName = chat.Encrypt("Project team", rawConvKey);
```
```java theme={null}
String groupName = chat.decrypt(conversationGroupNameB64, rawConvKey);
String encryptedName = chat.encrypt("Project team", rawConvKey);
```
Usa la versión **actual** de la clave de conversación que aplica a esos metadatos. Si las claves rotaron, descifra con la versión que estaba activa cuando el campo se escribió (o sigue las reglas del producto si los metadatos siempre se reescriben en la rotación).
***
## Mensajes y eventos
Enviar y recibir en un grupo es lo mismo que en un 1:1 una vez que tienes la clave de conversación en bruto:
* **Enviar:** `encrypt_message` → API send-message ([Primeros pasos](/xchat/getting-started#5-send-a-message))
* **Recibir:** API de events o [entrega en tiempo real](/xchat/real-time-events) → `decrypt_event` / `decrypt_events`
* **Multimedia:** [Multimedia](/xchat/media) con el id de conversación del grupo
Siempre cifra con la versión **más reciente** de la clave después de una rotación impulsada por cambios de membresía.
***
## Lista de verificación
1. Genera el id con prefijo `g` con `POST /2/chat/conversations/group/initialize`
2. `prepare_group_create` con **cada** miembro; envía con POST los envoltorios de clave de participantes y **ambas** firmas de acción a `POST /2/chat/conversations/group`
3. Cachea la clave en bruto + versión; actualiza en eventos de cambio de clave
4. En cambios de membresía, `prepare_group_members_change` (dos firmas) → `POST /2/chat/conversations/{id}/members`
5. Descifra los metadatos del grupo con `decrypt` cuando los campos sean texto cifrado
6. Envía/recibe con los mismos patrones que en 1:1
# Introducción a la Chat API
Source: https://docs.x.com/es/xchat/introduction
Descripción general de la Chat API de X para enviar y recibir mensajes directos cifrados de extremo a extremo y firmados con el Chat XDK.
La **Chat API** te permite enviar y recibir mensajes directos **cifrados de extremo a extremo** en X. Los cuerpos de los mensajes se cifran en el cliente; X enruta el texto cifrado y no puede leer el contenido en texto plano. Los mensajes también se **firman** para que los destinatarios puedan verificar al remitente.
***
## Lo que necesitas en tu aplicación
| Pieza | Responsabilidad |
| :------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **[Chat XDK](/xchat/xchat-xdk)** | Generar claves, cifrar/descifrar, firmar/verificar y, opcionalmente, copia de seguridad segura de claves protegida con código de acceso (Python, JS, Rust, Go, C#, Java) |
| **Acceso a la X API** | Claves públicas, claves de conversación, mensajes, eventos y multimedia—mediante el **[XDK](/xdks/python/overview)** (Python/TypeScript) o HTTPS |
| **Entrega** | [Webhooks o activity stream](/xchat/real-time-events) para eventos en vivo; events API para historial |
Sigue **[Primeros pasos](/xchat/getting-started)** para una implementación completa. Si solo quieres conceptos, consulta el **[Manual básico de criptografía](/xchat/cryptography-primer)**.
***
## Cómo funciona el cifrado (resumen)
1. Crea pares de claves de **identidad** y **firma**; guarda las claves privadas de forma segura (copia de seguridad segura de claves o un blob protegido).
2. **Publica las claves públicas** para que otros puedan intercambiar claves de conversación contigo y verificar firmas.
3. Comparte una **clave de conversación** publicando copias cifradas para cada participante.
4. **Cifra y firma** los mensajes salientes; envía a X solo el texto cifrado.
5. **Recibe** texto cifrado a través de webhooks, stream o historial de eventos.
6. **Verifica y descifra** con el Chat XDK.
***
## Endpoints útiles
Agrupados bajo **API reference** en la barra lateral, incluyen:
* Claves públicas — registrar y consultar
* Conversaciones y mensajes — listar/obtener conversaciones, agregar/rotar claves, eventos, enviar, escribiendo, leído, membresía de grupo
* Multimedia — subir y descargar adjuntos cifrados ([guía](/xchat/media))
***
## Notas de autenticación
Usa **OAuth 2.0 user context** con los scopes relacionados a DM (`dm.read`, `dm.write`, además de `users.read` / `tweet.read` según sea necesario; `media.write` para subidas). La actividad de X Chat de un usuario requiere la autorización de ese usuario. La configuración de la copia de seguridad segura de claves se devuelve en **tu** registro de clave pública (campo `juicebox_config`)—consulta Primeros pasos.
***
## Próximos pasos
1. [Manual básico de criptografía](/xchat/cryptography-primer) — antecedentes opcionales sobre conceptos de E2EE
2. [Primeros pasos](/xchat/getting-started) — implementa claves, envío y recepción
3. [Chat XDK](/xchat/xchat-xdk) — referencia del SDK de cifrado
4. [Eventos en tiempo real](/xchat/real-time-events), [Multimedia](/xchat/media) o [Solución de problemas](/xchat/troubleshooting) cuando necesites esos temas
# Multimedia y adjuntos
Source: https://docs.x.com/es/xchat/media
Cifra, sube, envía, descarga y descifra imágenes y archivos adjuntos en X Chat con el Chat XDK, cifrado de streams y endpoints de subida.
Las imágenes y otros archivos usan la **misma clave de conversación** que el texto. Cifra los bytes con el Chat XDK (`encrypt_stream` / `decrypt_stream`), sube mediante las rutas **`/2/chat/media/upload`** (barra lateral **API reference → Media**) y luego adjunta **`media_hash_key`** en `encrypt_message`.
Incluye **`media.write`** con tus scopes de DM al subir. Usa ids de conversación con guión en las rutas (`:` → `-`). Prefiere el MIME/dimensiones desde los bytes **descifrados**.
Este camino **no** es el modelo de multimedia de Posts (`expansions=attachments.media_keys`, `media.fields=variants`, etc.). Esos parámetros aplican a **Posts**; los blobs E2EE de X Chat se direccionan por **`media_hash_key`** y por la descarga de multimedia de X Chat.
```mermaid theme={null}
flowchart LR
A[Plain bytes] --> B[encrypt_stream]
B --> C[Upload 3 steps]
C --> D[media_hash_key]
D --> E[encrypt_message + send]
F[GET media] --> G[decrypt_stream]
G --> H[Plain bytes]
```
***
## Cifrar
```python theme={null}
from chat_xdk import detect_mime_type, detect_image_dimensions
with open("photo.jpg", "rb") as f:
plaintext = f.read()
mime = detect_mime_type(plaintext)
dims = detect_image_dimensions(plaintext)
width, height = dims if dims else (0, 0)
encrypted_blob = chat.encrypt_stream(plaintext, raw_conv_key)
```
```typescript theme={null}
import { detectMimeType, detectImageDimensions } from '@xdevplatform/chat-xdk';
import { readFile } from 'fs/promises';
const plaintext = await readFile('photo.jpg');
const mime = detectMimeType(plaintext);
const dims = detectImageDimensions(plaintext);
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;
const encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
```
```rust theme={null}
use chat_xdk_core::{detect_image_dimensions, detect_mime_type};
let plaintext = std::fs::read("photo.jpg")?;
let _mime = detect_mime_type(&plaintext);
let dims = detect_image_dimensions(&plaintext);
let (width, height) = dims.map(|d| (d.width as i64, d.height as i64)).unwrap_or((0, 0));
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let encrypted_blob = chat.encrypt_stream(&plaintext, &conv_key)?;
```
```go theme={null}
plaintext, err := os.ReadFile("photo.jpg")
mime, _ := chatxdk.DetectMimeType(plaintext)
dims, _ := chatxdk.DetectImageDimensions(plaintext)
_ = mime
encrypted, err := chat.EncryptStream(plaintext, rawConvKey)
_ = dims
_ = encrypted
```
```csharp theme={null}
using ChatXdk;
byte[] plaintext = await File.ReadAllBytesAsync("photo.jpg");
string? mime = ChatXdkUtilities.DetectMimeType(plaintext);
var dims = ChatXdkUtilities.DetectImageDimensions(plaintext);
int width = (int)(dims?.Width ?? 0);
int height = (int)(dims?.Height ?? 0);
byte[] encryptedBlob = chat.EncryptStream(plaintext, rawConvKey);
```
```java theme={null}
import com.x.chatxdk.ChatXdkUtilities;
import com.x.chatxdk.Types.ImageDimensions;
byte[] plaintext = Files.readAllBytes(Path.of("photo.jpg"));
String mime = ChatXdkUtilities.detectMimeType(plaintext);
ImageDimensions dims = ChatXdkUtilities.detectImageDimensions(plaintext);
int width = dims != null ? (int) dims.width : 0;
int height = dims != null ? (int) dims.height : 0;
byte[] encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
```
`encrypt_stream` / `decrypt_stream` procesan la carga completa en memoria. Para archivos grandes, `stream_encryptor()` / `stream_decryptor()` devuelven objetos incrementales (`StreamEncryptor` / `StreamDecryptor`): aliméntalos por fragmentos con `push` y luego llama a `finish` una vez—`finish` arroja error si el stream se truncó.
***
## Subir
| Paso | Método | Ruta |
| :---------- | :----- | :----------------------------------- |
| Inicializar | `POST` | `/2/chat/media/upload/initialize` |
| Añadir | `POST` | `/2/chat/media/upload/{id}/append` |
| Finalizar | `POST` | `/2/chat/media/upload/{id}/finalize` |
Usa los cuerpos de solicitud en las páginas de OpenAPI bajo **API reference → Media**. Prefiere el tamaño del blob **cifrado** donde se requiera el tamaño. Finalizar produce **`media_hash_key`** para adjuntos y descarga. Reintenta `5xx` transitorios con backoff. Python/TypeScript pueden usar el XDK cuando existan helpers de multimedia; en caso contrario, haz POST con un Bearer token en cualquier lenguaje.
***
## Enviar con un adjunto
Cifra con un adjunto de multimedia y luego haz POST del cuerpo send-message (mismo mapeo de campos que en [Primeros pasos](/xchat/getting-started#5-send-a-message)).
```python theme={null}
import uuid
from xdk.chat.models import SendMessageRequest
message_id = str(uuid.uuid4())
payload = chat.encrypt_message(
message_id,
sender_id,
conversation_id,
raw_conv_key,
caption or "",
conversation_key_version,
signing_key_version,
attachments=[{
"attachment_type": "media",
"media_hash_key": media_hash_key,
"width": width,
"height": height,
"filesize_bytes": len(plaintext),
"filename": "photo.jpg",
}],
)
client.chat.send_message(
conversation_id.replace(":", "-"),
SendMessageRequest(
message_id=message_id,
encoded_message_create_event=payload.encrypted_content,
encoded_message_event_signature=payload.encoded_event_signature,
),
)
```
```typescript theme={null}
const messageId = crypto.randomUUID();
const payload = chat.encryptMessage({
messageId,
senderId,
conversationId,
conversationKey: rawConvKey,
text: caption || '',
conversationKeyVersion,
signingKeyVersion,
attachments: [{
attachmentType: 'media',
mediaHashKey: mediaHashKey,
width,
height,
filesizeBytes: plaintext.byteLength,
filename: 'photo.jpg',
}],
});
await client.chat.sendMessage(conversationId.replace(/:/g, '-'), {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
});
```
```rust theme={null}
// Set attachments on EncryptMessageParams per chat_xdk_core AttachmentDescriptor::Media
let payload = chat.encrypt_message(params_with_media_attachment)?;
let body = serde_json::json!({
"message_id": message_id,
"encoded_message_create_event": payload.encrypted_content,
"encoded_message_event_signature": payload.encoded_event_signature,
});
let path_id = conversation_id.replace(':', "-");
http.post(format!("https://api.x.com/2/chat/conversations/{path_id}/messages"))
.header("Authorization", &auth)
.json(&body)
.send()?;
```
```go theme={null}
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawConvKey, Text: caption,
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
Attachments: []chatxdk.AttachmentDescriptor{{
AttachmentType: "media",
MediaHashKey: mediaHashKey,
Width: width,
Height: height,
FilesizeBytes: int64(len(plaintext)),
Filename: "photo.jpg",
}},
})
// POST payload.EncryptedContent / EncodedEventSignature to /2/chat/conversations/{id}/messages
```
```csharp theme={null}
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId,
SenderId = senderId,
ConversationId = conversationId,
ConversationKey = rawConvKey,
Text = caption ?? "",
ConversationKeyVersion = conversationKeyVersion,
SigningKeyVersion = signingKeyVersion,
// Attachments = media descriptor with MediaHashKey, Width, Height,
// FilesizeBytes, and Filename (as in the Go tab above)
});
// POST EncryptedContent / EncodedEventSignature as for text messages
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawConvKey;
params.text = caption != null ? caption : "";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
// params.attachments — media type with mediaHashKey, width, height, filename
SendPayload payload = chat.encryptMessage(params);
// POST to /2/chat/conversations/{id}/messages
```
***
## Descargar y descifrar
Ruta: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/download-chat-media). El cuerpo de la respuesta es texto cifrado. En los mensajes entrantes, lee `media_hash_key` desde los adjuntos descifrados / `media_hashes`.
**Elige la clave por la versión de clave del evento.** Cada evento de mensaje descifrado lleva la `keyVersion` (JS; `key_version` en los demás bindings) con la que se cifró su contenido. Descifra un adjunto con la clave de conversación de **esa** versión—`conversationKeys.keys[event.keyVersion]`—no la más reciente. Después de una rotación de clave (por ejemplo al agregar un miembro), la clave más reciente no puede descifrar multimedia adjunta a mensajes anteriores.
```python theme={null}
keys = result["conversation_keys"]["keys"]
key_for_media = keys[event["key_version"]] # not the latest version
plaintext = chat.decrypt_stream(encrypted_blob, key_for_media)
```
```typescript theme={null}
const keys = result.conversationKeys.keys;
const keyForMedia = keys[event.keyVersion]; // not the latest version
const plaintext = chat.decryptStream(encryptedBlob, keyForMedia);
```
```python theme={null}
import requests
from chat_xdk import detect_mime_type
api_id = conversation_id.replace(":", "-")
url = f"https://api.x.com/2/chat/media/{api_id}/{media_hash_key}"
r = requests.get(url, headers={"Authorization": f"Bearer {access_token}"})
r.raise_for_status()
plaintext = chat.decrypt_stream(r.content, raw_conv_key)
mime = detect_mime_type(plaintext) or "application/octet-stream"
```
```typescript theme={null}
import { detectMimeType } from '@xdevplatform/chat-xdk';
const apiId = conversationId.replace(/:/g, '-');
const res = await fetch(
`https://api.x.com/2/chat/media/${apiId}/${mediaHashKey}`,
{ headers: { Authorization: `Bearer ${accessToken}` } },
);
const encryptedBlob = new Uint8Array(await res.arrayBuffer());
const plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
const mime = detectMimeType(plaintext) ?? 'application/octet-stream';
```
```rust theme={null}
let api_id = conversation_id.replace(':', "-");
let encrypted_blob = http
.get(format!("https://api.x.com/2/chat/media/{api_id}/{media_hash_key}"))
.header("Authorization", &auth)
.send()?
.bytes()?;
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let plaintext = chat.decrypt_stream(&encrypted_blob, &conv_key)?;
```
```go theme={null}
url := fmt.Sprintf("https://api.x.com/2/chat/media/%s/%s",
strings.ReplaceAll(conversationID, ":", "-"), mediaHashKey)
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := http.DefaultClient.Do(req)
// read body into []byte → chat.DecryptStream(encryptedBlob, rawConvKey)
_ = resp
_ = err
```
```csharp theme={null}
var apiId = conversationId.Replace(':', '-');
byte[] encryptedBlob = await http.GetByteArrayAsync(
$"https://api.x.com/2/chat/media/{apiId}/{mediaHashKey}");
byte[] plaintext = chat.DecryptStream(encryptedBlob, rawConvKey);
string? mime = ChatXdkUtilities.DetectMimeType(plaintext);
```
```java theme={null}
String apiId = conversationId.replace(':', '-');
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/media/" + apiId + "/" + mediaHashKey))
.header("Authorization", "Bearer " + accessToken)
.GET()
.build();
byte[] encryptedBlob = http.send(req, HttpResponse.BodyHandlers.ofByteArray()).body();
byte[] plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
String mime = ChatXdkUtilities.detectMimeType(plaintext);
```
***
## Consejos
* Usa la misma **versión de clave de conversación** que cuando se cifró la multimedia
* No registres multimedia en texto plano ni claves en bruto
* Detecta el MIME **después** de descifrar
* Clientes web: cifra/descifra en el cliente cuando sea posible; mantén los tokens de OAuth en tu servidor
Los esquemas completos de solicitud y respuesta para cada ruta de multimedia están bajo **API reference → Media** en la barra lateral (inicializar subida, añadir chunk, finalizar subida y descargar multimedia).
# Eventos de X Chat en tiempo real
Source: https://docs.x.com/es/xchat/real-time-events
Recibe eventos chat.received, chat.sent y otras actividades cifradas de X Chat mediante webhooks o activity stream y descifra con el Chat XDK.
X entrega **`chat.received`**, **`chat.sent`** y actividad relacionada de X Chat con **texto cifrado** en el payload. Descifra con el [Chat XDK](/xchat/xchat-xdk).
| Capa | Función |
| :----------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
| **X Activity API** | `GET /2/activity/stream`; `POST` / `GET` / `PUT` / `DELETE` `/2/activity/subscriptions` (consulta la seguridad de OpenAPI por operación) |
| **Webhooks** | Rutas opcionales `POST` / `GET` `/2/webhooks` y `PUT` / `DELETE` `/2/webhooks/{webhook_id}` si terminas en tu propia URL HTTPS |
| **Chat XDK** | `extract_conversation_keys`, `decrypt_event` / `decrypt_events` |
Los tipos de evento privados de X Chat requieren autorización del usuario que monitoreas. Los adjuntos de archivos cifrados de X Chat usan **`media_hash_key`** y la descarga de multimedia de X Chat—no `expansions=attachments.media_keys` / `media.fields=variants` de la Post API.
***
## Tipos de evento
| Evento | Cuándo |
| :----------------------- | :---------------------------------------------------------- |
| `chat.received` | El usuario suscrito recibe un DM cifrado |
| `chat.sent` | El usuario suscrito envía un DM cifrado |
| `chat.conversation_join` | El usuario suscrito se une a un grupo (cuando se le ofrece) |
***
## 1. Elige el modo de entrega
**Activity stream (a menudo lo más simple para bots):** `GET /2/activity/stream` con un Bearer token de app (opcional `backfill_minutes`, `start_time`, `end_time` según OpenAPI). Filtra en el cliente por `chat.received` / `chat.sent`.
**Suscripciones de Activity:** gestiona suscripciones duraderas con:
* `POST /2/activity/subscriptions` — crear
* `GET /2/activity/subscriptions` — listar (paginado)
* `PUT /2/activity/subscriptions/{subscription_id}` — actualizar
* `DELETE /2/activity/subscriptions/{subscription_id}` o `DELETE /2/activity/subscriptions?ids=` — eliminar
Los cuerpos de solicitud y los scopes requeridos se definen en la operación OpenAPI de cada ruta. Crear una suscripción de la X Activity API (XAA) requiere **autorización de contexto de usuario** (OAuth 2.0 de contexto de usuario con los scopes correspondientes, como `dm.read` para eventos de chat) para el usuario cuya actividad monitoreas.
**Webhooks:** si terminas los eventos en tu endpoint HTTPS, registra un webhook con `POST /2/webhooks`, pasa los challenges CRC y luego crea tus suscripciones de actividad con `POST /2/activity/subscriptions`, haciendo referencia a tu `webhook_id` (consulta las operaciones Webhooks y Activity en OpenAPI). El XDK de Python/TypeScript puede exponer helpers para webhooks y actividad cuando tu versión del SDK los incluya.
```python theme={null}
from xdk import Client
# Stream (app token) — exact helper names depend on your XDK version
stream_client = Client(bearer_token="YOUR_BEARER_TOKEN")
# for event in stream_client.activity.stream():
# handle_payload(event) # see "Decrypt with the Chat XDK" below
# Or create a subscription — requires user-context auth for the monitored user
client = Client(access_token="YOUR_OAUTH2_USER_TOKEN")
client.activity.create_subscription({
"event_type": "chat.received",
"filter": {"user_id": "USER_ID_TO_MONITOR"},
})
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
// Creating a subscription requires user-context auth for the monitored user
const client = new Client({ accessToken: 'YOUR_OAUTH2_USER_TOKEN' });
await client.activity.createSubscription({
event_type: 'chat.received',
filter: { user_id: 'USER_ID_TO_MONITOR' },
});
// Stream: client.activity.stream() when available in your SDK version
```
Suscríbete también a `chat.sent` si necesitas copias salientes. Otros lenguajes: llama directamente a las mismas rutas HTTPS `/2/activity/*` (token de contexto de usuario para crear suscripciones, Bearer token de app para el stream).
***
## 2. CRC (solo webhooks)
Si usas webhooks, responde a los Challenge-Response Checks (GET `crc_token`) con HMAC-SHA256 del token usando tu consumer secret, en la forma JSON que espera tu producto de webhooks (normalmente `sha256=`).
***
## 3. Descifra con el Chat XDK
Campos en vivo: **`payload.encoded_event`**, opcional **`payload.conversation_key_change_event`**. Deduplica por **`event_uuid`**.
JavaScript usa tipos de evento en camelCase (`message`); los demás bindings usan `"Message"` y campos en snake\_case.
```python theme={null}
from chat_xdk import Chat
chat = Chat(JUICEBOX_CONFIG_JSON)
chat.unlock("YOUR_PASSCODE")
chat.set_key_version(SIGNING_KEY_VERSION)
conversation_keys = {}
def signing_keys(user_id: str):
resp = api_client.chat.get_user_public_keys(
user_id,
public_key_fields=[
"public_key_version", "public_key", "signing_public_key", "identity_public_key_signature",
],
)
return [
{
"user_id": user_id,
"public_key_version": r["public_key_version"],
"public_key": r["signing_public_key"],
"identity_public_key": r["public_key"],
"identity_public_key_signature": r["identity_public_key_signature"],
}
for r in resp.data
]
data = body.get("data") or {}
if data.get("event_type") in ("chat.received", "chat.sent"):
p = data.get("payload") or {}
cid = p.get("conversation_id")
if p.get("conversation_key_change_event"):
conversation_keys[cid] = chat.extract_conversation_keys(
[p["conversation_key_change_event"]]
)["keys"]
ev = chat.decrypt_event(
p["encoded_event"],
conversation_keys.get(cid, {}),
signing_keys(p["sender_id"]),
)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: JUICEBOX_CONFIG_JSON,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(SIGNING_KEY_VERSION);
const conversationKeys = new Map>();
async function signingKeys(userId: string) {
const resp = await apiClient.chat.getUserPublicKeys(userId, {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key', 'identity_public_key_signature',
],
});
return resp.data.map((r: any) => ({
userId,
publicKeyVersion: r.public_key_version,
publicKey: r.signing_public_key,
identityPublicKey: r.public_key,
identityPublicKeySignature: r.identity_public_key_signature,
}));
}
const data = body?.data ?? {};
if (data.event_type === 'chat.received' || data.event_type === 'chat.sent') {
const p = data.payload ?? {};
const cid = p.conversation_id as string;
if (p.conversation_key_change_event) {
conversationKeys.set(
cid,
chat.extractConversationKeys([p.conversation_key_change_event]).keys,
);
}
const ev = chat.decryptEvent(
p.encoded_event,
conversationKeys.get(cid) ?? {},
await signingKeys(p.sender_id),
);
}
```
```rust theme={null}
// chat: ChatCore or Chat, already unlocked / keys imported
if let Some(kc) = key_change.as_deref() {
let extracted = chat.extract_conversation_keys(&[kc]);
conv_keys.extend(extracted.keys);
}
// sender_signing_keys from GET /2/users/{sender_id}/public_keys
let event = chat.decrypt_event(&encoded_event, &conv_keys, &sender_signing_keys)?;
```
```go theme={null}
if keyChange != "" {
extracted, _ := chat.ExtractConversationKeys([]string{keyChange})
for v, k := range extracted.Keys {
convKeys[v] = k
}
}
event, err := chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys)
if err == nil && event.Type == "Message" {
fmt.Println(event.AsMessage().Text())
}
```
```csharp theme={null}
if (!string.IsNullOrEmpty(keyChangeB64))
{
var extracted = chat.ExtractConversationKeys(new[] { keyChangeB64 });
foreach (var kv in extracted.Keys)
convKeys[kv.Key] = kv.Value;
}
var evt = chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys);
if (evt.GetProperty("type").GetString() == "Message")
Console.WriteLine(evt.GetProperty("content").GetProperty("text").GetString());
```
```java theme={null}
if (keyChangeB64 != null && !keyChangeB64.isEmpty()) {
var extracted = chat.extractConversationKeys(List.of(keyChangeB64));
convKeys.putAll(extracted.keys);
}
JsonNode evt = chat.decryptEvent(encodedEvent, convKeys, senderSigningKeys);
if ("Message".equals(evt.path("type").asText())) {
System.out.println(evt.path("content").path("text").asText());
}
```
Historial: [`GET /2/chat/conversations/{id}/events`](/x-api/chat/get-chat-conversation-events) + **`decrypt_events`** — consulta [Primeros pasos](/xchat/getting-started#6-receive-and-decrypt).
***
## Forma del payload (en vivo)
```json theme={null}
{
"data": {
"event_type": "chat.received",
"event_uuid": "0f52b591-4b7e-4f13-92cd-30e6b2a3f18a",
"payload": {
"conversation_id": "1215441834412953600-1843439638876491776",
"sender_id": "1843439638876491776",
"encoded_event": "BASE64_ENCODED_MESSAGE_EVENT",
"conversation_key_version": "1782945126642",
"conversation_key_change_event": "BASE64_ENCODED_KEY_CHANGE_EVENT"
}
}
}
```
***
## Prácticas
* Verifica las firmas del webhook según los requisitos de la plataforma
* Cachea las claves de conversación y las claves públicas de los remitentes
* Aplica los blobs de cambio de clave antes de descifrar mensajes dependientes
* Deduplica por `event_uuid`
# Solución de problemas
Source: https://docs.x.com/es/xchat/troubleshooting
Diagnostica problemas comunes de cifrado en X Chat, como errores del Chat XDK, recuperación de copia segura de claves y fallos de descifrado.
Esta página cubre problemas **específicos del cifrado de X Chat y del Chat XDK**—claves, copia de seguridad segura de claves, descifrar/verificar y construcción de payloads cifrados de envío.
Para webhooks, OAuth, códigos de estado HTTP y límites de tasa, usa la documentación general de la [X API](/x-api/introduction) y de [autenticación](/fundamentals/authentication/overview).
***
## Claves y copia de seguridad segura de claves
### El desbloqueo falla (código de acceso inválido)
* Confirma que el código de acceso coincide con el usado en `setup`
* Espera entre intentos; los realms limitan por tasa los intentos incorrectos y pueden bloquear la recuperación tras demasiados fallos
```python theme={null}
try:
chat.unlock(passcode)
except ValueError as e:
print(e) # may mention InvalidPin or guesses remaining
```
```typescript theme={null}
try {
await chat.unlock(passcode);
} catch (e) {
console.error((e as Error).message);
}
```
```rust theme={null}
chat.unlock(passcode_bytes).await?;
```
```go theme={null}
if err := chat.Unlock(passcode, juiceboxConfigJSON); err != nil {
log.Println(err)
}
```
```csharp theme={null}
try { chat.Unlock(passcode, juiceboxConfigJson); }
catch (Exception e) { Console.WriteLine(e.Message); }
```
```java theme={null}
try { chat.unlock(passcode, juiceboxConfigJson); }
catch (Exception e) { System.out.println(e.getMessage()); }
```
### El cifrado o descifrado falla porque las claves no están cargadas
Carga primero las claves privadas y después establece la **versión** de clave pública desde tu registro en X.
```python theme={null}
chat.unlock(passcode) # or: chat.import_keys(blob)
chat.set_key_version(signing_key_version)
```
```typescript theme={null}
await chat.unlock(passcode);
chat.setKeyVersion(signingKeyVersion);
```
```rust theme={null}
chat.import_keys(&blob)?;
chat.set_key_version(&signing_key_version);
```
```go theme={null}
blob, _ := chatxdk.Base64ToBytes(privateKeysB64)
_ = chat.ImportKeys(blob)
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
chat.ImportKeys(blobBytes);
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
chat.importKeys(blobBytes);
chat.setKeyVersion(signingKeyVersion);
```
### Falta la clave de conversación para un mensaje
No tienes la clave **en bruto** para el `conversation_key_version` de ese mensaje.
1. Descifra el material de clave desde `conversation_key_change_event` (eventos en vivo) o `meta.conversation_key_events` (historial) con `extract_conversation_keys`, **o** incluye esos blobs en `decrypt_events`
2. Confirma que se agregaron claves de conversación para esa versión y que sigues siendo participante (consulta [Primeros pasos](/xchat/getting-started#4-set-up-conversation-keys))
### El par no tiene claves públicas
Quizás no ha completado la incorporación. Después de que se registren, carga `public_key`, `signing_public_key`, `identity_public_key_signature` y `public_key_version` desde **API reference → Encryption keys**.
***
## Descifrado y firmas
### El descifrado falla
* Clave de conversación **en bruto** desactualizada o incorrecta, o versión de clave incorrecta
* Cadena `encoded_event` incompleta
* El tipo de evento no es un mensaje cifrado que puedas tratar como contenido descifrable
### La firma no verifica
La verificación es **fail-closed por defecto** (`reject_unverified = true`): el SDK ya rechaza los eventos firmados no verificados, así que un fallo aquí significa que las entradas de verificación son incorrectas, no que debas activar la comprobación. Causas comunes:
* Entrada de clave de firma faltante o incompleta para el **remitente** (todos los campos que requiere el Chat XDK—consulta la referencia del [Chat XDK](/xchat/xchat-xdk))
* El remitente rotó versiones—vuelve a obtener sus claves públicas
* Una versión de clave por debajo del piso aceptado nunca verifica
El setter `set_reject_unverified` existe para **optar por salir** de este predeterminado (`false`, no recomendado). Si lo desactivaste antes, restaura el predeterminado fail-closed:
```python theme={null}
chat.set_reject_unverified(True)
```
```typescript theme={null}
chat.setRejectUnverified(true);
```
```rust theme={null}
chat.set_reject_unverified(true);
```
```go theme={null}
chat.SetRejectUnverified(true)
```
```csharp theme={null}
chat.SetRejectUnverified(true);
```
```java theme={null}
chat.setRejectUnverified(true);
```
### Los eventos antiguos fallan la verificación de forma permanente
Errores como `signature missing or no matching signing key` o un desajuste ECDSA en eventos **antiguos** son permanentes. Las firmas son inmutables y se verifican reconstruyendo el payload firmado desde el evento en sí, así que un evento firmado sobre bytes distintos (o nunca firmado) fallará en cada carga futura—ninguna reintentación, actualización de claves o llamada a la API puede sanarlo. Trata estos eventos como tombstones, no como errores reintentables. Rotar la clave de conversación inicia un historial limpio y verificable desde ese punto en adelante; los mensajes nuevos no se ven afectados.
***
## Construcción del payload de envío
Estos errores son específicos del cifrado de X Chat (no errores HTTP generales):
| Problema | Solución |
| :-------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Bytes de clave incorrectos | Pasa los bytes de la clave de conversación **en bruto** al Chat XDK, no la cadena de clave cifrada que retorna la API |
| Nombres de campo JSON incorrectos | Mapea `encrypted_content` → `encoded_message_create_event` y `encoded_event_signature` → `encoded_message_event_signature` |
| Falta el id del mensaje | Genera `message_id` por tu cuenta y envía el mismo valor en el cuerpo de la solicitud |
| Desajuste de versión | Alinea `conversation_key_version` con la clave que usas; alinea la versión de la clave de firma con `set_key_version` / tu registro de clave pública |
| Forma del id en la ruta | Las rutas URL siguen necesitando el id de conversación con guión (`:` → `-`), pero para firmar el SDK acepta cualquier forma: `A:B`, `A-B` (en cualquier orden) o solo el id de usuario del destinatario—todos se canonicalizan a los mismos bytes firmados |
### La API devuelve 400 en una llamada que cambia estado
Cada llamada de chat que cambia estado—agregar o rotar claves de conversación, crear un grupo, agregar miembros—requiere **`action_signatures`** en el cuerpo de la solicitud, validado en el límite de la API. Una entrada faltante o mal formada (cada una necesita `message_id`, `encoded_message_event_detail` y un `message_event_signature` con `signature`, `public_key_version` y `signature_version`) devuelve inmediatamente una respuesta HTTP 400 problem-details. Usa los métodos prepare del SDK (`prepare_conversation_key_change`, `prepare_group_create`, `prepare_group_members_change`) y envía **todas** las firmas devueltas—crear un grupo y añadir miembros devuelven dos.
***
## Cifrar y descifrar multimedia
* Usa la **misma** clave de conversación (y versión) que el mensaje que referencia el adjunto
* Trata las respuestas de descarga como **texto cifrado** hasta que ejecutes `decrypt_stream`
* Infiere el tipo MIME **después** de descifrar; el `Content-Type` de la descarga a menudo no es el tipo real de imagen
Detalles: [Multimedia](/xchat/media).
***
## Depuración segura
Al investigar fallos criptográficos:
* Registra solo los ids de conversación, ids de evento y **versiones** de clave
* **No** registres texto plano, códigos de acceso, claves privadas ni blobs de clave completos
* Confirma que `set_key_version` coincide con `public_key_version` en tu registro de clave pública
* Para historial incompleto, pagina **todas** las páginas de eventos para no saltarte metadatos de cambio de clave antes de descifrar
# Referencia del Chat XDK
Source: https://docs.x.com/es/xchat/xchat-xdk
Referencia del Chat XDK, el SDK de cifrado que gestiona claves, cifrado, descifrado y firmas para X Chat en los lenguajes compatibles.
El **Chat XDK** se encarga de la gestión de claves, cifrado, descifrado y firma para X Chat. **No** llama a la HTTP API de X—combínalo con el **XDK** de [Python](/xdks/python/overview) o [TypeScript](/xdks/typescript/overview), o con HTTPS y un token de acceso de usuario.
Recorrido de la app: [Primeros pasos](/xchat/getting-started). Bots de ejemplo: [chat-xdk/examples](https://github.com/xdevplatform/chat-xdk/tree/main/examples).
### Instalar
```bash theme={null}
pip install chatxdk
```
El paquete de PyPI es `chatxdk`; impórtalo como `chat_xdk`. Requiere Python 3.10+.
```bash theme={null}
npm install @xdevplatform/chat-xdk
npm install juicebox-sdk # optional peer dependency — required for setup()/unlock() secure key backup
```
El motor WASM compilado viene dentro del paquete: no hay paso de build. Requiere Node.js 18+.
```toml theme={null}
[dependencies]
# chat-xdk-core is not yet on crates.io — use the git dependency.
# It exports both ChatCore and the async secure-key-backup Chat type.
chat-xdk-core = { git = "https://github.com/xdevplatform/chat-xdk", tag = "v0.2.1" }
# Required until thrift 0.24 is released on crates.io
[patch.crates-io]
thrift = { git = "https://github.com/apache/thrift.git", rev = "deb36fa409849de45973b04ffc3ce49d277ca90a" }
```
```bash theme={null}
go get github.com/xdevplatform/chat-xdk/go/chatxdk
```
Se incluyen bibliotecas estáticas precompiladas (macOS arm64/amd64, Linux amd64 glibc/musl): necesitas un compilador de C, pero no Rust. Requiere Go 1.21+.
```bash theme={null}
dotnet add package XDevPlatform.ChatXdk
```
El paquete es autónomo: incluye las bibliotecas nativas para macOS (arm64, x64), Linux (x64) y Windows (x64). Requiere .NET 8+.
```xml theme={null}
com.xchatxdk0.2.1
```
Disponible en Maven Central. El jar incluye la biblioteca nativa para macOS (arm64, x64), Linux (x64) y Windows (x64): no necesitas configurar `jna.library.path`. Importa desde `com.x.chatxdk`. Requiere JDK 17+.
***
## Inicio rápido
Descifra un backlog, cachea claves, descifra un evento y cifra una respuesta. Conecta el cuerpo de envío a [`POST /2/chat/conversations/{id}/messages`](/x-api/chat/send-chat-message) como se explica en [Primeros pasos](/xchat/getting-started).
```python theme={null}
from chat_xdk import Chat
chat = Chat(juicebox_config_json) # or Chat() + import_keys(blob)
chat.unlock("YOUR_PASSCODE")
chat.set_key_version(signing_key_version)
result = chat.decrypt_events(raw_events, signing_keys)
for dm in result["messages"]:
ev = dm["event"]
if ev.get("type") == "Message":
print(ev.get("sender_id"), ev.get("content", {}).get("text"))
cached = result["conversation_keys"]["keys"]
event = chat.decrypt_event(one_event_b64, cached, sender_signing_keys)
raw_key = cached[result["conversation_keys"]["latest_version"]]
payload = chat.encrypt_message(
message_id, sender_id, conversation_id, raw_key, "Hi!",
conversation_key_version, signing_key_version,
)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: juiceboxConfigJson,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(signingKeyVersion);
const result = chat.decryptEvents(rawEvents, signingKeys);
for (const dm of result.messages) {
if (dm.event.type === 'message') {
console.log(dm.event.senderId, dm.event.content?.text);
}
}
const cached = result.conversationKeys.keys;
const event = chat.decryptEvent(oneEventB64, cached, senderSigningKeys);
const rawKey = cached[result.conversationKeys.latestVersion!];
const payload = chat.encryptMessage({
messageId, senderId, conversationId, conversationKey: rawKey, text: 'Hi!',
conversationKeyVersion, signingKeyVersion,
});
```
```rust theme={null}
// ChatCore + import_keys, or chat_xdk_core::Chat + unlock().await
let result = chat.decrypt_events(&raw_events, &signing_keys);
let cached = &result.conversation_keys.keys;
let event = chat.decrypt_event(one_event_b64, cached, &sender_signing_keys)?;
// cached values are XChatConversationKey; encrypt_message wants owned bytes
let latest = result.conversation_keys.latest_version.as_deref().unwrap_or_default();
let conv_key = cached[latest].to_bytes();
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id, &sender_id, &conversation_id, conv_key, "Hi!",
&conversation_key_version, &signing_key_version,
))?;
```
```go theme={null}
chat := chatxdk.New()
defer chat.Close()
blob, _ := chatxdk.Base64ToBytes(privateKeysB64)
_ = chat.ImportKeys(blob)
chat.SetKeyVersion(signingKeyVersion)
result, err := chat.DecryptEvents(rawEvents, signingKeys)
cached := result.ConversationKeys.Keys
event, err := chat.DecryptEvent(oneEventB64, cached, senderSigningKeys)
rawKey := cached[*result.ConversationKeys.LatestVersion]
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawKey, Text: "Hi!",
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
})
_ = event
_ = payload
_ = err
```
```csharp theme={null}
using var chat = new Chat();
chat.ImportKeys(privateKeyBytes);
chat.SetKeyVersion(signingKeyVersion);
var result = chat.DecryptEvents(rawEvents, signingKeys);
var cached = result.ConversationKeys.Keys;
var evt = chat.DecryptEvent(oneEventB64, cached, senderSigningKeys);
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId, SenderId = senderId, ConversationId = conversationId,
ConversationKey = rawKey, Text = "Hi!",
ConversationKeyVersion = conversationKeyVersion, SigningKeyVersion = signingKeyVersion,
});
```
```java theme={null}
try (Chat chat = new Chat()) {
chat.importKeys(privateKeyBytes);
chat.setKeyVersion(signingKeyVersion);
DecryptEventsResult result = chat.decryptEvents(rawEvents, signingKeys);
Map cached = result.conversationKeys.keys;
JsonNode event = chat.decryptEvent(oneEventB64, cached, senderSigningKeys);
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawKey;
params.text = "Hi!";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
}
```
***
## Ciclo de vida y claves
Construye el SDK, guarda las claves privadas (copia de seguridad segura de claves protegida con código de acceso o un blob de claves local), registra las claves **públicas** con la Chat API y establece tu **versión de clave pública** registrada después de unlock o import. La copia de seguridad segura de claves está implementada con **Juicebox**, y por eso los campos de configuración relacionados llevan ese nombre. Llama a `generate_keypairs` una vez por identidad de dispositivo/app; envía el payload de registro con POST al endpoint de claves públicas. Usa `setup` / `unlock` (y helpers de código de acceso relacionados) para la copia de seguridad segura de claves en cada binding. `export_keys` / `import_keys` (persistencia de blob de clave en bruto para bots y servidores) están disponibles solo en los **bindings nativos**—Python, Go, .NET, JVM y Rust. El binding JS/WASM no expone la exportación ni importación de claves en bruto: en un navegador cualquier script que acceda a la instancia podría exfiltrar la identidad, así que JS mantiene las claves dentro de la copia de seguridad segura de claves. Un servidor JS que quiera evitar un round-trip al realm de copia de seguridad por solicitud debería reutilizar una única instancia `Chat` desbloqueada entre solicitudes, o ejecutar un binding nativo donde se admitan blobs de clave.
```python theme={null}
from chat_xdk import Chat
# Secure key backup (client)
chat = Chat(juicebox_config_json)
chat.setup("YOUR_PASSCODE") # first time — generates keypairs
# chat.unlock("YOUR_PASSCODE") # later sessions
chat.set_key_version(version) # from add-public-key / get-public-keys response
reg = chat.get_public_keys() # or registration fields from generate_keypairs
# Key blob (server / bot)
chat2 = Chat()
chat2.import_keys(secret_blob)
chat2.set_key_version(version)
blob = chat2.export_keys() # treat as a password
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: juiceboxConfigJson,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.setup('YOUR_PASSCODE');
// await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(version);
const publics = chat.getPublicKeys();
// JS/WASM stores keys only through secure key backup — there is no raw key
// export/import here. For key-blob persistence, use a native binding.
```
```rust theme={null}
// chat_xdk_core::Chat — async secure key backup unlock, or ChatCore + import_keys
chat.setup("YOUR_PASSCODE").await?;
// chat.unlock("YOUR_PASSCODE").await?;
chat.set_key_version(&version);
let publics = chat.get_public_keys()?;
let blob = chat.export_keys()?;
chat.import_keys(&blob)?;
```
```go theme={null}
chat := chatxdk.New()
defer chat.Close()
// Prefer ImportKeys for servers; secure key backup unlock where supported
keyBlob, _ := chatxdk.Base64ToBytes(privateKeysB64)
if err := chat.ImportKeys(keyBlob); err != nil {
log.Fatal(err)
}
chat.SetKeyVersion(version)
publics, err := chat.GetPublicKeys()
blob, err := chat.ExportKeys()
_ = publics
_ = blob
_ = err
```
```csharp theme={null}
using var chat = new Chat();
chat.ImportKeys(privateKeyBytes);
// or secure key backup setup / unlock when config is available
chat.SetKeyVersion(version);
var publics = chat.GetPublicKeys();
var blob = chat.ExportKeys();
```
```java theme={null}
try (Chat chat = new Chat()) {
chat.importKeys(privateKeyBytes);
chat.setKeyVersion(version);
var publics = chat.getPublicKeys();
byte[] blob = chat.exportKeys();
}
```
La configuración de la copia de seguridad segura de claves acepta tres formas: el objeto `juicebox_config` de la X API (recomendado—pasado verbatim), un wrapper completo `sdk_config` o un `token_map` desnudo.
Opcional: la verificación de firma está **activada por defecto** (`reject_unverified = true`)—llama a `set_reject_unverified(false)` para desactivarla (no recomendado); `update_config` si cambia la configuración de realms de copia de seguridad; `is_unlocked` / `has_identity_key` para el estado de la UI. Las listas completas de campos están en los stubs del [repo chat-xdk](https://github.com/xdevplatform/chat-xdk).
***
## Claves de conversación
Tres métodos **prepare** hacen que una sola llamada haga todo lo que un cambio de clave necesita: generar una nueva clave de conversación, cifrarla para cada participante (a partir de las claves públicas que pases) y firmar el cambio. Todos devuelven la misma forma **`PreparedConversationChange`**, lista para POST—renombra el campo del SDK `encrypted_key` a **`encrypted_conversation_key`** en `conversation_participant_keys` y mapea las firmas de acción al campo de cuerpo requerido **`action_signatures`**.
| Escenario | Método | Firmas de acción devueltas |
| :-------------------------------------------------------------------------------------------------------------------- | :-------------------------------- | :------------------------- |
| Iniciar un 1:1 (omite el id de conversación—el SDK lo deriva) o rotar la clave de cualquier conversación (pasa el id) | `prepare_conversation_key_change` | 1 |
| Crear un grupo (id acuñado por `POST /2/chat/conversations/group/initialize`) | `prepare_group_create` | 2—envía ambas |
| Agregar miembros a un grupo | `prepare_group_members_change` | 2—envía ambas |
Conserva los bytes de la clave **en bruto** para `encrypt_message` y multimedia; nunca pases el sobre cifrado de la API a encrypt.
**Verifica las claves obtenidas antes de envolverlas.** Los métodos prepare cifran la nueva clave de conversación hacia cualesquiera claves públicas que pases. Antes de pasarlas, llama a `verify_key_binding(identity, signing, signature)` en cada registro obtenido—sus campos `public_key`, `signing_public_key` e `identity_public_key_signature` de la API de claves públicas—para que una clave de identidad sustituida no pueda recibir la clave de conversación.
Usa `extract_conversation_keys` en los payloads de eventos de cambio de clave para reconstruir `{ keys, latest_version }`. `decrypt_conversation_key` desenvuelve un solo blob ECIES.
```python theme={null}
# One entry per participant public key, from the public-keys API:
# participants = [
# {"user_id": "1215441834412953600", "public_key": "BASE64_IDENTITY_PUBLIC_KEY", "key_version": "1733889755256"},
# {"user_id": "1843439638876491776", "public_key": "BASE64_IDENTITY_PUBLIC_KEY", "key_version": "1766181805686"},
# ]
prepared = chat.prepare_conversation_key_change(my_user_id, signing_key_version, participants)
# prepared["conversation_key"] — raw bytes for encrypt_message
# prepared["participant_keys"] — per-user wraps; rename encrypted_key → encrypted_conversation_key on POST
# prepared["action_signatures"] — required on the POST body
extracted = chat.extract_conversation_keys(key_change_blobs)
keys = extracted["keys"]
latest = extracted["latest_version"]
raw = keys[latest]
one = chat.decrypt_conversation_key(encrypted_blob)
```
```typescript theme={null}
const prepared = chat.prepareConversationKeyChange({
senderId: myUserId, signingKeyVersion, publicKeys: participants,
});
// prepared.conversationKey — Uint8Array for encryptMessage
// prepared.participantKeys / prepared.actionSignatures — POST body fields
const extracted = chat.extractConversationKeys(keyChangeBlobs);
const raw = extracted.keys[extracted.latestVersion!];
const one = chat.decryptConversationKey(encryptedBlob);
```
```rust theme={null}
let prepared = chat.prepare_conversation_key_change(
ConversationKeyChangeParams::new(&my_user_id, &signing_key_version, participants),
)?;
let extracted = chat.extract_conversation_keys(&key_change_blobs);
let latest = extracted.latest_version.as_deref().unwrap_or_default();
let raw = &extracted.keys[latest];
let one = chat.decrypt_conversation_key(&encrypted_blob)?;
```
```go theme={null}
prepared, err := chat.PrepareConversationKeyChange(chatxdk.ConversationKeyChangeParams{
SenderID: myUserID, SigningKeyVersion: signingKeyVersion, PublicKeys: participants,
})
// prepared.ConversationKey feeds EncryptMessage
// prepared.ParticipantKeys / prepared.ActionSignatures — POST body fields
extracted, err := chat.ExtractConversationKeys(keyChangeBlobs)
one, err := chat.DecryptConversationKey(encryptedBlob)
_ = prepared
_ = extracted
_ = one
_ = err
```
```csharp theme={null}
var prepared = chat.PrepareConversationKeyChange(new ConversationKeyChangeParams {
SenderId = myUserId, SigningKeyVersion = signingKeyVersion, PublicKeys = participants,
});
var extracted = chat.ExtractConversationKeys(keyChangeBlobs);
var raw = extracted.Keys[extracted.LatestVersion];
var one = chat.DecryptConversationKey(encryptedBlob);
```
```java theme={null}
ConversationKeyChangeParams keyParams = new ConversationKeyChangeParams();
keyParams.senderId = myUserId;
keyParams.signingKeyVersion = signingKeyVersion;
keyParams.publicKeys = participants;
PreparedConversationChange prepared = chat.prepareConversationKeyChange(keyParams);
ConversationKeyBundle extracted = chat.extractConversationKeys(keyChangeBlobs);
byte[] raw = extracted.keys.get(extracted.latestVersion);
byte[] one = chat.decryptConversationKey(encryptedBlob);
```
Para crear grupo y agregar miembros, pasa los params que cada método necesita (listas de ids de miembros/admins para `prepare_group_create`; nuevos más el roster actual para `prepare_group_members_change`)—consulta [Grupos](/xchat/groups#create-the-group-and-establish-keys) para ejemplos. Ambos devuelven **dos** firmas de acción; el POST debe incluir ambas.
***
## Descifrar
**`decrypt_events`** es para el historial y el backlog: extrae las claves de conversación del stream, devuelve los mensajes descifrados y **recolecta** errores por evento en lugar de fallar el lote completo. **`decrypt_event`** es para un solo evento en vivo cuando ya tienes un caché de claves; lanza excepción/throw ante un fallo.
Pasa **claves de firma** para que el SDK pueda verificar a los remitentes. Mapea los campos de clave pública de la API a `SigningKeyEntry`: `public_key_version` → `public_key_version` (mismo nombre), `signing_public_key` → `public_key`, `public_key` → `identity_public_key`, más `identity_public_key_signature` y `user_id`. La verificación es obligatoria por defecto: omitir o pasar una lista vacía de claves de firma **no** la salta—los eventos firmados fallan (recolectados en `errors` para `decrypt_events`, lanzados para `decrypt_event`). Para realmente saltar la verificación primero debes llamar a `set_reject_unverified(false)` (no recomendado en producción).
```python theme={null}
signing_keys = [{
"user_id": uid,
"public_key_version": row["public_key_version"],
"public_key": row["signing_public_key"],
"identity_public_key": row["public_key"],
"identity_public_key_signature": row["identity_public_key_signature"],
} for row in api_public_keys]
result = chat.decrypt_events(raw_events, signing_keys)
for idx, msg in (result.get("errors") or {}).items():
log.warning("event %s failed: %s", idx, msg)
for dm in result["messages"]:
ev = dm["event"]
if ev.get("type") == "Message":
text = ev.get("content", {}).get("text")
cached = result["conversation_keys"]["keys"]
live = chat.decrypt_event(one_event_b64, cached, signing_keys_for_sender)
```
```typescript theme={null}
const signingKeys = apiPublicKeys.map((row) => ({
userId: uid,
publicKeyVersion: row.public_key_version,
publicKey: row.signing_public_key,
identityPublicKey: row.public_key,
identityPublicKeySignature: row.identity_public_key_signature,
}));
const result = chat.decryptEvents(rawEvents, signingKeys);
for (const [idx, msg] of Object.entries(result.errors ?? {})) {
console.warn(`event ${idx} failed: ${msg}`);
}
const cached = result.conversationKeys.keys;
const live = chat.decryptEvent(oneEventB64, cached, signingKeysForSender);
```
```rust theme={null}
let result = chat.decrypt_events(&raw_events, &signing_keys);
for (idx, msg) in &result.errors {
eprintln!("event {idx} failed: {msg}");
}
let cached = &result.conversation_keys.keys;
let live = chat.decrypt_event(one_event_b64, cached, &signing_keys_for_sender)?;
```
```go theme={null}
result, err := chat.DecryptEvents(rawEvents, signingKeys)
for idx, msg := range result.Errors {
log.Printf("event %s failed: %s", idx, msg)
}
cached := result.ConversationKeys.Keys
live, err := chat.DecryptEvent(oneEventB64, cached, signingKeysForSender)
_ = live
_ = err
```
```csharp theme={null}
var result = chat.DecryptEvents(rawEvents, signingKeys);
foreach (var kv in result.Errors) { /* kv.Key = event index, kv.Value = error */ }
var cached = result.ConversationKeys.Keys;
var live = chat.DecryptEvent(oneEventB64, cached, signingKeysForSender);
```
```java theme={null}
DecryptEventsResult result = chat.decryptEvents(rawEvents, signingKeys);
Map cached = result.conversationKeys.keys;
JsonNode live = chat.decryptEvent(oneEventB64, cached, signingKeysForSender);
```
***
## Helpers de cifrado y envío
**`encrypt_message`** construye el texto cifrado firmado para un mensaje de texto (entidades opcionales, adjuntos vía `media_hash_key`, TTL, flags de notificación). Mapea el payload devuelto al cuerpo send-message: `encrypted_content` → **`encoded_message_create_event`**, `encoded_event_signature` → **`encoded_message_event_signature`**, más tu **`message_id`**.
Usa **`encrypt_reply`**, **`encrypt_add_reaction`** y **`encrypt_remove_reaction`** para respuestas y reacciones (`sequence_id` apunta al padre). **`encrypt` / `decrypt`** son para metadatos UTF-8 bajo la clave de conversación (por ejemplo, un nombre de grupo cifrado)—no sobres de mensajes. **`encrypt_stream` / `decrypt_stream`** cifran los bytes de los adjuntos; consulta [Multimedia](/xchat/media). Los métodos de bajo nivel **`sign` / `verify` / `verify_key_binding`** admiten flujos avanzados; los cambios de clave de conversación, creaciones de grupo y adiciones de miembros son firmados por los [métodos prepare](#claves-de-conversaci-n).
El id de conversación pasado a `encrypt_message` / `encrypt_reply` puede ser cualquier forma que tengas—`A:B` de eventos, `A-B` de listados o rutas URL (en cualquier orden) o solo el id de usuario del destinatario—el SDK lo canonicaliza antes de firmar. Los ids de grupo (con prefijo `g`) pasan sin cambios.
```python theme={null}
payload = chat.encrypt_message(
message_id, sender_id, conversation_id, raw_conversation_key, "Hello",
conversation_key_version, signing_key_version,
# Optional keyword args: entities, attachments, should_notify, ttl_msec
)
body = {
"message_id": message_id,
"encoded_message_create_event": payload["encrypted_content"],
"encoded_message_event_signature": payload["encoded_event_signature"],
}
# POST body to /2/chat/conversations/{id}/messages
reply = chat.encrypt_reply(
reply_message_id, sender_id, conversation_id, raw_conversation_key,
"Sounds good", conversation_key_version, signing_key_version,
parent_sequence_id, # reply_to_sequence_id — the message being replied to
)
name_ct = chat.encrypt("Group title", raw_conversation_key)
title = chat.decrypt(name_ct, raw_conversation_key)
```
```typescript theme={null}
const payload = chat.encryptMessage({
messageId, senderId, conversationId, conversationKey: rawConversationKey, text: 'Hello',
conversationKeyVersion, signingKeyVersion,
});
const body = {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
};
const reply = chat.encryptReply({
messageId: replyMessageId, senderId, conversationId, conversationKey: rawConversationKey,
text: 'Sounds good', conversationKeyVersion, signingKeyVersion,
replyToSequenceId: parentSequenceId, // the message being replied to
});
const nameCt = chat.encrypt('Group title', rawConversationKey);
const title = chat.decrypt(nameCt, rawConversationKey);
```
```rust theme={null}
// conv_key: XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id, &sender_id, &conversation_id, conv_key.to_bytes(), "Hello",
&conversation_key_version, &signing_key_version,
))?;
// Map payload fields into the send-message JSON body as above
let name_ct = chat.encrypt("Group title", &conv_key)?;
let title = chat.decrypt(&name_ct, &conv_key)?;
```
```go theme={null}
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawKey, Text: "Hello",
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
})
// body: message_id, encoded_message_create_event, encoded_message_event_signature
nameCt, err := chat.Encrypt("Group title", rawKey)
title, err := chat.Decrypt(nameCt, rawKey)
_ = payload
_ = title
_ = err
```
```csharp theme={null}
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId, SenderId = senderId, ConversationId = conversationId,
ConversationKey = rawKey, Text = "Hello",
ConversationKeyVersion = conversationKeyVersion, SigningKeyVersion = signingKeyVersion,
});
// Map EncryptedContent / EncodedEventSignature into the send-message body
var nameCt = chat.Encrypt("Group title", rawKey);
var title = chat.Decrypt(nameCt, rawKey);
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawKey;
params.text = "Hello";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
// Map to encoded_message_create_event / encoded_message_event_signature on POST
String nameCt = chat.encrypt("Group title", rawKey);
String title = chat.decrypt(nameCt, rawKey);
```
***
## Streams de multimedia
Cifra los bytes del archivo con la **misma** clave de conversación usada para el texto, sube mediante las APIs de multimedia de Chat y adjunta **`media_hash_key`** en `encrypt_message`. Este no es el modelo de multimedia de Posts (`expansions=attachments.media_keys`). Flujo completo de subida/descarga: [Multimedia](/xchat/media).
```python theme={null}
ciphertext = chat.encrypt_stream(file_bytes, raw_conversation_key)
# Upload `ciphertext`; the `media_hash_key` you attach on encrypt_message
# comes from the media-upload finalize step, not from encrypt_stream.
plain = chat.decrypt_stream(ciphertext, raw_conversation_key)
```
```typescript theme={null}
const ciphertext = chat.encryptStream(fileBytes, rawConversationKey);
// Upload `ciphertext`; mediaHashKey comes from the upload finalize step.
const plain = chat.decryptStream(ciphertext, rawConversationKey);
```
```rust theme={null}
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let ciphertext = chat.encrypt_stream(&file_bytes, &conv_key)?;
let plain = chat.decrypt_stream(&ciphertext, &conv_key)?;
```
```go theme={null}
ciphertext, err := chat.EncryptStream(fileBytes, rawKey)
plain, err := chat.DecryptStream(ciphertext, rawKey)
_ = plain
_ = err
```
```csharp theme={null}
var ciphertext = chat.EncryptStream(fileBytes, rawKey);
var plain = chat.DecryptStream(ciphertext, rawKey);
```
```java theme={null}
byte[] ciphertext = chat.encryptStream(fileBytes, rawKey);
byte[] plain = chat.decryptStream(ciphertext, rawKey);
```
### Streaming incremental para multimedia grande
Para archivos grandes, evita mantener el payload completo en memoria: `stream_encryptor()` / `stream_decryptor()` devuelven un `StreamEncryptor` / `StreamDecryptor` al que alimentas por chunks (unos 1 MB cada uno) con `push(chunk)`, y luego llamas a `finish()` una vez al final. Al descifrar, `finish()` detecta un stream truncado (falla si la entrada terminó antes del frame final), así que no trates el texto plano acumulado como completo hasta que tenga éxito.
**Solo JS/WASM:** `finish()` consume y libera el objeto WASM subyacente—nunca llames a `free()` después de `finish()` (lanza error). Llama a `free()` solo para abandonar un stream *antes* de finalizar (por ejemplo, en una ruta de error).
```python theme={null}
enc = chat.stream_encryptor(raw_conversation_key)
chunks = [enc.push(chunk) for chunk in read_in_chunks(file_bytes, 1 << 20)]
chunks.append(enc.finish())
ciphertext = b"".join(chunks)
dec = chat.stream_decryptor(raw_conversation_key)
out = [dec.push(chunk) for chunk in read_in_chunks(ciphertext, 1 << 20)]
out.append(dec.finish()) # raises on truncation
plain = b"".join(out)
```
```typescript theme={null}
const enc = chat.streamEncryptor(rawConversationKey);
const parts: Uint8Array[] = [];
try {
for (const chunk of readInChunks(fileBytes, 1 << 20)) parts.push(enc.push(chunk));
parts.push(enc.finish()); // consumes + frees enc — do not call enc.free() after this
} catch (e) {
enc.free(); // only when abandoning before finish()
throw e;
}
const ciphertext = concat(parts);
```
***
## Utilidades
Los helpers de Base64/hex, sniffing de MIME y dimensiones de imagen están disponibles como funciones a nivel de módulo (Python/JS/Rust/Go) o `ChatXdkUtilities` (C#/Java)—útiles al construir metadatos de adjuntos sin traer librerías adicionales.
```python theme={null}
from chat_xdk import (
bytes_to_base64, base64_to_bytes, bytes_to_hex, hex_to_bytes,
detect_mime_type, detect_image_dimensions,
)
b64 = bytes_to_base64(raw)
raw2 = base64_to_bytes(b64)
hexed = bytes_to_hex(raw)
raw3 = hex_to_bytes(hexed)
mime = detect_mime_type(file_bytes)
w, h = detect_image_dimensions(file_bytes)
```
```typescript theme={null}
import { bytesToBase64, base64ToBytes, bytesToHex, hexToBytes, detectMimeType, detectImageDimensions } from '@xdevplatform/chat-xdk';
const b64 = bytesToBase64(raw);
const raw2 = base64ToBytes(b64);
const hexed = bytesToHex(raw);
const raw3 = hexToBytes(hexed);
const mime = detectMimeType(fileBytes);
const dims = detectImageDimensions(fileBytes);
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;
```
```rust theme={null}
let b64 = chat_xdk_core::bytes_to_base64(&raw);
let raw2 = chat_xdk_core::base64_to_bytes(&b64)?;
let hexed = chat_xdk_core::bytes_to_hex(&raw);
let raw3 = chat_xdk_core::hex_to_bytes(&hexed);
let mime = chat_xdk_core::detect_mime_type(&file_bytes);
let dims = chat_xdk_core::detect_image_dimensions(&file_bytes);
let (w, h) = dims.map(|d| (d.width, d.height)).unwrap_or((0, 0));
```
```go theme={null}
b64, _ := chatxdk.BytesToBase64(raw)
raw2, err := chatxdk.Base64ToBytes(b64)
hexed, err := chatxdk.BytesToHex(raw)
raw3, err := chatxdk.HexToBytes(hexed)
mime, _ := chatxdk.DetectMimeType(fileBytes)
dims, _ := chatxdk.DetectImageDimensions(fileBytes)
w, h := dims.Width, dims.Height
_ = b64
_ = raw2
_ = hexed
_ = raw3
_ = mime
_ = w
_ = h
_ = err
```
```csharp theme={null}
var b64 = ChatXdkUtilities.BytesToBase64(raw);
var raw2 = ChatXdkUtilities.Base64ToBytes(b64);
var hexed = ChatXdkUtilities.BytesToHex(raw);
var raw3 = ChatXdkUtilities.HexToBytes(hexed);
var mime = ChatXdkUtilities.DetectMimeType(fileBytes);
var dims = ChatXdkUtilities.DetectImageDimensions(fileBytes);
var w = dims?.Width ?? 0;
var h = dims?.Height ?? 0;
```
```java theme={null}
String b64 = ChatXdkUtilities.bytesToBase64(raw);
byte[] raw2 = ChatXdkUtilities.base64ToBytes(b64);
String hexed = ChatXdkUtilities.bytesToHex(raw);
byte[] raw3 = ChatXdkUtilities.hexToBytes(hexed);
String mime = ChatXdkUtilities.detectMimeType(fileBytes);
ImageDimensions wh = ChatXdkUtilities.detectImageDimensions(fileBytes);
long width = wh.width, height = wh.height;
```
***
## Tipos importantes
Estos tipos conceptuales aparecen en varios lenguajes (los nombres exactos de los campos difieren; JS suele usar discriminadores de evento en camelCase como `message`):
* **SendPayload** — valor de retorno de `encrypt_message` y helpers de cifrado relacionados; mapea al cuerpo de envío de la Chat API.
* **PublicKeyRegistrationPayload** — salida de `generate_keypairs` / getters de claves públicas para la API add-public-key.
* **SigningKeyEntry** — material público del remitente pasado a decrypt para la verificación de firma.
* **PreparedConversationChange** — salida de los tres métodos prepare: el `conversation_id` derivado o pasado, los bytes de `conversation_key` en bruto, `conversation_key_version`, `participant_keys` (`user_id`, `encrypted_key`, `public_key_version`) y `action_signatures` (`message_id`, `encoded_message_event_detail`, `signature`, `signature_version`, `public_key_version`, `signature_payload` opcional—omitido en firmas de cambio de clave porque ese payload incrusta la clave en texto plano).
* **DecryptEventsResult** — mensajes, errores opcionales y `conversation_keys` extraídas.
Para listas completas de campos, usa los stubs de lenguaje en el [repo chat-xdk](https://github.com/xdevplatform/chat-xdk) (`docs/API.md`, `*.pyi`, `index.d.ts`).
***
## Errores
Python normalmente lanza **`ValueError`** con un mensaje descriptivo (por ejemplo, un código de acceso inválido). TypeScript/JavaScript lanza **`Error`**. Go devuelve `(value, error)`. Prefiere **`decrypt_events`** para el historial de modo que un evento defectuoso no aborte el lote; inspecciona la colección de errores para ver fallos parciales.
Algunos errores de verificación son **permanentes**. Las firmas son inmutables y se verifican reconstruyendo el payload firmado desde el evento en sí, así que un evento antiguo que falla con `signature missing or no matching signing key` o un desajuste ECDSA fallará en cada carga futura—ninguna reintentación, actualización de claves o llamada a la API puede sanarlo. Trátalos como tombstones, no como errores transitorios. Rotar la clave de conversación inicia un historial limpio y verificable desde ese punto en adelante.
***
## Próximos pasos
Conecta el Chat XDK a la Chat API
Cifrado por stream y REST de multimedia
Webhooks y entrega de actividad
Fallos comunes
# Ads API Access Form
Source: https://docs.x.com/forms/ads-api-access
Request access to the X Ads API by submitting your details, including intended use case and app information, for review and approval.
# Application for Trial Enterprise Access
Source: https://docs.x.com/forms/application-trial
Apply for trial access to the X Enterprise API. Submit company information, intended use cases, and contact details to request an evaluation environment.
# Billing support form
Source: https://docs.x.com/forms/billing-support
Contact X API billing support for help with invoices, payment methods, subscription changes, refunds, plan upgrades, and account-related billing issues.
Get billing support for Self-serve and Enterprise API subscriptions.
# Enterprise Access Form
Source: https://docs.x.com/forms/enterprise-api-interest
Request access to the X Enterprise API by submitting company details, intended use case, expected data volume, and contact information for review.
# Government End User Request Form
Source: https://docs.x.com/forms/government-end-user-request
Government and public sector form to request X API access, providing agency details, intended use case, and compliance information for review.
# Survey: Product Tracks & Commercial Use
Source: https://docs.x.com/forms/survey
Share feedback about your X API product track, commercial use case, integration plans, and developer experience to help guide future platform changes.
# Initial use case application for new X API customers
Source: https://docs.x.com/forms/use-case/initial
Initial application form for prospective customers to request access to X API enterprise products by describing the intended use case and integration plan.
# Use case modification request for X API customers
Source: https://docs.x.com/forms/use-case/modification
Form for existing X API enterprise customers to request modifications to a previously approved use case, including changes to data products or workflows.
# Public sector use case request for X API customers
Source: https://docs.x.com/forms/use-case/public-sector
Form for existing public-sector X API customers, including government agencies, to submit a request related to a contracted enterprise data use case.
# Upgrade your enterprise account and add data products
Source: https://docs.x.com/forms/use-case/upgrade
Form for existing X API enterprise customers to upgrade their account and add new data products such as Search, Filtered Stream, or Account Activity.
# OAuth API reference index
Source: https://docs.x.com/fundamentals/authentication/api-reference
Reference index of X authentication endpoints across OAuth 1.0a and OAuth 2.0, including request tokens, authorize, access tokens, and token revocation.
### OAuth 1.0a
| | |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------- |
| **Purpose** | Method |
| Step 1 of the 3-legged OAuth flow and Sign in with X Allows a Consumer application to obtain an OAuth Request Token to request user authorization. | [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) |
| Step 2 of the 3-legged OAuth flow and Sign in with X Allows a Consumer application to use an OAuth Request Token to request user authorization. | [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) |
| Step 2 of the 3-legged OAuth flow and Sign in with X Allows a Consumer application to use an OAuth Request Token to request user authorization. | [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) |
| Step 3 of the 3-legged OAuth flow and Sign in with X Allows a Consumer application to exchange the OAuth Request Token for an OAuth Access Token. | [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) |
| Allows a registered application to revoke an issued OAuth Access Token. | [POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth-invalidate-token) |
### OAuth 2.0 Bearer Token
| | |
| :----------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
| **Purpose** | Method |
| Allows a registered App to generate an OAuth 2 app-only Bearer Token, which can be used to make API requests on an App's behalf, without user context. | [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) |
| Allows a registered App to revoke an issued OAuth 2 app-only Bearer Token. | [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) |
### POST oauth/request\_token
Allows a Consumer application to obtain an OAuth Request Token to request user authorization. This method fulfills [Section 6.1](https://oauth.net/core/1.0/#auth_step1) of the [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9).
**We require you use HTTPS for all OAuth authorization steps.**
**Usage Note:** Only ASCII values are accepted for the `oauth_nonce`
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/request_token`
**Resource Information[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Response formats | JSON |
| Requires authentication? | No |
| Rate limited? | Yes |
**Parameters[](#parameters "Permalink to this headline")**
| Name | Required | Description | Example |
| :-------------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------- |
| oauth\_callback | required | For OAuth 1.0a compliance this parameter is **required** . The value you specify here will be used as the URL a user is redirected to should they approve your application's access to their account. Set this to `oob` for out-of-band pin mode. This is also how you specify custom callbacks for use in desktop/mobile applications. Always send an `oauth_callback` on this step, regardless of a pre-registered callback.
We require that any callback URL used with this endpoint will have to be configured within the App’s settings on developer.x.com\* | `http://themattharris.local/auth.php` `twitterclient://callback` |
| x\_auth\_access\_type | optional | Overrides the access level an application requests to a users account. Supported values are `read` or `write` . This parameter is intended to allow a developer to register a read/write application but also request read only access when appropriate. | |
Learn more about how to approve your callback URLs on [this page](/resources/fundamentals/developer-apps#callback-urls).
**Please note** - You can view and edit your existing [X apps](/resources/fundamentals/developer-apps) via the [X app dashboard](https://developer.x.com/en/apps) if you are logged into your X account on developer.x.com.
**Example request[](#example-request "Permalink to this headline")**
Request URL: `POST https://api.x.com/oauth/request_token`
Request POST Body: *N/A*
Authorization Header: `OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw", oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1300228849", oauth_consumer_key="OqEqJeafRSF11jBMStrZz", oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", oauth_version="1.0"`
Response: `oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik&oauth_token_secret=Kd75W4OQfb2oJTV0vzGzeXftVAwgMnEK9MumzYcM&oauth_callback_confirmed=true`
### GET oauth/authorize
Allows a Consumer application to use an OAuth Request Token to request user authorization. This method fulfills [Section 6.2](http://oauth.net/core/1.0/#auth_step2) of the [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9). Desktop applications must use this method (and cannot use [GET oauth / authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate)).
**Usage Note:** An `oauth_callback` is never sent to this method, provide it to [POST oauth / request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) instead.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authorize`
**Resource Information[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Response formats | JSON |
| Requires authentication? | Yes |
| Rate limited? | Yes |
**Parameters[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :------- | :-------------------------------------------------------------------------------------------- | :------------ | :------ |
| Name | Required | Description | Default Value | Example |
| force\_login | optional | Forces the user to enter their credentials to ensure the correct users account is authorized. | | |
| screen\_name | optional | Prefills the username input box of the OAuth login screen with the given value. | | |
**Example request[](#example-request "Permalink to this headline")**
Send the user to the `oauth/authorize` step in a web browser, including an oauth\_token parameter:
`https://api.x.com/oauth/authorize?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### GET oauth/authenticate
Allows a Consumer application to use an OAuth `request_token` to request user authorization.
This method is a replacement of [Section 6.2](http://oauth.net/core/1.0/#auth_step2) of the [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9) for applications using the callback authentication flow. The method will use the currently logged in user as the account for access authorization unless the `force_login` parameter is set to `true`.
This method differs from [GET oauth / authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) in that if the user has already granted the application permission, the redirect will occur without the user having to re-approve the application. To realize this behavior, you must enable the *Use Sign in with X* setting on your [application record](https://developer.x.com/apps).
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authenticate`
**Resource Information[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Response formats | JSON |
| Requires authentication? | Yes |
| Rate limited? | Yes |
**Parameters[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :------- | :-------------------------------------------------------------------------------------------- | :------------ | :------ |
| Name | Required | Description | Default Value | Example |
| force\_login | optional | Forces the user to enter their credentials to ensure the correct users account is authorized. | | *true* |
| screen\_name | optional | Prefills the username input box of the OAuth login screen with the given value. | | |
**Example request[](#example-request "Permalink to this headline")**
Send the user to the `oauth/authenticate` step in a web browser, including an oauth\_token parameter:
`https://api.x.com/oauth/authenticate?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### POST oauth/access\_token
Allows a Consumer application to exchange the OAuth Request Token for an OAuth Access Token. This method fulfills [Section 6.3](http://oauth.net/core/1.0/#auth_step3) of the [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9).
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/access_token`
**Resource Information[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :--- |
| Response formats | JSON |
| Requires authentication? | Yes |
| Rate limited? | Yes |
**Parameters[](#parameters "Permalink to this headline")**
| | | | | |
| :-------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------ | :------ |
| Name | Required | Description | Default Value | Example |
| oauth\_token | required | The oauth\_token here must be the same as the oauth\_token returned in the request\_token step. | | |
| oauth\_verifier | required | If using the OAuth web-flow, set this parameter to the value of the *oauth\_verifier* returned in the callback URL. If you are using out-of-band OAuth, set this value to the pin-code. For OAuth 1.0a compliance this parameter is **required**. OAuth 1.0a is strictly enforced and applications not using the *oauth\_verifier* will fail to complete the OAuth flow. | | |
**Example request[](#example-request "Permalink to this headline")**
`POST https://api.x.com/oauth/access_token?oauth_token=qLBVyoAAAAAAx72QAAATZxQWU6P&oauth_verifier=ghLM8lYmAxDbaqL912RZSRjCCEXKDIzx`
From PIN-based `POST https://api.x.com/oauth/access_token?oauth_token=9Npq8AAAAAAAx72QBRABZ4DAfY9&oauth_verifier=4868795`
**Example response[](#example-response "Permalink to this headline")**
`oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG5ly3sR3XjE0IBSnlQu4ZrUzPiYTmrkVU&user_id=6253282&screen_name=xapi`
### POST oauth/invalidate\_token
Allows a registered application to revoke an issued OAuth access\_token by presenting its client credentials. Once an access\_token has been invalidated, new creation attempts will yield a different Access Token and usage of the invalidated token will no longer be allowed.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/1.1/oauth/invalidate_token`
**Resource Information[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :-------------------------------------------------------------------------- |
| Response formats | JSON |
| Requires authentication? | Yes - User context with the access tokens that you would like to invalidate |
| Rate limited? | Yes |
**Example request[](#example-request "Permalink to this headline")**
```bash theme={null}
curl --request POST
--url 'https://api.x.com/1.1/oauth/invalidate_token.json'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**Example response[](#example-response "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 127
...
{"access_token":"ACCESS_TOKEN"}
```
**Example error response after token has been invalidated[](#example-error-response-after-token-has-been-invalidated "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 401 Authorization Required
...
{"errors": [{
"code": 89,
"message": "Invalid or expired token."}
]}
```
### POST oauth2/token
Allows a registered application to obtain an OAuth 2 Bearer Token, which can be used to make API requests on an application's own behalf, without a user context. This is called [Application-only authentication](/resources/fundamentals/authentication/oauth-2-0/application-only).
A Bearer Token may be invalidated using oauth2/invalidate\_token. Once a Bearer Token has been invalidated, new creation attempts will yield a different Bearer Token and usage of the previous token will no longer be allowed.
Only one bearer token may exist outstanding for an application, and repeated requests to this method will yield the same already-existent token until it has been invalidated.
Successful responses include a JSON-structure describing the awarded Bearer Token.
Tokens received by this method should be cached. If attempted too frequently, requests will be rejected with an HTTP 403 with code 99.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/token`
**Resource Information[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :-------------------------------------------------------------------------------------- |
| Response formats | JSON |
| Requires authentication? | Yes - Basic auth with your API key as your username and API key secret as your password |
| Rate limited? | Yes |
**Parameters[](#parameters "Permalink to this headline")**
| | | | | |
| :---------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------ | :-------------------- |
| Name | Required | Description | Default Value | Example |
| grant\_type | required | Specifies the type of grant being requested by the application. At this time, only *client\_credentials* is allowed. See [Application-Only Authentication](/resources/fundamentals/authentication/oauth-2-0/application-only) for more information. | | *client\_credentials* |
**Example request[](#example-request "Permalink to this headline")**
```bash theme={null}
POST /oauth2/token HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=client_credentials
```
**Example response:**
```bash theme={null}
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
```
### POST oauth2/invalidate\_token
Allows a registered application to revoke an issued oAuth 2.0 Bearer Token by presenting its client credentials. Once a Bearer Token has been invalidated, new creation attempts will yield a different Bearer Token and usage of the invalidated token will no longer be allowed.
Successful responses include a JSON-structure describing the revoked Bearer Token.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/invalidate_token`
**Resource Information[](#resource-information "Permalink to this headline")**
| | |
| :----------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Response formats | JSON |
| Requires authentication? | Yes - [oAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a) with the application's consumer API keys and the application owner's access token & access token secret |
| Rate limited? | Yes |
**Parameters[](#parameters "Permalink to this headline")**
| Name | Required | Description |
| :------------ | :------- | :-------------------------------------------------------------- |
| access\_token | required | The value of the bearer token that you would like to invalidate |
**Example request[](#example-request "Permalink to this headline")**
```
curl --request POST
--url 'https://api.x.com/oauth2/invalidate_token?access_token=AAAA%2FAAA%3DAAAAAAAA'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**Example response[](#example-response "Permalink to this headline")**
```
Status: 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 135
...
{
"access_token": "AAAA%2FAAA%3DAAAAAAAA"
}
```
# Basic authentication
Source: https://docs.x.com/fundamentals/authentication/basic-auth
Use HTTP Basic authentication to access X enterprise APIs like PowerTrack, Decahose, and Search by sending your email and password over HTTPS.
## Basic authentication
Many of X's enterprise APIs require the use of HTTP Basic Authentication. To make a successful request to an API that requires Basic Authentication, you must pass a valid email address and password combination as an authorization header for each request. The email and password combination are the same ones that you will use to access the [enterprise API console](https://console.gnip.com/), and can be edited from within this console.
When building a request using Basic Authentication, make sure you add the Authentication: Basic HTTP header with encoded credentials over HTTPS.
In the following cURL request example, you would replace `` and `` with your credentials before sending the request:
```bash theme={null}
curl -v --compressed -u:
"https://gnip-api.x.com/search/30day/accounts//prod/counts.json?query=from%3Axdevelopers"
```
**APIs that require basic authentication:**
* [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) enterprise
* [Decahose stream API](http://localhost:3000/x-api/enterprise-gnip-2.0/fundamentals/decahose-api) enterprise
* [30-Day Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Full-Archive Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Usage API](/x-api/enterprise-gnip-2.0/fundamentals/usage) enterprise
# OAuth FAQ
Source: https://docs.x.com/fundamentals/authentication/faq
Answers to common questions about OAuth 1.0a, OAuth 2.0, access tokens, scopes, and authentication errors when working with the X API.
## General
OAuth is an authentication protocol that allows users to approve an application to act on their behalf without sharing their password. More information can be found at [oauth.net](http://oauth.net/).
You must have a [X app](/resources/fundamentals/developer-apps) to generate access tokens. Learn more about access tokens [here](/resources/fundamentals/authentication#oauth-1-0a-2).
You must have a [developer account](/resources/fundamentals/developer-portal) to create a [X app](/resources/fundamentals/developer-apps). You can sign up for one [here](https://developer.x.com/en/portal/petition/essential/basic-info).
You can view and edit your app from the [X app dashboard](https://developer.x.com/content/developer-twitter/en/apps) if you are logged into your X account on developer.x.com.
## Technical
Access tokens are not explicitly expired. An access token will be invalidated if a user explicitly revokes an application in their X account settings, or if X suspends an application. If an application is suspended, there will be a note in the [X app](/resources/fundamentals/developer-apps) dashboard stating that it has been suspended.
Assume a user’s access token *may* become invalid at any time. If this happens, prompt the user to re-authorize the application. Ensuring that this situation is handled gracefully is important for a good user experience.
Many users trust an application to read their information, but not necessarily change their user profile information or post new statuses. Updating information via the X API - be it name, location or adding a new status - requires an HTTP POST. Any API method that requires an HTTP POST is considered a write method and requires read & write access.
# Best practices
Source: https://docs.x.com/fundamentals/authentication/guides/authentication-best-practices
Your API keys and tokens should be guarded very carefully. These credentials are directly tied to your developer App and those X account that have authorized.
Your API keys and tokens should be guarded very carefully.
These credentials are directly tied to your [developer App](/resources/fundamentals/developer-apps) and those X account that have authorized you to make requests on behalf of them. If your keys are compromised, bad actors could use them to make requests to the X endpoints on behalf of your developer App or its authorized users, which could mean their requests might cause you to hit unexpected rate limits, use up your paid access allotment, or even cause your developer App to be suspended.
The following sections include best practices that should be considered when managing your API keys and tokens.
## Regenerate API keys and tokens
In the event that you believe that your API keys has been exposed, you should regenerate your API keys by following these steps:
1. Navigate to the [Developer Console's "Apps" page](https://developer.x.com/en/portal/projects-and-apps.html).
2. Click on the "Keys and tokens" icon (🗝 ) next to the relevant App.
3. Click on the "Regenerate" button next to the set of keys and tokens that you would like to regenerate.
If you would prefer to regenerate your Access Tokens or Bearer Tokens programmatically, you can do so using our authentication endpoints.
* If you would like to regenerate your Access Tokens, you must invalidate your tokens using the [POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) endpoint, then regenerate your tokens using the [3-legged OAuth flow](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens).
* If you would like to regenerate your Bearer Token, you must invalidate your token using the [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) endpoint, then regenerate your token using the [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) endpoint.
## Having a central file for your secrets
Having a file such as .ENV file or any other sort of .yaml file to contain your secrets is an option that could be helpful but be sure to have a strong .gitignore file that can prevent you from accidentally committing these to a git repository.
## Environment variables
Writing code that utilizes environment variables might be helpful.
An example of this is as follows written in Python:
```python theme={null}
import os
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")
```
Inside of your terminal you would want to write something like this:
```bash theme={null}
export CONSUMER_KEY='xxxxxxxxxxxxxxxxxxx'
export CONSUMER_SECRET='xxxxxxxxxxxxxxxxxxxxxxx'
```
## Source code and version control
The most common security mistakes made by developers are having API keys and tokens committed to source code in accessible version control systems like GitHub and BitBucket. Many of these code repositories are publicly accessible. This mistake is made so often in public code repositories that there are lucrative bots that scrape for API keys.
* Use server environment variables. By storing API keys in environment variables, you keep them out of your code and version control. This also allows you to use different keys for different environments easily.
* Use a configuration file excluded from source control. Add the filename to your [.gitignore](https://git-scm.com/docs/gitignore) file to exclude the file from being tracked by version control.
* If you remove the API keys from your code after you have used version control, the API keys are likely still accessible by accessing previous versions of your codebase. Regenerate your API keys, as described in the next section.
## Databases
If you need to store your access tokens in a database, please keep the following in mind:
* Restrict access to the database in a way such that the access tokens are only readable by the owner of the token.
* Restrict edit/write privileges to the database table for access tokens - this should be automated with the key management system.
* Encrypt access tokens before storing in any data stores.
## Password management tools
Password management tools such as 1password or Last Pass can be helpful in keeping your keys and tokens in a secure place. You might want to avoid sharing these inside of a shared team password management tool.
## Web storage & cookies
There are two types of web storage: LocalStorage and SessionStorage. These were created as improvements to using Cookies since the storage capacity for web storage is much higher than Cookie storage. However, there are different pros and cons to each of these storage options.
**Web Storage: LocalStorage**
Anything stored in local web storage is persistent. This means that the data will persist until the data is explicitly deleted. Depending on the needs of your project, you might view this as a positive. However, you should be mindful of using LocalStorage, since any changes/additions to data will be available on all future visits to the webpage in question. We would not usually recommend using LocalStorage, although there may be a few exceptions to this. If you decide to use LocalStorage, it is good to know that it supports the same-origin policy, so all data stored here will only be available via the same origin. An added performance perk of using LocalStorage would be a resulting decrease in client-server traffic since the data does not have to be sent back to the server for every HTTP request.
**Web Storage: SessionStorage**
SessionStorage is similar to LocalStorage, but the key difference is that SessionStorage is not persistent. Once the window (or tab, depending on which browser you are using) that was used to write to SessionStorage is closed, the data will be lost. This is useful in restricting read access to your token within a user session. Using SessionStorage is normally more preferable than LocalStorage when thinking in terms of security. Like LocalStorage, the perks of same-origin policy support and decreased client-server traffic apply to SessionStorage as well.
**Cookies**
Cookies are the more traditional way to store session data. You can set an expiration time for each cookie, which would allow for ease of revocability and restriction of access. However, the client-server traffic would definitely increase when using cookies, since the data is being sent back to the server for every HTTP request. If you decide to use cookies, you need to protect against session hijacking. By default, cookies are sent in plaintext over HTTP, which makes their contents vulnerable to packet sniffing and/or man-in-the-middle attacks where attackers may modify your traffic. You should always enforce HTTPS to protect your data in transit. This will provide confidentiality, integrity (of the data), and authentication. However, if your web application or site is available both through HTTP and HTTPS, you will also want to use the 'Secure' flag on the cookie. This will prevent attackers from being able to send links to the HTTP version of your site to a user and listening in on the resulting HTTP request generated.
Another secondary defense against session hijacking when using cookies would be to validate the user's identity again before any high-impact actions are carried out. One other flag to consider for improving the security of your cookies would be the 'HttpOnly' flag. This flag tells the browser that the cookie in question shall only be accessible from the server specified. Any attempts made by client-side scripts would be forbidden by this flag, therefore helping to protect against most cross-site scripting (XSS) attacks.
# Log in with X
Source: https://docs.x.com/fundamentals/authentication/guides/log-in-with-x
Implement Sign in with X on websites and mobile apps using the OAuth 1.0a request token flow to authenticate users and obtain access tokens.
Use Log in with X, also known as Sign in with X, to place a button on your site or application which allows X users to enjoy the benefits of a registered user account in as little as one click. This works on websites, iOS, mobile, and desktop applications.
## Features
* Ease of use - A new visitor to your site only has to click two buttons in order to log in for the first time.
* X integration - The Log in with X flow can grant authorization to use X APIs on your users' behalf.
* OAuth based - A wealth of client libraries and example code are compatible with the Log in with X API.
## Available for
* Browsers - If your users can access a browser, you can integrate with Log in with X. Learn about the browser sign in flow.
* Mobile devices - Any web-connected mobile device can take advantage of Log in with X. Learn about the mobile sign in flow.
## Implementing Log in with X
The browser and mobile web implementations of Log in with X are based on OAuth. This page demonstrates the requests needed to obtain an access token for the sign in flow.
To use the “Log in with X" flow, please go to your [X app settings](/resources/fundamentals/developer-apps) and ensure that the *"Allow this app to be used to Sign in with X?*” option is enabled.
This page assumes that the reader knows how to sign requests using the OAuth 1.0a protocol. If you want to know how to sign a request, read the [Authorizing a request](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request) page.
If you want to check the signing of the requests on this page, the consumer secret used is: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg. This value is for test purposes and will not work for real requests.
The three steps for implementing Log in with X through obtaining a request token, redirecting a user, and converting a request token into an access token are listed below.
### Step 1: Obtaining a request token
To start a sign-in flow, your [X app](/resources/fundamentals/developer-apps) must obtain a request token by sending a signed message to [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token). The only unique parameter in this request is oauth\_callback, which must be a URL-encoded version of the URL you wish your user to be redirected to when they complete step 2. The remaining parameters are added by the OAuth signing process.
**Note:** Any [callback URL](/resources/fundamentals/developer-apps#callback-urls) that you use with the [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) endpoint will have to be registered within the [X app settings](/resources/fundamentals/developer-apps) in the [Developer Console](/resources/fundamentals/developer-portal).
**Example request (Authorization header has been wrapped):**
```
POST /oauth/request_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization:
OAuth oauth_callback="http%3A%2F%2Flocalhost%2Fsign-in-with-twitter%2F",
oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="ea9ec8429b68d6b77cd5600adbbb0456",
oauth_signature="F1Li3tvehgcraF8DMJ7OyxO4w9Y%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_version="1.0"
```
Your app should examine the HTTP status of the response. Any value other than 200 indicates a failure. The body of the response will contain the oauth\_token, oauth\_token\_secret, and oauth\_callback\_confirmed parameters. Your app should verify that oauth\_callback\_confirmed is true and store the other two values for the next steps.
**Example response (response body has been wrapped):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:06 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 146
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI&
oauth_callback_confirmed=true
```
### Step 2: Redirecting the user
The next step is to direct the user to X so that they may complete the appropriate flow, as described in Browser sign-in flow below. Direct the user to [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate), and the request token obtained in step 1 should be passed as the oauth\_token parameter.
The most seamless way for a website to implement this would be to issue an HTTP 302 redirect as the response to the original “sign in” request. Mobile and desktop apps should open a new browser window or direct to the URL via an embedded web view.
**Example URL to redirect to:**
[https://api.x.com/oauth/authenticate?oauth\_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0](https://api.x.com/oauth/authenticate?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0)
The sign in endpoint will behave in one of three ways depending on the user’s status:
1. **Signed in and approved**: If the user is signed in on x.com and has already approved the calling application, they will be immediately authenticated and returned to the callback URL with a valid OAuth request token. The redirect to x.com is not obvious to the user.
2. **Signed in but not approved**: If the user is signed in to x.com but has not approved the calling application, a request to share access with the calling application will be shown. After accepting the authorization request, the user will be redirected to the callback URL with a valid OAuth request token.
3. **Not signed in**: If the user is not signed in on x.com, they will be prompted to enter their credentials and grant access for the application to access their information on the same screen. Once signed in, the user will be returned to the callback URL with a valid OAuth request token.
Upon a successful authentication, your callback\_url would receive a request containing the oauth\_token and oauth\_verifier parameters. Your application should verify that the token matches the request token received in step 1.
**Request from client’s redirect (querystring parameters wrapped):**
```
GET /sign-in-with-twitter/?
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.5 (KHTML, like Gecko) Chrome/16.0.891.1 Safari/535.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://localhost/sign-in-with-twitter/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
```
### Step 3: Converting the request token to an access token
To render the request token into a usable access token, your application must make a request to the [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) endpoint, containing the oauth\_verifier value obtained in step 2. The request token is also passed in the oauth\_token portion of the header, but this will have been added by the signing process.
**Example request (Authorization header wrapped):**
```
POST /oauth/access_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
oauth_version="1.0"
Content-Length: 57
Content-Type: application/x-www-form-urlencoded
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
```
A successful response contains the oauth\_token, oauth\_token\_secret parameters. The token and token secret should be stored and used for future authenticated requests to the X API. To determine the identity of the user, use [GET account/verify\_credentials](https://dev.x.com/rest/reference/get/account/verify_credentials).
**Example response (response body has been wrapped):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:08 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 157
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4&
oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo
```
### Log in with X Resources
#### Client libraries
The client libraries listed at [X libraries](/resources/tools-and-libraries) will help implement Log in with X. Use the /oauth/authenticate endpoint, as described in the previous steps.
#### Brand Toolkit
X would prefer your application to use the official [X Brand Toolkit](https://about.x.com/en/who-we-are/brand-toolkit) for consistent branding. Save these assets and use them when creating a 'Login with X' button.
The browser log in flow is appropriate for websites and applications which are able to open or embed a web browser. At a very high level:
* The application renders a “Sign in with X” link or button.
* The user clicks the sign in button.
* The current web browser is redirected to X (or a new browser is opened and directed to X).
* The user completes a login and authorization step at X if needed.
* X redirects back to an URL under the application’s control, passing authorization information for the user.
X keeps track of the authorizations, so for users already signed in to X.com who have authorized the application, no UI is shown - instead, they are automatically redirected back to the application.
### Desktop flow
To demonstrate the flows, pretend the website pictured above (“The greatest website ever created”) has implemented this API, as shown by the Sign in with X button on the landing page.
When the user clicks the Sign in button, the page they see depends on whether they are signed in and whether they have previously allowed the application to access their account.
When the user is signed in to x.com but has not granted access, a list of requested permissions, along with Sign In and Cancel buttons are shown.
When the user is not signed in to x.com input fields for a username and password will be shown. Note that even if the user has already granted access to the application, the list of permissions will still be shown.
After the user inputs valid credentials (if needed) and clicks “Sign In”, X will redirect the user to the website which started the sign in flow.
In the case where the user is already signed in to x.com and has granted access to the website, this redirect happens immediately.
The UI flow for mobile web browsers works exactly like the Browser sign in flow, but is optimized for mobile browsers.
Below are screenshots for the signed in, signed out, and redirect screens:
# Connection to X API using TLS
Source: https://docs.x.com/fundamentals/authentication/guides/tls
Connect securely to the X API over TLS 1.2, with guidance on trusted root stores, certificate revocation checks, and HTTPS verification practices.
TLS connections are required in order to access X API endpoints. Communicating over TLS preserves user privacy and security by protecting information between the user and the X API as it travels across the public Internet. Connections to the X API require TLS version 1.2.
## Verification
### Use an up-to-date root store
It's important that your application or library use a trustworthy and up-to-date root store when verifying the X certificate. Where possible, using the root store provided by your operating system may be the simplest approach here. Alternatively, the [Mozilla (NSS) root store](https://www.mozilla.org/en-US/about/governance/policies/security-group/certs/) is well maintained in a public and transparent manner. Curl also provides [a version of this store in PEM format](https://curl.haxx.se/docs/caextract.html).
X currently issues the bulk of our certs from the [DigiCert High Assurance EV Root CA](https://www.digicert.com/digicert-root-certificates.htm), but this is not true for 100% of X-related certificates and may not hold true forever, so trusting only the currently-used Digicert roots may lead to issues with your app in the future.
### Check CRLs and the OCSP status[](#check-crls-and-the-ocsp-status "Permalink to this headline")
Many applications do not check the Certificate Revocation List for returned certificates or rely on the operating system to do so. Ensure that your application or TLS library is configured to force CRL and OCSP (Online Certificate Status Protocol) verification before accepting X’s certificate.
### CDNs[](#cdns "Permalink to this headline")
When showing Tweets that contain media, use the `media_url_https` attribute for the HTTPS URLs to use when showing images. In the future, all URLs served from API endpoints will provide HTTPS paths.
## Provide an indication of security status
If possible, you should show an indication of the current status between your application and X. Some web browsers indicate this by offering a Lock Icon, while others indicate the current connection state with descriptive messaging.
# X API v2 authentication mapping
Source: https://docs.x.com/fundamentals/authentication/guides/v2-authentication-mapping
The following chart illustrates which v2 endpoints map to what authentication methods. Documentation for the X developer platform covering v2 authentication.
The following chart illustrates which v2 endpoints map to what authentication methods.
| | | | |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------- | :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **Endpoint** | **OAuth 1.0a User Context** | **OAuth 2.0** **App Only ** | **OAuth 2.0 Authorization Code with PKCE** |
| [Tweet lookup](/x-api/posts/lookup/introduction)
Scope |
# API Key and Secret
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/api-key-and-secret
Learn what the X API Key and Secret (consumer key and secret) are, how to create them in the Developer Portal, and how to regenerate or rotate them.
### API Key and Secret
The API Key and Secret (also known as Consumer Key and Secret) are the most fundamental credentials required to access the X API. These credentials act as the username and password for your X App, and are used by the X API to understand which App requests are coming from.
These credentials can be used by [authentication endpoints](/resources/fundamentals/authentication/api-reference) to generate additional credentials, such as [user Access Tokens and Secrets](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret), and [Bearer Tokens](/resources/fundamentals/authentication/oauth-2-0/bearer-tokens). You also need to use these credentials along with Access Tokens and other authorization parameters to [authorize requests](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request) that require OAuth 1.0a User Context authentication.
#### How to acquire an API Key and Secret
To acquire a X API Key and Secret, please follow these steps:
1. [Sign up for a X developer account](https://developer.x.com/en/apply-for-access)
2. Create a [X App](/resources/fundamentals/developer-apps) within the [Developer Console](/resources/fundamentals/developer-portal). Note that if you would like to use [X API v2](/x-api/introduction), you must use keys and tokens from a developer App.
When you create your X App, you will be presented with your API Key and Secret, along with a Bearer Token. Please note that we only display these credentials once, so make sure to save them in your password manager or somewhere secure.
We have more recommendations on how to handle your keys and tokens within our [authentication best practices](/resources/fundamentals/authentication/guides/authentication-best-practices) page, including details on what you should do if your credentials have been compromised.
#### How to find and regenerate your API Key and Secret after App creation
If you've already created an App and need to find or regenerate your API Key and Secret, please follow these steps:
1. Navigate to the Developer Console
2. Expand the 'Apps' dropdown in the sidenav
3. Open the App which is associated with the API Key and Secret that you would like to find or regenerate
4. Navigate to the Keys and tokens tab
From there, you will find all of the credentials associated with your App.
#### How to use your API Key and Secret
If you are just exploring the X Developer Platform, we recommend that you use a [tool or library](/resources/tools-and-libraries) to see what’s available on the platform. These tools handle authentication gracefully, and can save you a lot of time and frustration. We specifically recommend [getting started with Postman](/tutorials/postman-getting-started) or [Insomnia](https://insomnia.rest/) for beginner developers.
If you are interested in building a request from scratch, please read our guide on [authorizing an OAuth 1.0a request](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request).
# Authorizing a request
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/authorizing-a-request
Build an OAuth 1.0a Authorization header to sign X API requests, including the consumer key, nonce, signature, timestamp, token, and version fields.
### Authorizing a request
The purpose of this document is to show you how to modify HTTP requests for the purpose of sending authorized requests to the X API.
All of X's APIs are based on the HTTP protocol. This means that any software you write which uses X's APIs sends a series of structured messages to X’s servers. For example, a request to post the text “**Hello Ladies + Gentlemen, a signed OAuth request!**” as a Tweet will look something like this:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
Any HTTP library should be able to generate and issue the above request with a minimum of difficulty. However, the above request is considered invalid, since there is no way of knowing:
1. Which application is making the request
2. Which user the request is posting on behalf of
3. Whether the user has granted the application authorization to post on the user’s behalf
4. Whether the request has been tampered by a third party while in transit
To allow applications to provide this information, X’s API relies on the [OAuth 1.0a protocol](http://tools.ietf.org/html/rfc5849). At a very simplified level, X’s implementation requires that requests needing authorization contain an additional HTTP Authorization header with enough information to answer the questions listed above. A version of the HTTP request shown above, modified to include this header, looks like this (normally the Authorization header would need to be on one line, but has been wrapped for legibility here):
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth\_consumer\_key="xvz1evFS4wEEPTGEFPHBog",
oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth\_signature\_method="HMAC-SHA1",
oauth_timestamp="1318622958",
oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
oauth_version="1.0"
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
When this request was created, it would have been accepted by the X API as valid.
If this signing process sounds like it is beyond the scope of your integration, consider using [Web Intents](https://dev.x.com/web/intents), which do not need to use OAuth to interact with the X API.
**Collecting parameters**
You should be able to see that the header contains 7 key/value pairs, where the keys all begin with the string “oauth\_”. For any given X API request, collecting these 7 values and creating a similar header will allow you to specify authorization for the request. How each value was generated is described below:
**Consumer key**
The oauth\_consumer\_key identifies which application is making the request. Obtain this value from the settings page for your [X app](/resources/fundamentals/developer-apps) in the [Developer Console](/resources/fundamentals/developer-portal).
| | |
| :------------------- | :--------------------- |
| oauth\_consumer\_key | xvz1evFS4wEEPTGEFPHBog |
**Nonce**
The oauth\_nonce parameter is a unique token your application should generate for each unique request. X will use this value to determine whether a request has been submitted multiple times. The value for this request was generated by base64 encoding 32 bytes of random data, and stripping out all non-word characters, but any approach which produces a relatively random alphanumeric string should be OK here.
| | |
| :----------- | :----------------------------------------- |
| oauth\_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
**Signature**
The oauth\_signature parameter contains a value which is generated by running all of the other request parameters and two secret values through a signing algorithm. The purpose of the signature is so that X can verify that the request has not been modified in transit, verify the application sending the request, and verify that the application has authorization to interact with the user’s account.
The process for calculating the oauth\_signature for this request is described in [Creating a signature](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature).
| | |
| :--------------- | :--------------------------- |
| oauth\_signature | tnnArxj06cWHq44gCs1OSKk/jLY= |
**Signature method**
The oauth\_signature\_method used by X is HMAC-SHA1. This value should be used for any authorized request sent to X’s API.
| | |
| :----------------------- | :-------- |
| oauth\_signature\_method | HMAC-SHA1 |
**Timestamp**
The oauth\_timestamp parameter indicates when the request was created. This value should be the number of seconds since the Unix epoch at the point the request is generated, and should be easily generated in most programming languages. X will reject requests which were created too far in the past, so it is important to keep the clock of the computer generating requests in sync with NTP.
| | |
| :--------------- | :--------- |
| oauth\_timestamp | 1318622958 |
**Token**
The oauth\_token parameter typically represents a user’s permission to share access to their account with your application. There are a few authentication requests where this value is not passed or is a different form of token, but those are covered in detail in [Obtaining access tokens](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens). For most general-purpose requests, you will use what is referred to as an **access token**.
You can generate a valid [access token](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) for your account on the settings page for your [X app](/resources/fundamentals/developer-apps) on the [Developer Console](/resources/fundamentals/developer-portal).
| | |
| :----------- | :------------------------------------------------- |
| oauth\_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
**Version**
The oauth\_version parameter should always be 1.0 for any request sent to the X API.
| | |
| :------------- | :-- |
| oauth\_version | 1.0 |
#### Building the header string
To build the header string, imagine writing to a string named DST.
1. Append the string “OAuth ” (including the space at the end) to DST.
2. For each key/value pair of the 7 parameters listed above:
1. [Percent encode](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) the key and append it to DST.
2. Append the equals character ‘=’ to DST.
3. Append a double quote ‘”’ to DST.
4. [Percent encode](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) the value and append it to DST.
5. Append a double quote ‘”’ to DST.
6. If there are key/value pairs remaining, append a comma ‘,’ and a space ‘ ‘ to DST.
Pay particular attention to the percent encoding of the values when building this string. For example, the oauth\_signature value of tnnArxj06cWHq44gCs1OSKk/jLY= must be encoded as tnnArxj06cWHq44gCs1OSKk%2FjLY%3D.
Performing these steps on the parameters collected above results in the following string:
```
OAuth oauth\_consumer\_key="xvz1evFS4wEEPTGEFPHBog", oauth\_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg", oauth\_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth\_signature\_method="HMAC-SHA1", oauth\_timestamp="1318622958", oauth\_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0"
```
This value should be set as the Authorization header for the request.
# Creating a signature
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/creating-a-signature
Generate an OAuth 1.0a HMAC-SHA1 signature for X API requests by collecting parameters, building the signature base string, and signing with your keys.
### Creating a signature
This page explains how to generate an OAuth 1.0a HMAC-SHA1 signature for an HTTP request. This signature will be suitable for passing to the X API as part of an authorized request, as described in [authorizing a request.](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request)
The request used to demonstrate signing is a POST to [https://api.x.com/1.1/statuses/update.json](https://api.x.com/1.1/statuses/update.json). The raw request looks like this:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
**Collecting the request method and URL**
To produce a signature, start by determining the HTTP method and URL of the request. These two are known when creating the request, so they are easy to obtain.
The request method will almost always be GET or POST for X API requests.
| | |
| :---------- | :--- |
| HTTP Method | POST |
The base URL is the URL to which the request is directed, minus any query string or hash parameters. It is important to use the correct protocol here, so make sure that the “https\://” portion of the URL matches the actual request sent to the API.
| | |
| :------- | :--------------------------------------------------------------------------------------- |
| Base URL | [https://api.x.com/1.1/statuses/update.json](https://api.x.com/1.1/statuses/update.json) |
#### Collecting parameters
Next, gather all of the parameters included in the request. There are two such locations for these additional parameters - the URL (as part of the query string) and the request body. The sample request includes a single parameter in both locations:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
An HTTP request has parameters that are URL encoded, but you should collect the raw values. In addition to the request parameters, every oauth\_\* parameter needs to be included in the signature, so collect those too. Here are the parameters from [authorizing a request](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request):
| | |
| :----------------------- | :------------------------------------------------- |
| status | Hello Ladies + Gentlemen, a signed OAuth request! |
| include\_entities | true |
| oauth\_consumer\_key | xvz1evFS4wEEPTGEFPHBog |
| oauth\_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
| oauth\_signature\_method | HMAC-SHA1 |
| oauth\_timestamp | 1318622958 |
| oauth\_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
| oauth\_version | 1.0 |
These values need to be encoded into a single string, which will be used later on. The process to build the string is very specific:
1. [Percent encode](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) every key and value that will be signed.
2. Sort the list of parameters alphabetically [\[1\]](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature) by encoded key [\[2\]](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature).
3. For each key/value pair:
4. Append the encoded key to the output string.
5. Append the ‘=’ character to the output string.
6. Append the encoded value to the output string.
7. If there are more key/value pairs remaining, append a ‘&’ character to the output string.
\[1] The OAuth spec says to sort lexicographically, which is the default alphabetical sort for many libraries.
\[2] In the case of two parameters with the same encoded key, the OAuth spec says to continue sorting based on value. However, X does not accept duplicate keys in API requests
**Parameter string**
The following *parameter string* will be produced by repeating these steps with the parameters collected above:
| status | Hello Ladies + Gentlemen, a signed OAuth request! |
| :----------------------- | :------------------------------------------------- |
| `include_entities` | true |
| `oauth_consumer_key` | xvz1evFS4wEEPTGEFPHBog |
| `oauth_nonce` | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
| `oauth_signature_method` | HMAC-SHA1 |
| `oauth_timestamp` | 1318622958 |
| `oauth_token` | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
| `oauth_version` | 1.0 |
#### Creating the signature base string
The three values collected so far must be joined to make a single string, from which the signature will be generated. This is called the **signature base string** by the OAuth specification.
To encode the HTTP method, base URL, and parameter string into a single string:
1. Convert the HTTP Method to uppercase and set the output string equal to this value.
2. Append the ‘&’ character to the output string.
3. [Percent encode](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) the URL and append it to the output string.
4. Append the ‘&’ character to the output string.
5. [Percent encode](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) the parameter string and append it to the output string.
This will produce the following *signature base string*:
```
POST&https%3A%2F%2Fapi.x.com%2F1.1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521
```
Make sure to percent encode the parameter string. The signature base string should contain exactly 2 ampersand ‘&’ characters. The percent ‘%’ characters in the parameter string should be encoded as %25 in the signature base string.
#### Getting a signing key
The last pieces of data to collect are secrets which identify the [X app](/resources/fundamentals/developer-apps) making the request, and the user the request is on behalf of. It is very important to note that these values are incredibly sensitive and should never be shared with anyone.
The value which identifies your app to X is called the **consumer secret** and can be found in the [Developer Console](/resources/fundamentals/developer-portal) by viewing the [app details page](/resources/fundamentals/developer-apps). This will be the same for every request your X app sends.
| | |
| :-------------- | :------------------------------------------ |
| Consumer secret | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw |
The value which identifies the account your application is acting on behalf of is called the **OAuth token secret**. This value can be obtained in several ways, all of which are described in [obtaining access tokens](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens).
| | |
| :----------------- | :---------------------------------------- |
| OAuth token secret | LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
Once again, it is very important to keep these values private to your application. If you feel that your values have been compromised, regenerate your tokens (the tokens on this page have been marked as invalid for real requests).
Both of these values need to be combined to form a **signing key** which will be used to generate the signature. The signing key is simply the [percent encoded](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) token secret:
Note that there are some flows, such as when obtaining a [request token](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens), where the token secret is not yet known. In this case, the signing key should consist of the [percent encoded](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) **consumer secret** followed by an ampersand character ‘&’.
| | |
| :---------- | :------------------------------------------------------------------------------------- |
| Signing key | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw\&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
#### Calculating the signature
Finally, the signature is calculated by passing the signature base string and signing key to the HMAC-SHA1 hashing algorithm. The details of the algorithm are explained as hash\_hmac function.
The output of the HMAC signing function is a binary string. This needs to be base64 encoded to produce the signature string. For example, the output given the base string and signing key given on this page is 2E CF 77 84 98 99 6D 0D DA 90 5D C7 17 7C 75 07 3F 3F CD 4E. That value, when converted to base64, is the OAuth signature for this request:
| | |
| :-------------- | :--------------------------- |
| OAuth signature | Ls93hJiZbQ3akF3HF3x1Bz8/zU4= |
# OAuth Echo
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/oauth-echo
Use OAuth Echo to securely delegate X authentication to a third party media provider for uploads using x-auth-service-provider and verify-credentials headers.
### OAuth Echo
OAuth Echo is a means to securely delegate OAuth authorization with a third party while interacting with an API.
There are four parties involved in this interaction:
* **the User** who is using X through a particular, authorized X application
* **the Consumer**, or the X application that is attempting to interact with the 3rd party media provider (e.g. the photo-sharing site)
* **the Delegator**, or the 3rd party media provider
* **the Service Provider** a.k.a. X itself
Essentially, prepare a request for the delegator to send to the X API on behalf of an application and a user. Add what would otherwise be a signed OAuth request into an HTTP header and ask the delegator to send that request to X after completing the intermediary operation.
Here’s an example: the User wants to upload a photo. The Consumer is going to call upload on the Delegator with a POST. The POST should contain the image, but it should also contain two additional items as HTTP headers:
* `x-auth-service-provider` — effectively, this is the realm that identity delegation should be sent to — in the case of X, set this to [https://api.x.com/1.1/account/verify\_credentials.json](https://api.x.com/1.1/account/verify_credentials.json). iOS5-based X integrations will add an additional application\_id parameter to this URL that will also be used to calculate the oauth\_signature used in x-verify-credentials-authorization.
* `x-verify-credentials-authorization` — Consumer should create all the OAuth parameters necessary so it could call [https://api.x.com/1.1/account/verify\_credentials.json](https://api.x.com/1.1/account/verify_credentials.json) using OAuth in the HTTP header (e.g. it should look like OAuth oauth\_consumer\_key=”...”, oauth\_token=”...”, oauth\_signature\_method=”...”, oauth\_signature=”...”, oauth\_timestamp=”...”, oauth\_nonce=”...”, oauth\_version=”...” ).
Keep in mind that the entire transaction period needs to occur within an amount of time where the `oauth_timestamp` will still be valid.
Alternatively, instead of sending these two parameters in the header, they could be sent in the POST as x\_auth\_service\_provider and x\_verify\_credentials\_authorization — in this case, remember to escape and include the parameters in the OAuth signature base string — similar to encoding parameters in any request. It’s best to use HTTP headers to keep the operations as separate as possible.
The Delegator’s goal, at this point, is to verify that the User is who they say they are before it saves the media. Once the Delegator receives all the data above via its upload method, it should temporarily store the image, and then construct a call to the endpoint specified in the x-auth-service-provider header — in this case, [https://api.x.com/1.1/account/verify\_credentials.json](https://api.x.com/1.1/account/verify_credentials.json), using the same OAuth authentication header provided by the Consumer in the x-verify-credentials-authorization header.
#### OAuth Echo best practices
Use the URL provided by `x-auth-service-provider` to perform the lookup, *not* a hard-coded value. Apple iOS, for example, adds an additional application\_id parameter to all OAuth requests, and its existence should be maintained at each stage of OAuth Echo.
For the OAuth authorization portion, take the header value in x-verify-credentials-authorization, and place that into its own Authorization header for its call to the service provider. For good measure, confirm that the value in `x-auth-service-provider` is what it should be.
* If the Service Provider returns an HTTP 200, then good. The Delegator should permanently store the image, generate a URL, and return it.
* If the Service Provider doesn’t return an HTTP 200, then dump the image, and then return an error back to the Consumer.
# Obtaining Access Tokens using 3-legged OAuth flow
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens
Walk through the 3-legged OAuth 1.0a flow to obtain user access tokens for the X API using request_token, authorize, and access_token endpoints.
### Obtaining access tokens using 3-legged OAuth flow
To perform actions on behalf of another user, you'll need to obtain their access tokens. Access tokens specify the X account the request is made on behalf of, so for you to obtain these they will need to first grant you access. These tokens do not expire but can be revoked by the user at any time.
X allows you to obtain user access tokens through the 3-legged OAuth flow, which allows your application to obtain an **access token** and access token secret by redirecting a user to X and having them authorize your application. This flow is almost identical to the flow described in [implementing Log in with X](/resources/fundamentals/authentication/guides/log-in-with-x), with two exceptions:
* The [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) endpoint is used instead of [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate).
* The user will **always** be prompted to authorize access to your application, even if access was previously granted.
Before you get started, you will need to check your [application's](/resources/fundamentals/developer-apps) permissions and know the consumer keys and callback URL. If you don't have a callback URL or publicly accessible UI, consider using [PIN-based authorization](/resources/fundamentals/authentication/oauth-1-0a/pin-based-oauth), which is intended for applications that cannot access or embed a web browser in order to redirect the user after authorization.
The possible states for the 3-legged sign in interaction are illustrated in the following flowchart:

#### Overview of the process
At a high level, the 3-Legged OAuth process will:
1. Create a request for a consumer application to obtain a request token.
2. Have the user authenticate, and send the consumer application a request token.
3. Convert the request token into a usable user access token.
**Terminology clarification**
In the guide below, you may see different terms referring to the same thing.
**Client credentials:**
* App Key === API Key === Consumer API Key === Consumer Key === Customer Key === `oauth_consumer_key`
* App Key Secret === API Secret Key === Consumer Secret === Consumer Key === Customer Key === `oauth_consumer_secret`
* Callback URL === `oauth_callback`
**Temporary credentials:**
* Request Token === `oauth_token`
* Request Token Secret === `oauth_token_secret`
* oauth\_verifier
**Token credentials:**
* Access token === Token === resulting `oauth_token`
* Access token secret === Token Secret === resulting `oauth_token_secret`
#### Walkthrough steps
**Step 1: [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token)**
Create a request for a consumer application to obtain a request token.
The only unique parameter in this request is oauth\_callback, which must be a [URL encoded](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters) version of the URL you wish your user to be redirected to when they complete step 2. The remaining parameters are added by the OAuth signing process.
Please note - any callback URL that you use with the [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) endpoint will have to be configured within your [developer App's](/resources/fundamentals/developer-apps) settings in the app details page of Developer Console.
**Request includes:**
`oauth_callback="https%3A%2F%2FyourCallbackUrl.com"`
`oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w" `
Your app should examine the HTTP status of the response. Any value other than 200 indicates a failure. The body of the response will contain the `oauth_token`, `oauth_token_secret`, and `oauth_callback_confirmed` parameters. Your app should verify that `oauth_callback_confirmed` is true and store the other two values for the next steps.
**Response includes**
`oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
`oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI`
`oauth_callback_confirmed=true`
**Step 2: [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize)**
Have the user authenticate, and send the consumer application a request token.
**Example URL to redirect user to:**
`https://api.x.com/oauth/authorize?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
Upon successful authentication, your `callback_url` would receive a request containing the `oauth_token` and `oauth_verifier` parameters. Your application should verify that the token matches the request token received in step 1.
**Request from client’s redirect:**
`https://yourCallbackUrl.com?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY`
**Step 3: [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token)**
Convert the request token into a usable access token.
To render the request token into a usable access token, your application must make a request to the [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) endpoint, containing the `oauth_verifier` value obtained in step 2. The request token is also passed in the `oauth_token` portion of the header, but this will have been added by the signing process.
**Request includes:**
`POST /oauth/access_token`
`oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w`
`oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
`oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY`
A successful response contains the `oauth_token`, `oauth_token_secret` parameters. The token and token secret should be stored and used for future authenticated requests to the X API. To determine the identity of the user, use [GET account/verify\_credentials](/resources/fundamentals/authentication/api-reference).
**Response includes:**
`oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4`
`oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo`
**Using these credentials for OAuth 1.0a (application-user) required requests**
Now you've obtained the user access tokens; you can use them to access certain APIs such as [POST statuses/update](/x-api/posts/manage-tweets/introduction) to create Tweets on the users' behalf.
**Request includes:**
`POST statuses/update.json`
`oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w`
`oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4`
#### Sample use case
The standard flow is web-based and uses the 3-legged authorization OAuth flow. The screenshots outlined here are part of a sample that you can view the source of at [https://github.com/xdevplatform/twauth-web](https://github.com/xdevplatform/twauth-web).
At some point in your application, you will want to redirect to X in order to authorize your application.
When you redirect to X with the request token, the user will be prompted to authorize your application.
Upon authorizing your application, the user will be redirected to the callback URL provided when you generated the request token. You will use this to obtain the permanent access token for this user and store it locally.
# OAuth 1.0a
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/overview
Overview of OAuth 1.0a user context authentication on X, covering API keys, access tokens, request signing, and tools for making authorized API calls.
## OAuth 1.0a
Many endpoints on the X developer platform use the OAuth 1.0a method to act, or make API requests, on behalf of a X account. For example, if you have a X developer app, you can make API requests on behalf of any X account as long as that user authenticates your app.
Please note: if you aren’t familiar with concepts such as HMAC-SHA1 and percent encoding, we recommend that you check out the "useful tools" section below that lists some API clients that greatly simplify the authentication process.
### Key concepts
#### Signing a request with keys and tokens
You have to sign each API request by passing several generated keys and tokens in an authorization header. To start, you can generate several keys and tokens in your [X developer app’s](/resources/fundamentals/developer-apps) details page, including the following:
| | |
| :------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| API key and secret:
`oauth_consumer_key`
`oauth_consumer_secret` | Think of these as the user name and password that represents your X developer app when making API requests. |
| Access token and secret:
`oauth_token`
`oauth_token_secret` | An access token and access token secret are user-specific credentials used to authenticate OAuth 1.0a API requests. They specify the X account the request is made on behalf of.
You can generate your own access token and token secret if you would like your app to make requests on behalf of the same X account associated with your developer account on the [X developer app's](/resources/fundamentals/developer-apps) details page.
If you'd like to generate access tokens for a different user, see "Making requests on behalf of users" below. |
#### Making requests on behalf of users
When creating a signature, you need a set of access tokens that represent the user that you are going to make a request on behalf of.
You can generate a set of access tokens that represents the X account that owns the X developer app from the [app’s details page,](https://developer.x.com/content/developer-twitter/en/apps) but if you are wanting to make a request on behalf of a different X account, that account’s owner must grant access to you by signing in to their account as part of the [3-legged OAuth flow](/resources/fundamentals/authentication#obtaining-access-tokens-using-3-legged-oauth-flow). The output of this process is a set of access tokens (oauth\_token and oauth\_token\_secret) that can be used to make an OAuth 1.0a request.
Once you have these keys and tokens, you can either [create a signature](/resources/fundamentals/authentication#creating-a-signature) from scratch. We don't recommend this unless you know what you are doing, or if you're using one of the tools mentioned below to make a request to an endpoint that requires OAuth 1.0a.
For reference, here is an example of a signed cURL request with all of the generated tokens passed in an authorization header:
```bash theme={null}
curl --request POST \
--url 'https://api.x.com/1.1/statuses/update.json?status=Hello%20world' \
--header 'authorization: OAuth oauth_consumer_key="CONSUMER_API_KEY", oauth_nonce="OAUTH_NONCE", oauth_signature="OAUTH_SIGNATURE", oauth_signature_method="HMAC-SHA1", oauth_timestamp="OAUTH_TIMESTAMP", oauth_token="ACCESS_TOKEN", oauth_version="1.0"' \
```
**Note:** User access tokens are sensitive and should be guarded very carefully. When access tokens are generated, the user they represent is trusting your application to keep them secure. If the security of both API keys and user access tokens are compromised, your application would potentially expose access to private information and account functionality. We encourage you to learn more about [securing keys and access tokens](/resources/fundamentals/developer-apps).
### Useful tools
The process of [signing a request](/resources/fundamentals/authentication#creating-a-signature) is complicated. We recommend that you use an API client library that automatically generates a lot of the authentication token:
| | |
| :------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Postman](https://www.getpostman.com/) | An API client that lets you build and send REST API requests. Read our “[Getting started with Postman](/tutorials/postman-getting-started)” tutorial to learn more about this tool. |
| [Insomnia](https://insomnia.rest/) | Insomnia is a REST API Client with cookie management, environment variables, code generation, and authentication for Mac, Window, and Linux. |
# Percent encoding parameters
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters
Apply RFC 3986 percent encoding to OAuth 1.0a parameters for X API requests, with rules for reserved characters and worked URL encoding examples.
### Percent encoding parameters
Parts of the X API, particularly those dealing with OAuth signatures, require strings to be encoded according to [RFC 3986, Section 2.1](http://tools.ietf.org/html/rfc3986#section-2.1). Since many implementations of URL encoding algorithms are not fully compatible with RFC 3986, bad encodings are a cause of many OAuth signature errors. For this reason, the exact signing algorithm to use is covered on this page.
This page covers the URL encoding process described in [RFC 3986, Section 2.1](http://tools.ietf.org/html/rfc3986#section-2.1). We encourage you to reference that specification in case of any ambiguity or conflict with this document.
#### Encoding a string
The following algorithm assumes you are encoding a string SRC by copying its values byte-by-byte to a string DST.
**Step 1: While SRC contains unread bytes, read the next byte (8 bits) from SRC.** Typically, this is considered a character, but in the case of encodings where a character may be more than one byte (such as UTF-8), just read the first byte.
**Step 2: Check whether the read byte matches any of the following ASCII equivalents.** The following table has been broken down into rows for legibility, but you only need to determine whether the read byte exists in the table at all, not the specific row.
| Name | ASCII characters | Equivalent byte values |
| :------------------ | :------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Digits | ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ | 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 |
| Uppercase letters | ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’ | 0x41, 0x42, 0x43, 0x44, 0x45,0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51,0x52, 0x53, 0x54, 0x55, 0x56, 0x57,0x58, 0x59, 0x5A |
| Lowercase letters | ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’ | 0x61, 0x62, 0x63, 0x64, 0x65,0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B,0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71,0x72, 0x73, 0x74, 0x75, 0x76, 0x77,0x78, 0x79, 0x7A |
| Reserved characters | ‘-‘, ‘.’, ‘\_’, ‘\~’ | 0x2D, 0x2E, 0x5F, 0x7E |
**Step 2b: If the byte is not listed in the above table, continue.** Any other value must be encoded. **Step 2a: If the byte is listed in the above table, copy it into DST and go back to Step 1.** Characters listed in the above table do not need to be escaped, so you will just copy the byte directly.
**Step 3: Write the character ‘%’ to DST.** The percent character ‘%’ (or 0x25 in hex and 00100101 in binary) indicates that the next two bytes will represent an encoded byte.
**Step 4: Write two characters representing the uppercase ASCII-encoded hex value of the current byte to DST.** This is a bit confusing, so here is an example. Pretend the current byte is 0xE6 (11100110 in binary). This corresponds with the UTF-8 encoded value of ‘æ’. To encode this value, write the character ‘E’ (0x45, from the table above) and then the character ‘6’ (0x36) to DST. The last three characters are written should have been “%E6”. Note that if you write a letter such as A,B,C,D,E or F, you must use the uppercase character.
**Step 5: Return to Step 1.** Keep going until the entirety of SRC is copied to DST.
#### Examples
The following examples may be helpful to compare with the output of your own code. You should consider any differences an error. Spaces encoded as “+” characters are an example of incorrect encoding.
| Original string | Encoded string |
| :----------------- | :-------------------------- |
| Ladies + Gentlemen | Ladies%20%2B%20Gentlemen |
| An encoded string! | An%20encoded%20string%21 |
| Dogs, Cats & Mice | Dogs%2C%20Cats%20%26%20Mice |
| ☃ | %E2%98%83 |
# PIN-based authorization
Source: https://docs.x.com/fundamentals/authentication/oauth-1-0a/pin-based-oauth
Use the PIN-based OAuth flow for X apps that cannot embed a browser, like CLI tools and game consoles, by entering a numeric PIN as the oauth_verifier.
### PIN-based authorization
The PIN-based OAuth flow is a version of the [3-legged OAuth](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) process and is intended for applications that cannot access or embed a web browser to redirect the user after authorization. Examples of such applications would be command-line applications, embedded systems, game consoles, and certain types of mobile apps.
PIN-based OAuth flow is initiated by an app in the `request_token` with the `oauth_callback` set to `oob`. The term `oob` means out-of-band OAuth. The user still visits X to login or authorize the app, but they will not be automatically redirected to the application upon approving access. Instead, they will see a numerical PIN code, with instructions to return to the application and enter this value.
**Note:** The `callback_url` within the X app settings is still required, even when using PIN-based auth.
#### Implementing the PIN-based OAuth flow
The PIN-based flow is implemented in the same way as [3-legged authorization](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) (and [Sign in with X](/resources/fundamentals/authentication#log-in-with-x)), with the following differences:
1. The value for `oauth_callback` must be set to `oob` during the [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) call.
2. After the user is sent to X to authorize your app using either a [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) or [GET oauth/authorize URL](/resources/fundamentals/authentication/api-reference#get-oauth-authorize), they will not be redirected to your `callback_url`, instead they will see a screen with a X generated \~7 digit PIN with directions to enter the PIN into your applications name.
3. The user enters this PIN into your application, and your application uses the PIN number as the `oauth_verifier` in the [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) to obtain an access\_token.
**Note:** PIN numbers are not reusable, and the `access_token` obtained should be used for application-user requests.
# App only authentication and OAuth 2.0 Bearer Token
Source: https://docs.x.com/fundamentals/authentication/oauth-2-0/application-only
Authenticate X API requests with OAuth 2.0 App-Only Bearer Tokens for server-to-server, read-only access to public data without a user context.
### App only authentication and OAuth 2.0 Bearer Token
X offers applications the ability to issue authenticated requests on behalf of the application itself, as opposed to on behalf of a specific user. X's implementation is based on the [Client Credentials Grant](http://tools.ietf.org/html/rfc6749#section-4.4) flow of the [OAuth 2 specification](http://tools.ietf.org/html/rfc6749).
Application-only authentication doesn't include any user-context and is a form of authentication where an application makes API requests on its own behalf. This method is for developers that just need read-only access to public information.
You can do application-only authentication using your apps consumer API keys, or by using an App only Access Token (Bearer Token). This means that the only requests you can make to a X API must not require an authenticated user.
With application-only authentication, you can perform actions such as:
* Pull user timelines
* Access friends and followers of any account
* Access lists resources
* Search Tweets
Please note that only [OAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret) or [OAuth 2.0 Authorization Code Flow](/resources/fundamentals/authentication/oauth-2-0/authorization-code) with PKCE is required to issue requests on behalf of users. The [API reference](/resources/fundamentals/authentication/api-reference) page describes the authentication method required to use an API. You will need user-authentication, user-context, with an [access token](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) to perform the following:
* Post Tweets or other resources
* Search for users
* Use any geo endpoint
* Access Direct Messages or account credentials
* Retrieve user's email addresses
#### Auth Flow
To use this method, you need to use a [App only Access Token](/resources/fundamentals/authentication/oauth-2-0/application-only)(also known as [Bearer Token](/resources/fundamentals/authentication/oauth-2-0/bearer-tokens)). You can generate an App only Access Token (Bearer Token) by passing your consumer key and secret through the [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) endpoint.
The application-only auth flow follows these steps:
* An application encodes its consumer key and secret into a specially encoded set of credentials.
* An application makes a request to the [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) endpoint to exchange these credentials for an [App only Access Token](/resources/fundamentals/authentication/oauth-2-0/application-only).
* When accessing the REST API, the application uses the App only Access Token to authenticate.
Because there is no need to sign a request, this approach is much simpler than the standard OAuth 1.0a model.
#### About application-only auth
**Tokens are passwords**
Keep in mind that the consumer key & secret and the App only Access Token (Bearer Token) itself grant access to make requests on behalf of an application. These values should be considered as sensitive as passwords, and must not be shared or distributed to untrusted parties.
**SSL required**
All requests (both to obtain and use the tokens) *must* use HTTPS endpoints. Follow the best practices detailed in [Connecting to X API using TLS](/resources/fundamentals/authentication/guides/tls) — peers should **always** be verified.
**No user-context**
When issuing requests using application-only auth, there is no concept of a "current user". Therefore, endpoints such as [POST statuses/update](/x-api/posts/creation-of-a-post) will not function with application-only auth. See [using OAuth](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) for more information for issuing requests on behalf of a user.
**Rate limiting**
Applications have two kinds of rate limiting pools.
Requests made on behalf of users with access tokens, also known as user-context, depletes from a different rate limiting context than that used in application-only authentication. So, in other words, requests made on behalf of users will not deplete from the rate limits available through app-only auth, and requests made through app-only auth will not deplete from the rate limits used in user-based auth.
Read more about [API Rate Limiting](/x-api/fundamentals/rate-limits) and [review the limits](https://developer.x.com/en/portal/products).
#### Issuing application-only requests
**Step 1: Encode consumer key and secret**
The steps to encode an application’s consumer key and secret into a set of credentials to obtain a Bearer Token are:
1. URL encode the consumer key and consumer secret according to [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Note that at the time of writing, this will not actually change the consumer key and secret, but this step should still be performed in case the format of those values changes in the future.
2. Concatenate the encoded consumer key, a colon character ":", and the encoded consumer secret into a single string.
3. [Base64 encode](http://en.wikipedia.org/wiki/Base64) the string from the previous step.
Below are example values showing the result of this algorithm. Note that the consumer secret used in this page is for test purposes and will not work for real requests.
| | |
| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------ |
| Consumer key | xvz1evFS4wEEPTGEFPHBog |
| Consumer secret | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| RFC 1738 encoded consumer
secret (does not change) | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| Bearer Token credentials | xvz1evFS4wEEPTGEFPHBog:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| Base64 encoded Bearer Token credentials | :: eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw== |
**Step 2: Obtain an App only Access Token (Bearer Token)**
The value calculated in step 1 must be exchanged for an App only Access Token by issuing a request to [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token):
* The request must be an HTTP POST request.
* The request must include an `Authorization` header with the value of `Basic .`
* The request must include a `Content-Type` header with the value of `application/x-www-form-urlencoded;charset=UTF-8.`
* The body of the request must be `grant_type=client_credentials`.
**Example request (Authorization header has been wrapped):**
```json theme={null}
POST /oauth2/token HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant\_type=client\_credentials
```
If the request was formatted correctly, the server would respond with a JSON-encoded payload:
**Example response:**
```json theme={null}
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token\_type":"bearer","access\_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
```
Applications should verify that the value associated with the `token_type` key of the returned object is `bearer`. The value associated with the `access_token` key is the App only Access Token (Bearer Token).
Note that one App only Access Token is valid for an application at a time. Issuing another request with the same credentials to `/oauth2/token` will return the same token until it is invalidated.
**Step 3: Authenticate API requests with the App only Access Token (Bearer Token)**
The App only Access Token (Bearer Token) may be used to issue requests to API endpoints that support application-only auth. To use the App Access Token, construct a normal HTTPS request and include an `Authorization` header with the value of `Bearer . Signing is not required.`
**Example request (Authorization header has been wrapped):**
```
GET /1.1/statuses/user\_timeline.json?count=100&screen\_name=twitterapi HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAA
AAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Accept-Encoding: gzip
```
**Invalidating an App only Access Token (Bearer Token)**
Should an App only Access Token become compromised or need to be invalidated for any reason, issue a call to [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token).
**Example request (Authorization header has been wrapped):**
```bash theme={null}
POST /oauth2/invalidate_token HTTP/1.1
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==
User-Agent: My X App v1.0.23
Host: api.x.com
Accept: */*
Content-Length: 119
Content-Type: application/x-www-form-urlencoded
access_token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
```
**Example response:**
```json theme={null}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 127
...
{"access_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
```
#### Common error cases
This section describes some common mistakes involved in the negotiation and use of Bearer Tokens. Be aware that not all possible error responses are covered here - be observant of unhandled error codes and responses.
**Invalid requests to obtain or revoke an App only Access Token**
Attempts to:
* Obtain an App only Access Token (Bearer Token) with an invalid request (for example, leaving out `grant_type=client_credentials`).
* Obtain or revoke an App only Access Token (Bearer Token) with incorrect or expired app credentials.
* Invalidate an incorrect or revoked App only Access Token (Bearer Token).
* Obtain an App only Access Token (Bearer Token) too frequently in a short period of time.
Will result in:
```json theme={null}
HTTP/1.1 403 Forbidden
Content-Length: 105
Content-Type: application/json; charset=utf-8
...
{"errors":\[{"code":99,"label":"authenticity\_token\_error","message":"Unable to verify your credentials"}\]}
```
#### API request contains invalid App only Access Token (Bearer Token)
Using an incorrect or revoked Access Token to make API requests will result in:
```json theme={null}
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 61
...
{"errors":\[{"message":"Invalid or expired token","code":89}\]}
```
#### App only Access Token (Bearer Token) used on endpoint which doesn't support application-only auth
Requesting an endpoint which requires a user context (such as `statuses/home_timeline`) with an App only Access Token (Bearer Token) will produce:
```json theme={null}
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 91
...
{"errors":\[{"message":"Your credentials do not allow access to this resource","code":220}\]}
```
# OAuth 2.0 Authorization Code Flow with PKCE
Source: https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code
Reference for the X OAuth 2.0 Authorization Code Flow with PKCE, covering scopes, refresh tokens, confidential clients, and access token lifetimes.
### OAuth 2.0 Authorization Code Flow with PKCE
#### Introduction
OAuth 2.0 is an industry-standard authorization protocol that allows for greater control over an application’s scope, and authorization flows across multiple devices. OAuth 2.0 allows you to pick specific fine-grained scopes which give you specific permissions on behalf of a user.
To enable OAuth 2.0 in your App, you must enable it in your App’s authentication settings found in the App settings section of the Developer Console.
#### How long will my credentials stay valid?
By default, the access token you create through the Authorization Code Flow with PKCE will only stay valid for two hours unless you’ve used the `offline.access` scope.
#### Refresh tokens
Refresh tokens allow an application to obtain a new access token without prompting the user via the refresh token flow.
If the scope `offline.access` is applied an OAuth 2.0 refresh token will be issued. With this refresh token, you obtain an access token. If this scope is not passed, we will not generate a refresh token.
An example of the request you would make to use a refresh token to obtain a new access token is as follows:
```bash theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ
```
#### App settings
You can select your App’s authentication settings to be OAuth 1.0a or OAuth 2.0. You can also enable an App to access both OAuth 1.0a and OAuth 2.0.
OAuth 2.0 can be used with the X API v2 only. If you have selected OAuth 2.0 you will be able to see a Client ID in your App’s Keys and Tokens section.
#### Confidential clients
[Confidential clients](https://datatracker.ietf.org/doc/html/rfc6749#section-2.1) can hold credentials in a secure way without exposing them to unauthorized parties and securely authenticate with the authorization server they keep your client secret safe. Public clients as they’re usually running in a browser or on a mobile device and are unable to use your client secrets. If you select a type of App that is a confidential client, you will be provided with a client secret.
If you selected a type of client that is a confidential client in the Developer Console, you will also be able to see a Client Secret. Your options are Native App, Single page App, Web App, Automated App, or bot. Native App and Single page Apps are public clients and Web App and Automated App or bots are confidential clients.
You don’t need client id for confidential clients with a valid Authorization Header. You still are required to include Client Id in the body for the requests with a public client.
#### Scopes
Scopes allow you to set granular access for your App so that your App only has the permissions that it needs. To learn more about what scopes map to what endpoints, view our [authentication mapping guide](/resources/fundamentals/authentication/guides/v2-authentication-mapping).
| | |
| :------------------- | :----------------------------------------------------------------------------------------------------------- |
| **Scope** | **Description** |
| tweet.read | All the Tweets you can view, including Tweets from protected accounts. |
| tweet.write | Tweet and Retweet for you. |
| tweet.moderate.write | Hide and unhide replies to your Tweets. |
| users.email | Email from an authenticated user. |
| users.read | Any account you can view, including protected accounts. |
| follows.read | People who follow you and people who you follow. |
| follows.write | Follow and unfollow people for you. |
| offline.access | Stay connected to your account until you revoke access. |
| space.read | All the Spaces you can view. |
| mute.read | Accounts you’ve muted. |
| mute.write | Mute and unmute accounts for you. |
| like.read | Tweets you’ve liked and likes you can view. |
| like.write | Like and un-like Tweets for you. |
| list.read | Lists, list members, and list followers of lists you’ve created or are a member of, including private lists. |
| list.write | Create and manage Lists for you. |
| block.read | Accounts you’ve blocked. |
| block.write | Block and unblock accounts for you. |
| bookmark.read | Get Bookmarked Tweets from an authenticated user. |
| bookmark.write | Bookmark and remove Bookmarks from Tweets. |
| dm.read | All the Direct Messages you can view, including Direct Messages from protected accounts. |
| dm.write | Send and manage Direct Messages for you. |
| media.write | Upload media. |
#### Rate limits
For the most part, the rate limits are the same as they are authenticating with OAuth 1.0a, with the exception of Tweets lookup and Users lookup. We are increasing the per-App limit from 300 to 900 requests per 15 minutes while using OAuth 2.0 for Tweet lookup and user lookup. To learn more be sure to check out our [documentation on rate limits](/resources/fundamentals/rate-limits).
#### Grant types
We only provide [authorization code](https://oauth.net/2/grant-types/authorization-code/) with [PKCE](https://oauth.net/2/pkce/) and [refresh token](https://oauth.net/2/grant-types/refresh-token/) as the supported [grant types](https://oauth.net/2/grant-types/) for this initial launch. We may provide more grant types in the future.
#### OAuth 2.0 flow
OAuth 2.0 uses a similar flow to what we are currently using for OAuth 1.0a. You can check out a diagram and detailed explanation in our [documentation on this subject](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens).
#### Glossary
| | |
| :---------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Term** | **Description** |
| Grant types | The OAuth framework specifies several grant types for different use cases and a framework for creating new grant types. Examples include authorization code, client credentials, device code, and refresh token. |
| Confidential client | Clients are applications that can securely authenticate with the authorization server, for example, keeping their registered client secret safe. |
| Public client | Clients cannot use registered client secrets, such as applications running in a browser or mobile device. |
| Authorization code flow | Used by both confidential and public clients to exchange an authorization code for an access token. |
| PKCE | An extension to the authorization code flow to prevent several attacks and to be able to perform the OAuth exchange from public clients securely. |
| Client ID | Can be found in the keys and tokens section of the Developer Console under the header "Client ID." If you don't see this, please get in touch with our team directly. The Client ID will be needed to generate the authorize URL. |
| Redirect URI | Your callback URL. You will need to have [exact match validation](https://datatracker.ietf.org/doc/html/rfc6749#section-10.6). |
| Authorization code | This allows an application to hit APIs on behalf of users. Known as the auth\_code. The auth\_code has a time limit of 30 seconds once the App owner receives an approved auth\_code from the user. You will have to exchange it with an access token within 30 seconds, or the auth\_code will expire. |
| Access token | Access tokens are the token that applications use to make API requests on behalf of a user. |
| Refresh token | Allows an application to obtain a new access token without prompting the user via the refresh token flow. |
| Client Secret | If you have selected an App type that is a confidential client you will be provided with a “Client Secret” under “Client ID” in your App’s keys and tokens section. |
#### Parameters
To construct an OAuth 2.0 authorize URL, you will need to ensure you have the following parameters in the authorization URL.
| | |
| :---------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Parameter** | **Description** |
| response\_type | You will need to specify that this is a code with the word “code”. |
| client\_id | Can be found in the Developer Console under the header "Client ID". |
| redirect\_uri | Your callback URL. This value must correspond to one of the Callback URLs defined in your App’s settings. For OAuth 2.0, you will need to have [exact match validation](https://datatracker.ietf.org/doc/html/rfc6749#section-10.6) for your callback URL. |
| state | A random string you provide to verify against [CSRF attacks](https://auth0.com/docs/protocols/state-parameters). The length of this string can be up to 500 characters. |
| code\_challenge | A [PKCE](https://www.oauth.com/oauth2-servers/pkce/authorization-request/) parameter, a random secret for each request you make. |
| code\_challenge\_method | Specifies the method you are using to make a request (S256 OR plain). |
#### Authorize URL
With OAuth 2.0, you create an authorize URL, which you can use to allow a user to authenticate via an authentication flow, similar to “Sign In” with X.
An example of the URL you are creating is as follows:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20account.follows.read%20account.follows.write&state=state&code_challenge=challenge&code_challenge_method=plain
```
You will need to have the proper encoding for this URL to work, be sure to check out our documentation on the [percent encoding](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters).
# Using and generating an app-only Bearer Token
Source: https://docs.x.com/fundamentals/authentication/oauth-2-0/bearer-tokens
Generate and use an app-only Bearer Token for X API OAuth 2.0 application-only authentication with a curl request to the oauth2/token endpoint.
### Using and generating an app-only Bearer Token
A bearer token allows developers to have a more secure point of entry for using the X APIs, and are one of the core features of OAuth 2.0.
Authentication, which uses a Bearer Token, is also known as application-only authentication. A Bearer Token is a byte array of unspecified format that you generate using a script like a curl command. You can also obtain a Bearer Token from the Developer Console inside the keys and tokens section of your App's settings. More information about this feature can be found on [OAuth's official documentation](https://oauth.net/2/bearer-tokens/).
#### When are they used?
The products that require the use of a Bearer Token are as follows:
* [Engagement API](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api)
* [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)
* Other APIs that utilize OAuth 2.0 Bearer Token authentication such as v2 and Labs endpoints.
#### Prerequisites
You will need to [sign up for a developer account](https://developer.x.com/en/portal/petition/essential/basic-info) and to have created a [X App](/resources/fundamentals/developer-apps). Once you have those, you'll also need to obtain the API keys found in the [Developer Console](/resources/fundamentals/developer-portal). Follow the steps below:
1. Login to your X account on developer.x.com.
2. Navigate to the [X App dashboard](https://developer.x.com/content/developer-twitter/en/apps) and open the X App for which you would like to generate access tokens.
3. Navigate to the "keys and tokens" page.
4. You'll find the API keys, user Access Tokens, and Bearer Token on this page.
### How to generate a Bearer Token
You can find the Bearer Token for your App with the rest of your "Keys and Tokens".
Copy the following cURL request into your command line after making changes to the following consumer API keys previously obtained from your [X App](/resources/fundamentals/developer-apps). Note that the consumer API keys used on this page have been decommissioned and will not work for real requests.
* **API key** `` e.g.`xvz1evFS4wEEPTGEFPHBog`
* **API secret key** `` e.g. `L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg`
```bash theme={null}
curl -u "$API_KEY:$API_SECRET_KEY" \
--data 'grant_type=client_credentials' \
'https://api.x.com/oauth2/token'
```
Here's an example of how the curl request should look with your API keys entered:
```bash theme={null}
curl -u 'xvz1evFS4wEEPTGEFPHBog:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg' \
--data 'grant_type=client_credentials' \
'https://api.x.com/oauth2/token'
```
Here is what the response would look like. Note that this is a decommissioned Bearer Token:
`{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F"}`
Our Bearer Token used to authenticate to resources with OAuth 2.0 would be:
`AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F`
# OAuth 2.0
Source: https://docs.x.com/fundamentals/authentication/oauth-2-0/overview
OAuth 2.0 Bearer Token authenticates requests on behalf of your developer App. As this method is specific to the App, it does not involve any users.
### Bearer Token (also known as app-only)
OAuth 2.0 Bearer Token authenticates requests on behalf of your [developer App](/resources/fundamentals/developer-apps). As this method is specific to the App, it does not involve any users. This method is typically for developers that need read-only access to public information.
This authentication method requires for you to pass a Bearer Token with your request, which you can generate within the Keys and tokens section of your developer Apps. Here is an example of what a request looks like with a fake Bearer Token:
```json theme={null}
curl "https://api.x.com/2/tweets?ids=1261326399320715264,1278347468690915330" \
-H "Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAFnz2wAAAAAAxTmQbp%2BIHDtAhTBbyNJon%2BA72K4%3DeIaigY0QBrv6Rp8KZQQLOTpo9ubw5Jt?WRE8avbi"
```
API calls using app-only authentication are [rate limited](/resources/fundamentals/rate-limits) per endpoint at the App level.
To use this method, you'll need a Bearer Token, which you can generate by passing your API Key and Secret through the [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) endpoint, or by generating it in the "keys and token" section of your App settings in the [Developer Console](/resources/fundamentals/developer-portal).
If you'd like to revoke a Bearer Token, you can use the [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) endpoint, or click where it says "revoke" next to the Bearer Token in the "keys and tokens" section of your App settings.
### OAuth 2.0 Authorization Code Flow with PKCE
OAuth 2.0 Authorization Code Flow with PKCE allows you to authenticate on behalf of another user with more control over an application’s scopes and improves authorization flows across multiple devices. In other words, developers building applications for people on X will have more control over the information their App requests from its users, so that you only have to ask your end-users for the data and information you need.
This modern authorization protocol will allow you to present your end-users with a more streamlined consent flow for authorizing your app, which only displays the specific scopes you have requested from them. Not only does this reduce your data burden, but it may also lead to increased trust from end-users.
# OAuth 2.0 Authorization Code Flow with PKCE
Source: https://docs.x.com/fundamentals/authentication/oauth-2-0/user-access-token
Step-by-step guide to connecting users to X API v2 endpoints with OAuth 2.0 Authorization Code Flow with PKCE, including authorize URLs and token exchange.
### How to connect to endpoints using OAuth 2.0 Authorization Code Flow with PKCE
#### How to connect to the endpoints
To authenticate your users, your App will need to implement an authorization flow. This authorization flow lets you direct your users to an authorization dialog on X. From there, the primary X experience will show the authorization dialog and handle the authorization on behalf of your App. Your users will be able to authorize your App or decline permission. After the user makes their choice, X will redirect the user to your App, where you can exchange the authorization code for an access token (if the user authorized your App), or handle a rejection (if the user did not authorize your App).
#### Working with confidential clients
If you are working with confidential clients, you will need to use a [basic authentication](https://datatracker.ietf.org/doc/html/rfc2617#section-2) scheme for generating an authorization header with base64 encoding while making requests to the token endpoints.
The `userid` and `password` are separated by a single colon (":") character within a base64 encoded string in the credentials.
An example would look like this:
`-header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='`
If the user agent wishes to send the Client ID "Aladdin" and password "open sesame,” it would use the following header field:
`Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==`
To create the basic authorization header you will need to base64 encoding on your Client ID and Client Secret which can be obtained from your App’s “Keys and Tokens” page inside of the [Developer Console.](https://developer.x.com/en/portal/dashboard)
#### Steps to connect using OAuth 2.0
**Step 1: Construct an Authorize URL**
Your App will need to build an authorize URL to X, indicating the scopes your App needs to authorize. For example, if your App needs to lookup Tweets, users and to manage follows, it should request the following scopes:
`tweet.read%20users.read%20follows.read%20follows.write`
The URL will also contain the `code_challenge` and state parameters, in addition to the other required parameters. In production you should use a random string for the `code_challenge`.
**Step 2: GET oauth2/authorize**
Have the user authenticate and send the application an authorization code. If you have enabled OAuth 2.0 for your App you can find your Client ID inside your App’s “Keys and Tokens” page.
An example URL to redirect the user to would look like this:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20follows.read%20follows.write&state=state&code_challenge=challenge&code_challenge_method=plain
```
An example URL with offline\_access would look like this:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20follows.read%20offline.access&state=state&code_challenge=challenge&code_challenge_method=plain
```
Upon successful authentication, the redirect\_uri you would receive a request containing the auth\_code parameter. Your application should verify the state parameter.
An example request from client’s redirect would be:
```
https://www.example.com/?state=state&code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE
```
**Step 3: POST oauth2/token - Access Token**
At this point, you can use the authorization code to create an access token and refresh token (only if `offline.access` scope is requested). You can make a POST request to the following endpoint:
```
https://api.x.com/2/oauth2/token
```
You will need to pass in the `Content-Type` of `application/x-www-form-urlencoded` via a header. Additionally, you should have in your request: `code`, `grant_type`, `client_id` and `redirect_uri`, and the `code_verifier`.
Here is an example token request for a public client:
```json theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ' \
--data-urlencode 'redirect_uri=https://www.example.com' \
--data-urlencode 'code_verifier=challenge'
```
Here is an example using a confidential client:
```json theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'redirect_uri=https://www.example.com' \
--data-urlencode 'code_verifier=challenge'
```
**Step 4: Connect to the APIs**
You are now ready to connect to the endpoints using OAuth 2.0. To do so, you will request the API as you would using [Bearer Token authentication](/resources/fundamentals/authentication/oauth-2-0/application-only). Instead of passing your Bearer Token, you’ll want to use the access token you generated in the last step. As a response, you should see the appropriate payload corresponding to the endpoint you are requesting. This request is the same for both public and confidential clients.
An example of the request you would make would look as follows:
```json theme={null}
curl --location --request GET 'https://api.x.com/2/tweets?ids=1261326399320715264,1278347468690915330' \
--header 'Authorization: Bearer Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE'
```
**Step 5: POST oauth2/token - refresh token**
A refresh token allows an application to obtain a new access token without prompting the user. You can create a refresh token by making a POST request to the following endpoint: [https://api.x.com/2/oauth2/token](https://api.x.com/2/oauth2/token) You will need to add in the `Content-Type` of `application/x-www-form-urlencoded` via a header. In addition, you will also need to pass in your refresh\_token, set your grant\_type to be a `refresh_token`, and define your `client_id`.
This request will work for public clients:
```json theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ'
```
Here is an example of one for confidential clients:
```json theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE'\
--data-urlencode 'grant_type=refresh_token'
```
**Step 6: POST oauth2/revoke - Revoke Token**
A revoke token invalidates an access token or refresh token. This is used to enable a "log out" feature in clients, allowing you to clean up any security credentials associated with the authorization flow that may no longer be necessary. The revoke token is for an App to revoke a token and not a user. You can create a revoke token request by making a POST request to the following URL if the App wants to programmatically revoke the access given to it:
```
https://api.x.com/2/oauth2/revoke
```
You will need to pass in the `Content-Type` of `application/x-www-form-urlencoded` via a header, your token, and your client\_id.
In some cases, a user may wish to revoke access given to an App, they can revoke access by visiting the [connected Apps page](https://x.com/settings/connected_apps).
```bash theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/revoke' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ'
```
This request will work for confidential clients:
```bash theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/revoke' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'token=Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE'
```
# Authentication
Source: https://docs.x.com/fundamentals/authentication/overview
X APIs handle enormous amounts of data. The way we ensure this data is secured for developers and users alike is through authentication.
X APIs handle enormous amounts of data, and authentication secures that data for developers and users alike. You can choose from several authentication methods, listed below.
Most developers don't need to handle the complexities of authentication directly—client libraries take care of them automatically.
You can find a list of available client libraries on our [Tools and libraries](/resources/tools-and-libraries) page.
## Authentication methods
OAuth 1.0a allows an authorized X developer App to access private account information or perform a X action on behalf of a X account.
[**Learn More**](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret)
App only Access Token allows a X developer app to access information publicly available on X.
[**Learn More**](/resources/fundamentals/authentication/oauth-2-0/overview)
Many of X's enterprise APIs require the use of HTTP Basic Authentication.
[**Learn More**](/resources/fundamentals/authentication/basic-auth)
OAuth 2.0 User Context allows you to authenticate on behalf of another account with greater control over an application's scope, and authorization flows across multiple devices.
[**Learn More**](/resources/fundamentals/authentication/oauth-2-0/authorization-code)
**Note:**
You can get your App's API Keys, App-only Access Token, personal Access Token, and Access Token Secret from the [X developer Apps](/resources/fundamentals/developer-apps) section in the [Developer Console](/resources/fundamentals/developer-portal).
**To make requests on behalf of another user**, generate a separate set of Access Tokens for that user using the [3-legged OAuth flow](https://developer.x.com/resources/fundamentals/authentication/obtaining-user-access-tokens), then pass that user's tokens with your OAuth 1.0a User Context or OAuth 2.0 user context requests.
## Additional resources
Learn how to generate tokens and authenticate requests using our integration guides.
Review our reference guides for our authentication endpoints.
Make sure you protect yourself and understand the best practices for storing your keys and tokens.
Have a question? Visit our FAQs.
# Counting Characters
Source: https://docs.x.com/fundamentals/counting-characters
How X counts characters in Posts, including the 280-character limit, weighted code points, URL shortening, emoji and Unicode handling, and edge cases.
Posts on X can contain up to **280 characters**. However, not all characters count equally—emojis, URLs, and certain Unicode ranges have special counting rules.
***
## Character weights
X uses a weighted character counting system. Most characters count as 1, but some count as 2:
| Character type | Weight | Max characters |
| :--------------------------------- | :---------- | :------------- |
| Latin, punctuation, common symbols | 1 | 280 |
| Emojis | 2 | 140 emojis |
| CJK (Chinese, Japanese, Korean) | 2 | 140 characters |
| Other Unicode | 2 (default) | Varies |
Use the open-source [twitter-text](https://github.com/twitter/twitter-text) library to accurately count characters in your app.
***
## Emoji counting
All emojis count as **2 characters**, regardless of complexity:
| Emoji | Display | Character count | Unicode |
| :---------- | :---------------- | :-------------- | :---------------- |
| 👾 | Single emoji | 2 | U+1F47E |
| 🙋🏽 | With skin tone | 2 | 🙋 + 🏽 modifier |
| 👨🎤 | Combined with ZWJ | 2 | 👨 + ZWJ + 🎤 |
| 👨👩👧👦 | Family sequence | 2 | 4 emojis + 3 ZWJs |
Zero-width joiners (ZWJ) combine emojis visually but don't add to the count.
***
## URL handling
All URLs are wrapped with `t.co` shortener and count as **23 characters**, regardless of the original length:
```
https://example.com → 23 characters
https://example.com/very/long/path → 23 characters
```
This applies to any valid URL detected in post text.
***
## Special cases
| Content | Counting rule |
| :----------------------- | :----------------------------------------------------------- |
| **@mentions in replies** | Auto-populated @mentions at the start of replies don't count |
| **New @mentions** | @mentions you add manually count normally |
| **Media** | Attached media (via official clients) counts as 0 characters |
| **Hashtags** | Count normally (# + tag text) |
***
## Text encoding
The X API requires **UTF-8** encoding. Character length is calculated using Unicode Normalization Form C (NFC).
Example with `café`:
| Form | Bytes | Characters |
| :--------------- | :---------- | :--------- |
| NFC (composed) | `c a f é` | 4 |
| NFD (decomposed) | `c a f e ́` | 5 |
X normalizes to NFC, so both encode to 4 characters.
***
## Implementation
Use the official [twitter-text](https://github.com/twitter/twitter-text) library for accurate character counting:
```javascript theme={null}
import { parseTweet } from 'twitter-text';
const result = parseTweet('Hello, world! 👋');
console.log(result.weightedLength); // 16
console.log(result.valid); // true
```
```python theme={null}
from twitter_text import parse_tweet
result = parse_tweet('Hello, world! 👋')
print(result.weightedLength) # 16
print(result.valid) # True
```
The library handles all edge cases including emoji sequences, URL detection, and Unicode normalization.
***
## Resources
Official open-source library for text parsing.
Character weight definitions and Unicode ranges.
# Apps
Source: https://docs.x.com/fundamentals/developer-apps
Create and configure X developer apps to get API credentials, set OAuth 1.0a and OAuth 2.0 permissions, manage callback URLs, and rotate keys.
Apps are containers for your API credentials. Each app has its own keys, tokens, and settings.
***
## App credentials
When you create an app, you can generate these credentials:
| Credential | Use case |
| :------------------------ | :--------------------------------------------------------------------------- |
| **API Key & Secret** | Authenticate with OAuth 1.0a. Used to sign requests or generate user tokens. |
| **Access Token & Secret** | Make requests on behalf of your own account (OAuth 1.0a). |
| **Client ID & Secret** | Authenticate with OAuth 2.0. Used for authorization code flow. |
| **Bearer Token** | App-only authentication for public data endpoints. |
Choose **OAuth 2.0** for new projects. It offers fine-grained scopes and is required for X API v2 user-context endpoints.
***
## Creating an app
Go to [console.x.com](https://console.x.com) and sign in.
Enter a name, description, and use case for your app.
After creation, generate the keys and tokens you need.
Save credentials immediately—they're only shown once.
***
## App permissions (OAuth 1.0a)
OAuth 1.0a apps have three permission levels:
* View posts, users, and public data
* Cannot post, like, or modify anything
* Cannot access Direct Messages
* All read permissions
* Post and delete posts
* Follow/unfollow users
* Like and repost
* Cannot access Direct Messages
* All read and write permissions
* Send and read Direct Messages
Changing permissions requires users to re-authorize your app to get new tokens with the updated scope.
***
## OAuth 2.0 app types
When configuring OAuth 2.0, select your app type:
| Type | Client | Use case |
| :---------------------- | :----------- | :------------------------------------------------------- |
| **Web App** | Confidential | Server-side applications that can securely store secrets |
| **Automated App / Bot** | Confidential | Bots and automated services running on servers |
| **Native App** | Public | Mobile or desktop apps that can't secure secrets |
| **Single Page App** | Public | Browser-based JavaScript apps |
**Confidential clients** receive a Client Secret. **Public clients** use PKCE only.
***
## Callback URLs
Callback URLs (redirect URIs) are required for OAuth flows. After a user authorizes your app, they're redirected to your callback URL with an authorization code.
### Requirements
* Add callback URLs to your app's allowlist in the Developer Console
* URLs must match exactly (including trailing slashes)
* Maximum of **10 callback URLs** per app
* Use `https://` in production
* For local development, use `http://127.0.0.1` (not `localhost`)
### Disallowed protocols
These protocols cannot be used: `javascript`, `data`, `file`, `ftp`, `mailto`, `telnet`, and other non-standard schemes.
`vbscript`, `javascript`, `vbs`, `data`, `mocha`, `keyword`, `livescript`, `ftp`, `file`, `gopher`, `acrobat`, `callto`, `daap`, `itpc`, `itms`, `firefoxurl`, `hcp`, `ldap`, `mailto`, `mmst`, `mmsu`, `msbd`, `rtsp`, `mso-offdap`, `snews`, `news`, `nntp`, `outlook`, `stssync`, `rlogin`, `telnet`, `tn3270`, `shell`, `sip`
***
## Best practices
Create different apps for development, staging, and production.
Regenerate keys periodically and if you suspect a compromise.
Request only the permissions your app actually needs.
Check the Developer Console regularly to track API usage.
***
## Automated account labels
If your app runs a bot account, you can label it as automated:
1. Go to your bot account's **Settings**
2. Select **Your account** → **Automation**
3. Link your managing account
This builds trust with users and distinguishes your bot from spam.
***
## Troubleshooting
Ensure your callback URL is exactly as registered in the Developer Console, including protocol and any trailing slashes. HTTP-encode the URL when passing it as a query parameter.
```json theme={null}
{
"errors": [{
"code": 415,
"message": "Callback URL not approved for this client application."
}]
}
```
If your app shows as suspended, check your email for a notice from the X platform team. Use the [Platform Help Form](https://help.x.com/forms/platform) to appeal.
# Developer Console
Source: https://docs.x.com/fundamentals/developer-portal
Use the X Developer Console to manage projects and apps, monitor API usage, access credentials, invite team members, and view billing information.
The [Developer Console](https://console.x.com) is your central hub for managing X API access. Create apps, generate credentials, monitor usage, and manage billing—all in one place.
***
## What you can do
Set up apps to get API credentials. Configure authentication, permissions, and callback URLs.
Track API usage in real-time. View costs per endpoint and manage your credit balance.
Create API keys, access tokens, and OAuth credentials for your apps.
Buy credits for pay-per-usage billing. No subscriptions or commitments required.
***
## Getting started
Go to [console.x.com](https://console.x.com) and sign in with your X account. Accept the Developer Agreement.
Click **New App** and provide a name and description. This generates your API credentials.
Copy and securely store your API Key, API Secret, and Access Tokens. These won't be shown again.
Use your credentials to authenticate API requests. Check out the [quickstart guide](/x-api/getting-started/make-your-first-request).
**Store credentials securely.** API keys and tokens are only displayed once when generated. Use a password manager or secure vault. If lost, you'll need to regenerate them, which invalidates the old credentials.
***
## Billing & credits
The X API uses pay-per-usage pricing with a credit-based system:
| Feature | Description |
| :----------------------- | :------------------------------------------------------------- |
| **No monthly fees** | Pay only for what you use—no subscriptions |
| **Credit-based** | Purchase credits upfront, deducted as you use the API |
| **Real-time tracking** | Monitor usage and costs in the console dashboard |
| **Per-endpoint pricing** | Different endpoints have different costs |
| **Deduplication** | Same resource requested twice in 24 hours is only charged once |
View current pricing and purchase credits in the [Developer Console](https://console.x.com).
[Learn more about pricing →](/x-api/getting-started/pricing)
***
## Team management
Team management is available for **Enterprise accounts** only.
Enterprise accounts can invite team members to collaborate:
| Role | Capabilities |
| :---------------- | :--------------------------------------------------------- |
| **Administrator** | Full access: manage apps, billing, team members, and roles |
| **Developer** | Manage own apps, read-only access to team apps |
To invite a team member, navigate to the Team page in your console and enter their X handle.
***
## Next steps
Learn about app settings, permissions, and credentials.
Use your credentials to call the API.
# Rate Limits
Source: https://docs.x.com/fundamentals/rate-limits
Understand X API rate limits across access tiers and endpoints, including app-level vs user-level limits, response headers, and best practices for retries.
Rate limits control how many API requests you can make in a given time period. They ensure fair usage and system stability across the platform.
***
## Rate limits by product
Each X API product has its own rate limiting approach:
Per-endpoint limits based on 15-minute windows. View detailed tables and recovery tips.
Custom limits based on your enterprise agreement and data package.
Limits specific to ad management and analytics endpoints.
***
## How rate limits work
| Concept | Description |
| :-------------------- | :------------------------------------------------------ |
| **Time window** | Most limits reset every 15 minutes |
| **Per-user limits** | Apply when using OAuth 1.0a or OAuth 2.0 user tokens |
| **Per-app limits** | Apply when using Bearer Token (app-only) authentication |
| **Endpoint-specific** | Each endpoint has its own limit |
***
## Checking your limits
Every API response includes headers showing your current rate limit status:
```
x-rate-limit-limit: 900
x-rate-limit-remaining: 847
x-rate-limit-reset: 1705420800
```
| Header | Description |
| :----------------------- | :--------------------------------------------- |
| `x-rate-limit-limit` | Maximum requests allowed in the current window |
| `x-rate-limit-remaining` | Requests remaining in the current window |
| `x-rate-limit-reset` | Unix timestamp when the limit resets |
***
## Rate limit errors
When you exceed a rate limit, you'll receive a **429 Too Many Requests** response:
```json theme={null}
{
"errors": [{
"code": 88,
"message": "Rate limit exceeded"
}]
}
```
***
## Best practices
Store API responses locally to reduce repeated requests for the same data.
When rate limited, wait before retrying. Double the wait time with each retry.
Monitor rate limit headers to avoid hitting limits proactively.
For real-time data, use filtered stream instead of polling search endpoints.
***
## Next steps
For detailed rate limit tables by endpoint, see the rate limits page for your specific API:
* [X API v2 Rate Limits](/x-api/fundamentals/rate-limits)
* [X Ads API Rate Limits](/x-ads-api/fundamentals/rate-limiting)
# Security
Source: https://docs.x.com/fundamentals/security
Security best practices for X API developers, including credential storage, OAuth handling, key rotation, secure callbacks, and vulnerability disclosure.
Building secure applications protects both your users and the X platform. This guide covers essential security practices for X API developers.
***
## Core requirements
All API requests must use HTTPS. Plain HTTP is rejected.
Never expose API keys or tokens in client-side code, logs, or repositories.
***
## Protecting credentials
Your API keys and tokens are the keys to your app. Keep them secure:
Store credentials in environment variables, not in code.
```bash theme={null}
export X_API_KEY="your-api-key"
export X_API_SECRET="your-api-secret"
```
Add credential files to `.gitignore`. Use tools like `git-secrets` to prevent accidental commits.
Regenerate keys periodically and immediately if you suspect a compromise.
Only request the OAuth scopes your app actually needs.
### If credentials are compromised
1. **Regenerate immediately** in the [Developer Console](https://console.x.com)
2. **Revoke old tokens** — regenerating automatically invalidates old credentials
3. **Audit usage** — check for unauthorized API activity
4. **Update your app** — deploy new credentials to all environments
***
## Application security
### Input validation
Never trust user input. Validate and sanitize all data before using it:
```python theme={null}
# Bad - vulnerable to injection
query = f"from:{user_input}"
# Good - validate input first
import re
if re.match(r'^[a-zA-Z0-9_]{1,15}$', user_input):
query = f"from:{user_input}"
```
### Output encoding
Escape X API data before displaying in HTML to prevent XSS:
```javascript theme={null}
// Bad - vulnerable to XSS
element.innerHTML = tweet.text;
// Good - escape HTML
element.textContent = tweet.text;
```
### Common vulnerabilities to prevent
| Vulnerability | Prevention |
| :----------------- | :---------------------------------------------------------- |
| **XSS** | Escape all user-generated content before rendering |
| **CSRF** | Use anti-CSRF tokens in forms; verify OAuth state parameter |
| **SQL Injection** | Use parameterized queries, never concatenate user input |
| **Open redirects** | Validate callback URLs against an allowlist |
***
## OAuth security
### State parameter
Always use the `state` parameter in OAuth flows to prevent CSRF:
```python theme={null}
import secrets
# Generate state before authorization
state = secrets.token_urlsafe(32)
session['oauth_state'] = state
# Verify state after callback
if request.args.get('state') != session.get('oauth_state'):
abort(403) # State mismatch - possible CSRF
```
### Token storage
| Token type | Storage recommendation |
| :----------------- | :------------------------------------------------- |
| **Access tokens** | Encrypted database or secure vault |
| **Refresh tokens** | Encrypted database with additional access controls |
| **Bearer tokens** | Environment variables or secure configuration |
***
## Secure development practices
Conduct regular security reviews and penetration testing.
Keep dependencies updated. Use tools to detect vulnerable packages.
Log security events but never log credentials or sensitive data.
Set up alerts for unusual API usage patterns.
***
## Reporting security issues
If you discover a security vulnerability affecting X:
**Report within 48 hours.** X Developer Platform users must notify X no more than 48 hours after suspecting a security incident.
Report vulnerabilities in X's systems through HackerOne.
If your app using X data is breached, report through the same channel.
***
## Compliance checklist
* [ ] All API requests use TLS/HTTPS
* [ ] Credentials stored securely (not in code or logs)
* [ ] User tokens encrypted at rest
* [ ] Input validation on all user-supplied data
* [ ] Output encoding to prevent XSS
* [ ] CSRF protection on OAuth flows
* [ ] Security logging enabled (without sensitive data)
* [ ] Incident response plan documented
* [ ] Dependencies regularly updated
* [ ] Minimal OAuth scopes requested
***
## Resources
Implement OAuth correctly.
Configure minimal required permissions.
# X IDs
Source: https://docs.x.com/fundamentals/x-ids
Understand 64-bit Snowflake IDs in the X API for Posts and users, including format, ordering, ID inflation, and safe handling in JavaScript clients.
Every object in the X API—posts, users, lists, DMs, spaces—has a unique ID. Understanding how these IDs work helps you build reliable integrations.
***
## ID format
X IDs are **64-bit unsigned integers** generated using a system called "Snowflake." Each ID encodes:
* **Timestamp** — When the object was created
* **Worker number** — Which server generated the ID
* **Sequence number** — Order within that millisecond
This means IDs are roughly time-ordered: higher IDs generally represent newer objects.
IDs are globally unique across all of X, not just within a single object type.
***
## String vs. integer representation
**Always use string IDs in your code.** Some programming languages (like JavaScript) can't accurately represent 64-bit integers.
In JavaScript, integers are limited to 53 bits. This causes precision loss with large IDs:
```javascript theme={null}
// This loses precision!
const id = 10765432100123456789;
console.log(id.toString()); // "10765432100123458000" — wrong!
// Use strings instead
const id = "10765432100123456789";
console.log(id); // "10765432100123456789" — correct!
```
### API versions
| Version | ID format |
| :------------- | :---------------------------------------------------------------------- |
| **X API v2** | IDs are returned as strings by default |
| **X API v1.1** | Returns both `id` (integer) and `id_str` (string) — always use `id_str` |
***
## Working with IDs
### Storing IDs
Store IDs as strings or 64-bit integers in your database:
| Database | Recommended type |
| :--------- | :-------------------------------------- |
| PostgreSQL | `BIGINT` or `TEXT` |
| MySQL | `BIGINT UNSIGNED` or `VARCHAR(20)` |
| MongoDB | String |
| SQLite | `TEXT` (SQLite integers max at 63 bits) |
### Comparing IDs
When comparing IDs for chronological ordering:
```python theme={null}
# Python - safe for 64-bit integers
if int(id1) > int(id2):
print("id1 is newer")
# JavaScript - compare as strings (lexicographically works for same-length IDs)
# Or use BigInt
if (BigInt(id1) > BigInt(id2)) {
console.log("id1 is newer");
}
```
***
## Common ID types
| Object | Example ID | Notes |
| :----------- | :-------------------- | :--------------------------------- |
| Post (Tweet) | `1234567890123456789` | Also called Tweet ID |
| User | `2244994945` | Older accounts have shorter IDs |
| List | `1234567890` | |
| Space | `1YqGodQbNXDxv` | Alphanumeric, not Snowflake format |
| DM Event | `1234567890123456789` | |
***
## Related resources
See ID fields for each object type.
Retrieve posts by ID.
# Important Resources
Source: https://docs.x.com/important-resources
Bookmark key X API documentation, SDKs, Postman collections, support channels, status pages, and community resources for developers building on X.
Bookmark these essential resources for X API development.
***
## Documentation
Complete endpoint documentation with parameters and examples.
Object schemas for posts, users, media, and more.
OAuth 1.0a and OAuth 2.0 implementation guides.
Per-endpoint limits and best practices.
***
## Tools
| Tool | Description |
| :------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ |
| [Developer Console](https://console.x.com) | Manage apps, credentials, and billing |
| [Postman Collection](https://www.postman.com/xapidevelopers/x-api-public-workspace/collection/34902927-2efc5689-99c6-4ab6-8091-996f35c2fd80) | Interactive API testing |
| [Python SDK](/xdks/python/overview) | Official Python library |
| [TypeScript SDK](/xdks/typescript/overview) | Official TypeScript library |
| [OpenAPI Spec](https://api.x.com/2/openapi.json) | Machine-readable API specification |
***
## Learning
Step-by-step guides for common use cases.
Example apps and code samples.
Ideas and inspiration for projects.
Upgrade from v1.1 to v2.
***
## Community and support
Ask questions and share solutions with the community.
FAQs, troubleshooting, and contact options.
Official updates and announcements.
API-specific news and tips.
***
## Stay updated
| Resource | What you'll get |
| :------------------------------------------------------------------- | :------------------------------------- |
| [Changelog](/changelog) | All platform changes and updates |
| [Changelog RSS feed](https://docs.x.com/changelog/rss.xml) | Changelog updates for your feed reader |
| [Newsletter](/newsletter) | Monthly roundup of news and features |
| [Forum Announcements](https://devcommunity.x.com/c/announcements/22) | Important platform notices |
| [API Status](/status) | Real-time service availability |
Follow [@XDevelopers](https://x.com/XDevelopers) and turn on notifications to catch breaking changes and new features.
***
## Quick reference
### Response structure
All v2 responses follow this structure:
```json theme={null}
{
"data": { ... }, // Primary object(s)
"includes": { ... }, // Expanded objects (if requested)
"meta": { ... }, // Pagination info
"errors": [ ... ] // Partial errors (if any)
}
```
### Common parameters
| Parameter | Use |
| :----------------- | :--------------------------- |
| `tweet.fields` | Request specific post fields |
| `user.fields` | Request specific user fields |
| `expansions` | Include related objects |
| `max_results` | Limit results per page |
| `pagination_token` | Get next/previous page |
### Authentication methods
| Method | Use case |
| :----------- | :-------------------------------------- |
| Bearer Token | Read-only public data |
| OAuth 2.0 | User actions with fine-grained scopes |
| OAuth 1.0a | User actions (legacy, full permissions) |
[Full authentication guide →](/resources/fundamentals/authentication/overview)
# 変更履歴
Source: https://docs.x.com/ja/changelog
X API v2、エンタープライズ API、Ads API、SDK、ストリーミング、Webhook、開発者プラットフォームのリリースノートとバージョン履歴。新機能、エンドポイントの変更、非推奨、移行ガイド、レート制限の最新アップデート情報をまとめて確認できます。
更新情報の通知を受け取るには、[**@API**](https://x.com/api) の [**「通知をオンにする」**](https://help.x.com/en/managing-your-account/notifications-on-mobile-devices#:~:text=In%20the%20top%20menu,%20you,you%20would%20like%20to%20receive) を有効にしてください。また、この変更履歴は [**RSS フィード**](https://docs.x.com/changelog/rss.xml)を使ってフィードリーダーで購読することもできます。
### Articles のドラフトおよび公開エンドポイント
本日、X API 経由で Articles をドラフトおよび公開するための[新しいエンドポイント](/x-api/articles/introduction)を追加しました。
### X Activity API における Post の作成・削除イベント
本日、[X Activity API](https://docs.x.com/x-api/activity/introduction) に `post.create` と `post.delete` イベントを追加しました。ユーザー ID で購読することで、ユーザーが Post を作成または削除したときにリアルタイム通知を受け取れるようになります。
基本的なユーザーごとの Post アクティビティには XAA を使用してください。高度なキーワードフィルタリングや Filtered Stream のすべての演算子を使用したい場合は、引き続き [Filtered Stream](/x-api/posts/filtered-stream/introduction) を使用してください。
### `paid_partnership` Post フィールド
Post の `paid_partnership` フィールドのサポートを追加しました。
* `POST /2/tweets` で Post を作成する際に `"paid_partnership": true` を設定すると、その Post が有料パートナーシップであること (つまり、投稿者が有料プロモーションを含むことを開示していること) を示します。Post には有料プロモーションとしてラベルが付きます。
* Post を読み取る際に `tweet.fields=paid_partnership` をリクエストすると、その値を取得できます (投稿者が有料プロモーションを含む Post として開示している場合は `true`)。
### 検索エンドポイントを新しい検索インデックスに移行
本日、X API v2 の検索エンドポイント (`/2/tweets/search/recent`、`/2/tweets/search/all`、`/2/tweets/counts/recent`、`/2/tweets/counts/all`) を、新しい X コアプラットフォームの検索インデックスへ移行しました。これにより、パフォーマンスが大幅に向上し、503 エラーが劇的に減少し、3 つの新しい精度オペレーター `min\_likes:`、`min\_replies:`、`min\_reposts:` が利用可能になります。注: キーワードベースの検索結果にはリツイートが含まれなくなりました (Filtered Stream に変更はありません)。詳細は[こちら](https://devcommunity.x.com/t/important-update-x-api-search-endpoints-migrating-to-new-search-index/264595)をご覧ください。
### X API 価格更新: Owned Reads が 1 件 \$0.001 に
2026 年 4 月 20 日より、自身のデータにアクセスする対象エンドポイント (`GET /2/users/{id}/bookmarks`、`/blocking`、`/muting`、`/pinned_lists`、`/tweets`、`/mentions`、`/liked_tweets`、`/followers`、`/following`、`/owned_lists`、`/followed_lists`、`/list_memberships`) について、新しい「Owned Reads」価格 \*\*1 リソースあたり $0.001** (1,000 件で $1) を導入しました。書き込みも更新しており、`POST /2/tweets` は 1 件あたり $0.015 となり、URL を含む投稿は 1 件あたり $0.20 (召喚された返信は \$0.01 のまま) です。API 経由のフォロー、いいね、引用投稿は、すべてのセルフサーブ階層から削除されました。詳細は[こちら](https://devcommunity.x.com/t/x-api-pricing-update-owned-reads-now-0-001-other-changes-effective-april-20-2026/263025)をご覧ください。
### Account Activity Replay エンドポイントの廃止
本日、`POST /2/account_activity/replay/webhooks/{webhook_id}/subscriptions/all` の廃止を発表しました。2026 年 3 月 25 日午後 12:00 ET より有効となります。代わりに、新しい統合エンドポイントである `POST /2/webhooks/replay` をご利用ください。同等の機能を提供します。詳細は[こちら](https://devcommunity.x.com/t/deprecation-of-account-activity-replay-endpoint/260354)をご覧ください。
### X Activity API サブスクリプションの Direction フィルター
本日、X Activity API のサブスクリプションに任意の `direction` フィルターを追加しました。サブスクライバーは、DM やチャットイベントを `sent`、`received`、またはその両方にスコープできるようになり、送信または受信のみが必要な場合のノイズを削減できます。
### X Activity API のイベントタイプ形式の更新
本日、X Activity API のイベントタイプ命名の変更を発表しました。2026 年 3 月 18 日から有効です。PascalCase のイベントタイプ (例: `ProfileBioUpdate`) は廃止され、ドット区切りの小文字形式 (例: `profile.update.bio`) に置き換えられます。古い値に依存するフィルタリング、switch 文、デシリアライズロジックを更新してください。詳細は[こちら](https://devcommunity.x.com/t/updates-to-event-types-format-in-the-x-activity-api/259765)をご覧ください。
### X Activity API のレガシー DM イベント
本日、レガシー DM イベント (`dm.received`、`dm.sent`、`dm.read`、`dm.indicate_typing`) を [X Activity API](https://docs.x.com/x-api/activity/introduction) に追加しました。これにより、Account Activity API からの DM イベント配信が、より低レイテンシの XAA パイプラインへ移行します。
### LLM によって生成されたスパムへの対応
本日、X 上の自動化された低品質な返信を削減するための変更を行いました。`POST /2/tweets` 経由のプログラム的な返信は、元の投稿の作成者が返信側のアカウントを「召喚」した場合 (そのアカウントを @メンションするか、その投稿の 1 つを引用した場合) にのみ許可されます。プログラムによるユーザーへの @メンションや引用にも追加の制限が適用されます。これらの変更はセルフサーブ階層のみが対象で、Enterprise アクセスには影響しません。詳細は[こちら](https://devcommunity.x.com/t/x-api-v2-update-addressing-llm-generated-spam/257909)をご覧ください。
### X API 従量課金制プランの提供開始
本日、**X API 従量課金制 (Pay-Per-Use)** プランを正式に提供開始しました。インディー開発者、スタートアップ、ホビイスト向けに設計された、柔軟なクレジットベースのモデルです。主なハイライト:
* [console.x.com](https://console.x.com) の新しい Developer Console
* ファーストパーティの Python および TypeScript SDK を含む [XDK (X Developer Kit)](https://docs.x.com/xdks/overview)
* テスト用のインタラクティブな [Playground](https://github.com/xdevplatform/playground)
* AI モデル向けの [MCP サーバー](https://github.com/xdevplatform/xmcp)
* X API に費やした 1 ドルごとに、最大 **20% を xAI/Grok API クレジットとして還元**
Public Utility App は引き続き無料の拡張アクセスを受けられます。最近アクティブだった Legacy Free 階層のユーザーには、\$10 のワンタイムバウチャーが付与されます。Basic および Pro プランは引き続き提供され、既存のサブスクライバーは従量課金制にオプトインできます。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-launch-of-x-api-pay-per-use-pricing/256476)をご覧ください。
### X Activity API での Spaces イベント
本日、Spaces のライフサイクルイベント (`spaces.start`、`spaces.end`) を [X Activity API](https://docs.x.com/x-api/activity/introduction) に追加しました。ユーザー ID 別にサブスクライブすると、Space の開始または終了をリアルタイムで通知します。
### カウントベースのオペレーターの廃止
本日、`/2/tweets/search/recent` および `/2/tweets/search/all` の `min\_likes`、`min\_replies`、`min\_reposts` オペレーターを廃止しました。この変更は Filtered Stream の同等のオペレーターには影響しません。将来的に最適な形でこれらを再有効化する方法を検討しています。詳細は[こちら](https://devcommunity.x.com/t/deprecating-count-based-operators-in-the-x-api/254933)をご覧ください。
### Account Activity API v2 に OAuth 2.0 サポートを追加
本日、[Account Activity API v2](https://docs.x.com/x-api/account-activity/introduction) に OAuth 2.0 の完全なサポートを追加しました。開発者は、オール・オア・ナッシングの OAuth 1.0a 権限モデルではなく、きめ細やかなスコープ (例: `follow.read`) を持つ OAuth 2.0 を使用してサブスクリプションを作成できるようになりました。既存の OAuth 1.0a ベースの統合は引き続き中断なく動作します。OAuth 1.0a の権限が存在する場合、OAuth 2.0 のスコープを完全に上書きします。詳細は[こちら](https://devcommunity.x.com/t/announcement-oauth2-0-support-added-to-account-activity-api-v2/254633)をご覧ください。
### X API Playground の提供開始
本日、[X API Playground](https://github.com/xdevplatform/playground) を発表しました。X API v2 のエンドポイントをエミュレートするセルフホスト型のローカルサーバーです。実際の API 呼び出しを行うことなく、またレート制限に到達することなく統合を開発・テストできます。現実的なモックデータ、状態の永続化、OpenAPI 検証、レート制限のシミュレーション、Web UI を備えています。`go install github.com/xdevplatform/playground/cmd/playground@latest` でインストールできます。詳細は[こちら](https://devcommunity.x.com/t/introducing-x-api-playground-local-development-tool-for-x-api-v2/253442)をご覧ください。
### News エンドポイントの提供開始
本日、X API v2 で新しい [News エンドポイント](https://docs.x.com/x-api/news/introduction) を提供開始しました:
* `GET /2/news/search` — 検索クエリに一致するトレンドニュース記事を返します
* `GET /2/news/{id}` — ID で特定のニュース記事をルックアップします
どちらのエンドポイントも、`name`、`summary`、`contexts`、`cluster\_posts\_results`、`last\_updated\_at\_ms` などのフィールドを選択するための `news.fields` をサポートしています。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-news-endpoints-in-the-x-api-v2/251833)をご覧ください。
### Python および TypeScript XDK の提供開始
本日、X API v2 向けの公式ファーストパーティ [Python](https://docs.x.com/xdks/python/overview) および [TypeScript](https://docs.x.com/xdks/typescript/overview) XDK (X Developer Kits) を提供開始しました。XDK は、認証 (Bearer Token、OAuth 2.0 PKCE、OAuth 1.0a)、自動ページネーション、再接続処理を備えたリアルタイムストリーミング、すべての v2 エンドポイントの包括的なカバレッジを提供します。`pip install xdk` または `npm install @xdevplatform/xdk` でインストールできます。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-python-and-typescript-xdks-for-the-x-api-v2/250860)をご覧ください。
### X Activity API サブスクリプションのキーワードフィルタリング
本日、X Activity API のサブスクリプションにキーワードフィルタリングを追加しました。ユーザー ID によるフィルタリングに加えて、サブスクライバーはキーワードによってイベント配信をさらに絞り込めるようになりました。これは、追加のフィルタリングが正当化されるイベント量の多い News イベントなどに有用です。
### X Activity API での認証バッジ、Affiliate バッジ、ハンドル更新イベント
本日、[X Activity API](https://docs.x.com/x-api/activity/introduction) を拡張し、プロフィール関連の追加イベントタイプを配信できるようになりました:
* `profile.update.verified` — ユーザーの認証ステータスが変更されたとき
* `profile.update.affiliate` — ユーザーの affiliate バッジが変更されたとき
* `profile.update.screenname` — ユーザーが @ハンドルを変更したとき
### X API 従量課金制 (Pay-Per-Use) のパイロット
本日、新しいクレジットベースの従量制価格モデルに関する限定クローズドパイロットを発表しました。開発者はクレジットを前払いで購入し、リクエストごとに課金されます。固定のサブスクリプション料金や月次オブジェクト上限はありません。パイロットの初期レート: Post Read $0.005、User Read $0.01、DM Event Read $0.01、Content Create $0.01、DM Interaction $0.01、User Interaction $0.015。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-x-api-pay-per-use-pricing-pilot/250253)をご覧ください。
### X Activity API オープンベータの開始
本日、[X Activity API](https://docs.x.com/x-api/activity/introduction) のオープンベータを開始しました。これは、X 上のリアルタイムなアクティビティイベントにサブセコンド遅延でサブスクライブできる新しいエンドポイント群です。プロフィールイベントタイプ (`ProfileBioUpdate`、`ProfilePictureUpdate`、`ProfileBannerUpdate`、`ProfileGeoUpdate`、`ProfileUrlUpdate`) にサブスクライブし、ユーザー ID でフィルタリングして、一致するイベントを永続的な HTTP ストリーム (`GET /2/activity/stream`) または Webhook 経由で受信できます。サブスクリプションは `POST /2/activity/subscriptions` で管理します。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-x-activity-api-open-beta/250099)をご覧ください。
### X API 経由での投稿編集
本日、X API 経由で最近の投稿をプログラム的に編集する機能を提供開始しました。既存の `POST /2/posts` エンドポイントを、`previous_post_id` を含む新しい `edit_options` オブジェクトとともに使用します。要件: 認証ユーザーが X Premium に加入していること、対象の投稿が自身のものであること、過去 1 時間以内に作成されていること。更新された [Create or Edit Post](https://docs.x.com/x-api/posts/create-post) ドキュメントを参照してください。詳細は[こちら](https://devcommunity.x.com/t/announcing-post-editing-via-the-x-api/249534)をご覧ください。
### アクティブなストリーミング接続を管理する Connections API
本日、アクティブなストリーミング接続をプログラム的に管理するための [Connections API](https://docs.x.com/x-api/connections/introduction) を提供開始しました:
* `GET /2/connections` — アクティブおよび過去のストリーミング接続を一覧表示します
* `DELETE /2/connections/all` — アプリのすべてのアクティブなストリーミング接続を終了します
* `DELETE /2/connections/{endpoint_id}` — 特定のストリーミングエンドポイントの接続を終了します
* `DELETE /2/connections` — UUID で特定の接続を終了します
これにより、開発者は「TooManyConnections」エラーを解決し、タイムアウトを待たずに古い接続をクリーンアップできます。
### Community Notes: Evaluate Note エンドポイント
本日、[Community Notes API](https://docs.x.com/x-api/community-notes/introduction) に `POST /2/evaluate_note` エンドポイントを追加しました。AI Note Writer は、提出前にドラフトされたノートを評価し、その潜在的な有用性、主張/意見のアラインメント、その他のモデルフィードバックに関するシグナルを受け取ることができます。
### Filtered Stream Webhooks API の提供開始
本日、[Filtered Stream Webhooks API](https://docs.x.com/x-api/webhooks/stream/introduction) を提供開始しました。永続的な接続を必要とせず、一致する公開投稿を登録済みの Webhook へ非同期に配信します。ルールは既存の `/2/tweets/search/stream/rules` エンドポイントを使用して管理し、一致する投稿 (編集履歴を含む) は JSON として Webhook に配信されます。Enterprise の開発者が利用可能で、プロジェクトあたり 25,000 以上のルール、ルール 1 件あたり最大 2,048 文字をサポートします。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-filtered-stream-webhooks-api/248464)をご覧ください。
### Free 階層から Like および Follow エンドポイントを削除
不正利用、プラットフォーム操作、不正なエンゲージメントに対抗するため、X API Free 階層から `POST /2/users/:id/likes` および `POST /2/users/:id/following` を即時削除しました。有料階層 (Basic、Pro、Enterprise) は影響を受けません。詳細は[こちら](https://devcommunity.x.com/t/update-to-x-api-free-tier-removal-of-like-and-follow-endpoints/247646)をご覧ください。
### PowerStream Rules Lookup エンドポイント
本日、`GET /2/powerstream/rules` エンドポイントを追加しました。PowerStream の顧客は、PowerStream インスタンスに対して構成されたルールをプログラム的に取得できるようになりました。
### `share_with_followers` によるコミュニティ投稿のブロードキャスト
本日、`POST /2/tweets` に新しいオプションのブール型パラメーター `share_with_followers` を追加しました。`community_id` と `share_with_followers: true` で投稿すると、コミュニティ投稿は認証ユーザーのフォロワーのタイムラインにもブロードキャストされます。これは x.com の「フォロワーにも共有する」チェックボックスに対応します。
### Community Notes API の提供開始
本日、[Community Notes API](https://docs.x.com/x-api/community-notes/introduction) を提供開始しました。AI Note Writer が Community Notes にプログラム的に参加するための新しいエンドポイント群です:
* `GET /2/notes/search/posts_eligible_for_notes` — Community Note の対象となる投稿を検索します
* `GET /2/notes/search/notes_written` — 認証された AI Note Writer によって過去に書かれたノートを取得します
* `POST /2/notes` — Community Note を提出します
アクセスには、X Developer AI への登録および Community Notes AI Note Writer の承認が必要です。
### DM Events の動作変更
本日、X API V2 の DM Events の動作を変更しました。新しい変更により、`participant_ids` 配列は `ParticipantsJoin` および `ParticipantsLeave` イベントのみに含まれ、イベント発生時に参加または退出した参加者のみがリストされるようになりました。`MessageCreate` イベントには `participant_ids` 配列が含まれなくなりました。詳細は[こちら](https://devcommunity.x.com/t/upcoming-change-to-x-api-dm-events-endpoints-behavior/241841)をご覧ください。
### Account Activity API エンドポイントの提供開始
本日、新しい X API v2 の [Account Activity API エンドポイント](/x-api/webhooks/introduction)を提供開始しました。詳細は[こちら](https://devcommunity.x.com/t/account-activity-api-is-now-available-in-v2/242895)をご覧ください。
### メディアアップロードエンドポイントの改善
開発者体験を向上させるため、メディアアップロードエンドポイントにいくつかの改善を加えました。チャンクメディアアップロード用の専用エンドポイントを [Media Upload エンドポイント](/x-api/media/introduction)に導入しました。詳細は[こちら](https://devcommunity.x.com/t/media-upload-endpoints-update-and-extended-migration-deadline/241818)をご覧ください。
### OAuth 2.0 でのメールアドレス取得サポート
本日、X API V2 で OAuth 2.0 によるメールアドレス取得のサポートを追加しました。詳細は[こちら](https://devcommunity.x.com/t/announcing-support-for-email-address-retrieval-with-oauth-2-0-in-the-x-api-v2/240555)をご覧ください。
### User Affiliation データの変更
本日、X API V2 の User Affiliation データに変更を加えました。新しい変更により、`affiliation.user_id` は user\_id の配列を返すようになりました。これまでは、ユーザーが複数のアフィリエーションを持っていても、文字列として単一の user\_id を返していました。詳細は[こちら](https://devcommunity.x.com/t/change-to-x-api-user-affiliation-data/237164)をご覧ください。
### Media Upload エンドポイントの提供開始
本日、新しい X API v2 の [Media Upload エンドポイント](/x-api/media/introduction)を提供開始しました。詳細は[こちら](https://devcommunity.x.com/t/announcing-media-upload-endpoints-in-the-x-api-v2/234175/3)をご覧ください。
### 新しいドキュメントサイトの提供開始
本日、新しい X Developer Platform ドキュメントサイト [https://docs.x.com](https://docs.x.com) を公開しました。
### xurl ツールの提供開始
本日、X 開発者向けに API テストを簡素化する新しいツール [xurl](https://github.com/xdevplatform/xurl) を提供開始しました。OAuth 2.0 をサポートしています。
### Community ID Tweet Field の追加
本日、X API v2 に `community_id` Tweet Field を追加しました。詳細は[こちら](https://x.com/tapshah21/status/1860061806653317126)をご覧ください。
### DM ブロックエンドポイントの追加
本日、X API v2 に DM ブロックおよび DM ブロック解除エンドポイントを追加しました。
### ロングフォーム投稿のサポート
本日、4k 文字に代わり 25k 文字のロングフォーム投稿を作成できる機能を追加しました。
### ロングフォーム投稿のサポート
本日、X API v2 を使用してロングフォーム投稿を作成できる機能を追加しました
### User Affiliation の取得
本日、X API v2 を使用してプログラム的にユーザーのアフィリエーションを取得できる機能を追加しました
### Article メタデータの取得
本日、X API v2 を使用して Article メタデータを取得できる機能を追加しました
### プロフィール画像とカバー画像の取得
本日、X V2 API 経由でプロフィール画像とカバー画像の URL を取得できる機能を追加しました
### Connection Status フィールドの追加
本日、X API v2 に `connection_status` フィールドを追加しました。詳細は[こちら](https://devcommunity.x.com/t/announcing-connection-status-field-in-the-user-object-in-the-x-api-v2/212588)をご覧ください。
### Trends ルックアップエンドポイントの追加
本日、X API v2 に Trends ルックアップエンドポイントを追加しました。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567)をご覧ください。
### Users Search エンドポイントの追加
本日、X API v2 に Users Search エンドポイントを追加しました。詳細は[こちら](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567)をご覧ください。
### DM Permissions の取得
本日、X API v2 経由で DM 権限を取得できる機能を追加しました。詳細は[こちら](https://devcommunity.x.com/t/dm-permissions-available-in-the-x-api-v2/209688)をご覧ください。
### Subscription Type フィールドの提供開始
本日、X API v2 の User オブジェクトに `subscription_type` フィールドを提供開始しました。詳細は[こちら](https://devcommunity.x.com/t/new-subscription-type-field-is-available-in-the-twitter-api-v2/209219/2)をご覧ください。
### Get Posts Usage エンドポイント
本日、X API v2 で投稿利用状況をプログラム的に取得するエンドポイントを提供開始しました。詳細は[こちら](https://developer.x.com/en/docs/twitter-api/usage/tweets/api-reference/get-usage-tweets)をご覧ください。
### Reposts Lookup エンドポイントの提供開始
本日、X API v2 で投稿のリポストをルックアップするエンドポイントを提供開始しました。詳細は[こちら](https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweets)をご覧ください。
### 検索エンドポイントの廃止
本日、X API v1.1 の `search/tweets`、`users/search`、`geo/search` エンドポイントを廃止します。詳細は[こちら](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features)をご覧ください。
### Replay API エンドポイントの廃止
本日、エンタープライズ X API から Replay API エンドポイントを廃止します。代わりに [recovery](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features) 機能をご利用いただけます。
### Historical PowerTrack エンドポイントの廃止
本日、エンタープライズ X API から Historical PowerTrack および Insights Track エンドポイントを廃止します。
### Basic および Pro 階層からの Follows エンドポイントの削除
本日、X API v2 の Basic および Pro 階層から Follows および List Follows エンドポイントを削除します。
### Manage Blocks エンドポイントの削除
本日、X API v2 から Manage Blocks エンドポイントを削除します。
### ブックマーク数とロング投稿のサポート
本日、X API v2 でブックマーク数の取得と 280 文字を超える投稿の取得をサポートしました。
### Statuses/Filter エンドポイントの廃止
本日、X API v1.1 の `statuses/filter` エンドポイントを廃止します。開発者は X API v2 の Filtered Stream エンドポイントを利用できます。
### View Counts のサポート
本日、X API v2 で View Counts のサポートを追加します。投稿ペイロードの `public_metrics` に新しいフィールド `impression_count` が利用可能になります。
### Verified Type フィールドの追加
本日、X API v2 に `verified_type` ユーザーフィールドを追加します。これは、ユーザーアカウントが持つ認証の種類 (blue、business、government、または none) を示します。
### Source フィールドの削除
本日、X API の投稿ペイロードから `source` フィールドを削除します。
### Direct Messages エンドポイントの追加
本日、v2 の Direct Messages エンドポイント 6 個を追加します。本リリースには、Direct Message 会話イベントを取得する 3 つの GET メソッドと、新しい Direct Message を作成する 3 つの POST メソッドが含まれます。これらのメソッドは初めてグループ会話をサポートします。
この更新の詳細については、[ブログ記事](https://developer.x.com/en/blog/product-news/2022/new-v2-direct-messages-endpoints)をご覧ください。
### 編集済み投稿メタデータのサポート
本日、X API v2 を使用して開発者が編集済み投稿のメタデータを取得できるようにしました。
この更新の詳細については、[ブログ記事](https://developer.x.com/en/blog/product-news/2022/supporting-edit-tweet-functionality)をご覧ください。
### フィルタリングオペレーターのエイリアスの追加
フィルタリング/クエリオペレーターの「エイリアス」が、Enterprise、Premium、v2 にまたがる Search および Filtered Stream エンドポイントに追加されました。多くの場合、オペレーターは statuses ではなく投稿を参照します。例: `in_reply_to_status_id` のエイリアスとしての `in_reply_to_tweet_id`。その他のケースでは、新しいオペレーターエイリアスがマッチングをより明確にします。例えば、投稿には動画添付ファイルが 1 つしか含められないため、`has:videos` の代わりに `has:video_link` という新しいエイリアスが提供されます。さらに多くの例については、[v2 Filtered Stream オペレーター表](https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule#list)をご覧ください。
### Reverse Chronological Home Timeline の更新
本日より、Reverse Chronological Home Timeline v2 エンドポイントは、過去 7 日間にタイムラインで作成されたすべての投稿、および作成日に関わらず最新 800 件の投稿を返すことができます。
### Filtered Stream 用の新しいフィルタリングオペレーター
本日、Filtered Stream エンドポイントを使用するすべての開発者に対して 10 個の新しい v2 フィルタリングオペレーターが利用可能になり、さらに 10 個が広く利用可能になりました。
この更新の詳細については、[ブログ記事](https://developer.x.com/en/blog/product-news/2022/twitter-api-v2-filtered-stream)をご覧ください。
### Streaming エンドポイントのレイテンシ更新
本日、X API v2 の Streaming エンドポイントの更新を行い、レイテンシを 50% 削減します。
### Essential アクセスでの v1.1 Media エンドポイントの有効化
本日、X API v2 の Essential アクセスで v1.1 Media エンドポイントを有効にします。
この更新の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/v1-1-media-endpoints-available-for-essential-access-in-the-twitter-api-v2/171664)をご覧ください。
### Reverse Chronological Home Timeline エンドポイントの提供開始
本日、フォロー中のアカウントが投稿した最新の投稿とリポストのコレクションを取得できる新しいエンドポイントを提供開始しました。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/reverse-chronological-home-timeline-in-the-twitter-api-v2/171549)をご覧ください。
新しいエンドポイントに加え、[media object](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/media) で `variants` フィールドが利用可能になりました。これにより、URL に添付されているコンテンツのタイプを取得できます。
### Bookmarks エンドポイントの提供開始
本日、X API v2 を使用してブックマークを管理・ルックアップできる新しいエンドポイントを提供開始しました。Bookmarks 機能は長らく X アプリで利用できましたが、これまで API 経由でブックマークを取得、作成、または管理するソリューションを構築するためのエンドポイントはありませんでした。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/build-with-bookmarks-on-the-twitter-api-v2/168804)をご覧ください。
### Quotes Lookup エンドポイントの提供開始
本日、投稿 ID の引用を取得できる [Quotes Lookup エンドポイント](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction)を提供開始しました。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/introducing-the-quote-tweets-lookup-endpoint-to-the-twitter-api-v2/168370)をご覧ください。
### ドキュメントナビゲーションの更新
皆さまからのフィードバックを反映しました。ドキュメント内のコンテンツを見つけるのが難しく、リンクをクリックすると全く別のサイドナビゲーションに遷移して混乱することがありました。
本日、X Developer Platform の全製品を 1 つのサイドナビゲーションから閲覧できる更新済みドキュメントナビゲーションをリリースしました。今回のリリースで、冗長なページを削除し、わかりにくいアイコンを取り除き、ナビゲーション内のさまざまな要素との操作方法を改善しました。
フィードバックがあれば、[フィードバックチャネル](https://twitterdevfeedback.uservoice.com/forums/930250-twitter-api)からお知らせください。
### Reposts および Likes Lookup エンドポイントの改善
本日、[Reposts Lookup](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) および [Likes Lookup](https://developer.x.com/en/docs/twitter-api/tweets/likes/introduction) エンドポイントの改善を提供開始しました。これにより、最後の 100 アカウントだけでなく、投稿にいいねまたはリポストしたすべてのアカウントの完全なリストを取得できます。
この提供開始の詳細については、フォーラムのお知らせをご覧ください。
### OAuth 2.0 認証のサポート
本日より、すべての開発者は Developer Console で OAuth 2.0 を認証方法として選択することで認証できるようになりました。本リリースの一環として、confidential および public クライアントのサポートと、この認証方法を使用するすべての関連 v2 エンドポイントのサポートを追加しました。
OAuth 2.0 は、アプリケーションのスコープに対する開発者の制御を強化し、複数デバイス間の認可フローを改善する業界標準の認可プロトコルです。つまり、X 上のユーザー向けにアプリケーションを構築する開発者は、アプリがユーザーに要求する情報をより細かく制御できるため、必要なデータと情報だけをエンドユーザーに要求すればよくなります。
この最新の認可プロトコルにより、要求した特定のスコープのみを表示する、より合理化されたアプリ認可のための同意フローをエンドユーザーに提示できます。
この提供開始の詳細については、フォーラムのお知らせをご覧ください。
### X API v2 への主要なプラットフォーム更新
**主要なプラットフォーム更新: X API v2 が主要バージョンに、新しい Essential および Elevated アクセス、ポリシー変更**
本日、X API v2 が X API の主要バージョンになることを発表します。X API v2 には、X API 上に構築された既存のアプリの 90% のニーズを満たすのに十分なエンドポイントと機能を提供してきました。
本日、X API v2 の開発者体験をさらに向上させるため、以下の変更を提供開始します:
* API への高速かつ無料の Essential アクセスと、ユースケースが承認された開発者向けの無料の Elevated アクセス。これらのアクセスレベルに関する詳細は、About the X API ページに記載されています。
* X のコア機能を使った開発方法を制限し、アプリを通じてサポートできるユーザー数を制限していた Developer Policy の文言を削除します。
* 私たちはプラットフォームを開放し、X をより良く、より健全にし、公共の対話を拡大するためのツールや製品の構築を皆さまに奨励します。[構築してほしいソリューションのリストはこちらをご覧ください](https://developer.x.com/en/docs/twitter-api/what-to-build)。
* 具体的には、X のコア機能を含む X 体験の複製を制限する文言や、多数のユーザートークンを持つために許可が必要な文言を削除しました。
* X 上のユーザーを支援するソリューションを構築するということは、多くの場合、開発者が X 上で利用可能な機能の一部を構築 (または複製) する必要があることを意味します。今回の Developer Policy 変更は、開発者エコシステムの明確性を向上させ、開発者が公共の対話に対して構築、革新、影響を与えやすいオープンな API プラットフォームを提供することを目的としています。
この提供開始と、これに至った X API v2 のリリースの詳細については、[フォーラム投稿](https://devcommunity.x.com/t/ushering-in-a-new-era-for-the-twitter-developer-platform-with-the-twitter-api-v2/162087)をご覧ください。
これまでの変更履歴に加え、X API v2 にこれまで何がリリースされてきたかを理解するための主要なリソースをまとめました:
* [X API endpoint map](/x-api/migrate/x-api-endpoint-map)
* [About the X API](/x-api/getting-started/about-x-api)
### List Lookup エンドポイントの提供開始
本日、X API v2 に新しい List lookup エンドポイントを提供開始します。これらのエンドポイントにより、フォロワー、メンバー、投稿など、指定したリストの詳細を取得できます。取得したデータは、キュレーション、分析、発見性のユースケースとニーズを解決するソリューションの構築に利用できます。新しい List エンドポイントに加え、Academic Research アクセスレベルで新しい `list:` オペレーターが利用可能になりました。これは Search Posts および Post Counts で使用できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-list-lookup-endpoints-for-the-twitter-api-v2/161965)をご覧ください。
### Spaces エンドポイントの追加機能
Spaces エンドポイントに、Space のチケットを購入した人々のリストを返す機能と、Topics のサポートを追加しています。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/adding-new-functionality-to-spaces-endpoints/161959)をご覧ください。
### Manage Posts エンドポイントの提供開始
本日、X API v2 に新しい Manage Posts エンドポイントを提供開始します。投稿および投稿削除機能に加え、投票の投稿、画像内の人物のタグ付け、返信設定付きの投稿、Super Followers への投稿の機能を追加しました。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-manage-tweets-endpoints-for-the-twitter-api-v2/161501)をご覧ください。
### 埋め込みボタンの変更
本日、X の埋め込みボタンにいくつかの変更を加えます。ボタンが X.com のボタンに合わせてより丸みを帯び、カラーパレットを (ごくわずかに) 更新しました。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/embedded-buttons-have-a-new-look/160528)をご覧ください。
### Lists エンドポイントグループの提供開始
本日、X API v2 に新しい Lists エンドポイントグループを提供開始します。これらのエンドポイントにより、好み、興味、グループ、トピックに基づいて投稿をキュレートおよび整理するソリューションを構築できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-manage-list-endpoints/159980)をご覧ください。
### Mutes Lookup エンドポイントの提供開始
本日、X API v2 に新しい [mutes lookup](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) エンドポイントを提供開始します。このエンドポイントにより、認証ユーザーはミュートしたアカウントの取得と情報の取得ができます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-new-mutes-lookup-endpoint-for-the-twitter-api-v2/159680)をご覧ください。
### OAuth 2.0 ベータの提供開始
本日、X API v2 で OAuth 2.0 と細分化されたスコープのベータを提供開始します。X Developer Platform 上の OAuth 2.0 の将来を形作ることに関心がある開発者は、OAuth 2.0 ベータへのアクセスをリクエストできます。
OAuth 2.0 は認証の業界標準であり、より現代的な認可体験を可能にします。
OAuth 2.0 ベータでは、v2 Project と関連する App でこの新機能をテストし、General Availability リリース前にフィードバックを提供できます。ただし、この OAuth 2.0 実装は現在開発中のため、公開のプロダクション環境やアプリでのテストは避けることを強く推奨します。
この提供開始の詳細については、フォーラムのお知らせをご覧ください。
### Batch Compliance エンドポイントの提供開始
本日、X API v2 を使用する開発者が X データを [Developer Agreement and Policy](https://developer.x.com/en/developer-terms/policy) に準拠して維持しやすくするため、新しい [Batch Compliance エンドポイント](https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/introduction) を X API v2 に提供開始します。これらのエンドポイントを使用すると、開発者や研究者は大量の投稿または User ID をバッチアップロードし、データセットがユーザーの意図と X 上のコンテンツの現在の状態を反映するために必要なアクションを把握できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-batch-compliance-endpoints-available-on-the-twitter-api-v2/158534)をご覧ください。
### Spaces エンドポイントの提供開始
本日、X API v2 に新しい [Spaces エンドポイント](https://developer.x.com/en/docs/twitter-api/spaces/overview) と[新しいトップレベルの Spaces データ辞書](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/space)を提供開始します。Spaces エンドポイントでは、Space ID または user ID で、あるいはタイトルでメンションされている人々のキーワード、ハッシュタグ、ユーザー名を使って Space をルックアップできます。新しいデータ辞書には、Space に関するタイトル、チケット販売状況、参加者メトリクスなどの関連情報が含まれます。すべての user ID はフルオブジェクトに展開できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/introducing-new-spaces-endpoints-on-the-twitter-api-v2/158213)をご覧ください。
### 動画再生回数の制限のための新しいオブジェクト
これまで、エンタープライズの \[Engagement API]/x-api/enterprise-gnip-2.0/fundamentals/engagement-api) で 1800 日以上前の投稿について動画再生メトリクスを要求した場合、あまりコンテキストなしにゼロ値が返されていました。本日より、これらのケースでは `unsupported_for_video_views_tweet_ids` という新しいオブジェクトの配信を開始します。これには、1800 日より古い投稿 ID のカンマ区切りリストが含まれます。これらの投稿について、その他要求されたメトリクスは別のオブジェクトで引き続き受け取ります。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-engagement-api-video-views-object-to-clarify-limitation/158163)をご覧ください。
### Alt Text フィールドの追加
本日、開発者がアクセシビリティをより意識的に構築できるよう、X API v2 の media オブジェクトに `alt_text` フィールドを利用可能にします。
このフィールドを要求するには、`expansions=attachments.media_keys` パラメーターと `media.fields=alt_text` パラメーターを渡す必要があります。リクエストに含まれていれば、alt text を含む画像を含む投稿の alt text を返します。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/media-alt-text-field-now-available-in-twitter-api-v2/157939)をご覧ください。
### Reposts エンドポイントの提供開始
本日、X API v2 に新しい [reposts](https://developer.x.com/en/docs/twitter-api/tweets/retweets) エンドポイントを提供開始します。開発者はこれらのエンドポイントを使用して、認証されたユーザーに代わって投稿をリポストまたはリポストを取り消したり、指定した投稿をリポストしたユーザーを検索したりできます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-retweets-endpoints/156827)をご覧ください。
### Manage Mutes エンドポイントの提供開始
本日、X API v2 に新しい [manage mutes](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) エンドポイントを提供開始します。これらのエンドポイントにより、認証ユーザーはアカウントをミュートまたはミュート解除できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-new-manage-mutes-endpoints-for-the-twitter-api-v2/156261)をご覧ください。
`tweet.fields` パラメーターで `context_annotations` フィールドを要求している場合、[full-archive search](/x-api/posts/full-archive-search) エンドポイントで配信可能な `max_results` を 100 に削減しました。つまり、フィールドを含む投稿はページあたり最大 100 件まで取得できます。
### Streaming エンドポイントの信頼性機能
本日、X API v2 の Filtered Stream および Sampled Stream の信頼性ストリーミング機能 2 つ (backfill および redundant connections) を提供開始します。これは現在 Academic Research プロダクトトラックで利用可能です。
Redundant Connections 機能を使用すると、特定のストリームに 2 回接続でき、ストリームの 1 つが切断された場合でもストリーミングの稼働時間を最大化できます。
Backfill は、ストリーミングリクエストに `backfill_minutes` パラメーターと 1 から 5 までの整数を追加することで利用でき、ストリームの切断によって失われた可能性のあるデータを要求できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-reliability-and-recovery-functionality-available-for-twitter-api-v2-streaming-endpoints/156244/2)をご覧ください。
### Post Counts エンドポイントの提供開始
本日、X API v2 に新しい [Post Counts エンドポイント](/x-api/posts/counts/introduction)を提供開始します。これには 2 つの異なるエンドポイントが含まれます: すべてのプロダクトトラックで利用可能な Recent Post Counts と、現在 Academic Research プロダクトトラックでのみ利用可能な Full-Archive Post Counts です。これらのエンドポイントを使用して、指定したクエリに一致する投稿数を受け取ることができます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/introducing-new-tweet-counts-endpoints-to-the-twitter-api-v2/155997)をご覧ください。
### Teams の改善
本日、コミュニティから寄せられたフィードバックに基づき、Teams の機能の主要な改善を提供開始します。Team ページのスタイルとデザインを更新しました。また、招待フローも変更し、チームメンバーを招待しやすくしたり、招待が失敗した理由を確認しやすくしました。Team アカウントをお持ちの場合は、Developer Console の [Teams ページ](https://developer.x.com/en/portal/teams)で変更を確認できます。Teams の詳細については、\[このトピックに関するドキュメント]\([https://developer.x.com/en/docs/Developer](https://developer.x.com/en/docs/Developer) Console/overview#team) および関連 \[FAQ]\([https://developer.x.com/en/docs/Developer](https://developer.x.com/en/docs/Developer) Console/faq#dev-portal-management-faq) をご覧ください。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-improvements-to-the-functionality-of-teams/155447/2)をご覧ください。
### Configuration エンドポイントの廃止
本日、標準 v1.1 の `GET /help/configuration` エンドポイントを廃止しました。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/retiring-the-1-1-configuration-endpoint/153319)をご覧ください。
### oEmbed エンドポイントの統合
本日、新機能を一貫した方法でサポートするために、v1.1 oEmbed エンドポイントが 2021 年 11 月 23 日に廃止・削除されることを共有します。その日付以降、X oEmbeds (埋め込み投稿およびタイムライン) の唯一の公式かつサポートされる API エンドポイントは publish.x.com/oembed 経由となります。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/consolidating-the-oembed-functionality/154690/2)をご覧ください。
### Blocks および Likes Lookup エンドポイントの提供開始
本日、X API v2 に新しい [blocks](/x-api/users/blocks) および [Likes](/x-api/posts/likes) ルックアップエンドポイントを提供開始します。これらのエンドポイントを使用すると、v2 API を使用して、アカウントがいいねした投稿、投稿にいいねしたユーザー、ご自身または認証ユーザーがブロックしたユーザーに関する情報を取得できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-twitter-api-v2-likes-lookup-and-blocks-lookup/154353)をご覧ください。
### Manage Likes エンドポイントの提供開始
本日、X API v2 に新しい [manage Likes](https://developer.x.com/en/docs/twitter-api/tweets/likes) エンドポイントを提供開始します。これらのエンドポイントを使用すると、v2 API で投稿のいいねといいね解除ができます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-new-manage-likes-endpoints-for-thetwitter-api-v2/152780)をご覧ください。
### Manage Blocks エンドポイントの提供開始
本日、X API v2 に新しい [manage blocks](/x-api/users/blocks) エンドポイントを提供開始します。これらのエンドポイントを使用すると、user ID を使ってユーザーに代わってアカウントをブロックまたはブロック解除できます。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/announcing-manage-blocks-for-twitter-api-v2/152358/2)をご覧ください。
### 埋め込みタイムラインのサポート削除
本日、[埋め込みタイムラインウィジェット](https://developer.x.com/en/docs/x-for-websites/timelines/overview)の将来に関する計画を共有します。2021 年 6 月 23 日に、Likes、Collections、Moments のタイムラインを廃止する予定です。[Profile](https://developer.x.com/en/docs/x-for-websites/timelines/guides/profile-timeline) および [Lists](https://developer.x.com/en/docs/x-for-websites/timelines/guides/list-timeline) のタイムラインを使用することをお勧めします。これらは、より高速で、使いやすく、X の機能性と最新の状態に保たれるよう更新中です。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/removing-support-for-embedded-like-collection-and-moment-timelines/150313)をご覧ください。
### Manage Follows エンドポイントの提供開始
本日、X API v2 に新しい [manage follows](/x-api/users/follows) エンドポイントを提供開始します。これらのエンドポイントを使用すると、ユーザー ID を使ってユーザーに代わってアカウントをフォローまたはフォロー解除できます。この提供開始は、アカウントのフォロワーとフォロー中のユーザーを取得できる [follows lookup](/x-api/users/follows) エンドポイントの提供開始からわずか数か月後のものです。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/introducing-the-new-manage-follows-endpoints-to-the-twitter-api-v2/149465)をご覧ください。
### Academic Research プロダクトトラックの紹介
本日、[X API v2](/x-api/introduction) に新しい [Academic Research プロダクトトラック](/resources/fundamentals/developer-apps)を紹介します。この更新は、Academic Researcher 向けの新しい申請プロセスを導入し、承認された方には、より大きなアクセスと高度な機能を解放する Academic Research [Project](/resources/fundamentals/developer-apps) を提供します。
新しい Academic Research プロダクトトラックでは、以下にアクセスできます:
* 新しい X API v2 [Full-Archive Search エンドポイント](/x-api/posts/full-archive-search) (現時点で Academic Research プロダクトトラックでのみ利用可能)。
* [Standard プロダクトトラック](/resources/fundamentals/developer-apps)の Basic [アクセスレベル](https://developer.x.com/en/products/x-api/early-access/guide#na_2)で利用可能な 500,000 件から増加した 1,000 万件の[Post Cap](/x-api/fundamentals/post-cap)。
* [Recent Search](/x-api/posts/recent-search)、[Full-Archive Search](/x-api/posts/full-archive-search)、および [Filtered Stream](/x-api/posts/filtered-stream) で利用可能な新しいフィルターオペレーター。`$` (別名 cashtag)、`bio` (filtered stream 経由でのみ利用可能)、`bio_name` (filtered stream 経由でのみ利用可能)、`bio_location` (filtered stream 経由でのみ利用可能)、`place`、`place_country`、`point_radius`、`bounding_box`、`-is:nullcast`、`has:cashtags`、`has:geo` を含みます。
* Standard プロダクトトラックの Basic アクセスレベルで利用可能な 25 件から増加した 1,000 件の同時ルールの Filtered Stream ルール制限。
* Standard プロダクトトラックの Basic アクセスレベルで利用可能な 512 文字制限から増加した 1,024 文字のクエリおよびルール文字制限
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/introducing-the-new-academic-research-product-track/148632)をご覧ください。
### Reply Settings フィールドの追加
本日、`reply_settings` という新しいフィールドを投稿オブジェクトに提供開始します。このフィールドは、Post Lookup、Hide Replies、Recent Search、Sampled Stream、Filtered Stream、Follows Lookup、User Post Timeline、User Mention Timeline など、投稿を返すすべての X API v2 エンドポイント、またはどのエンドポイントでも投稿オブジェクトを[expand](/x-api/fundamentals/expansions)することで利用可能です。
このフィールドは、投稿作成者が他の人にどのように返信を許可しているかを示します。全員か、投稿内でメンションした人々のみか、フォローしている人々のみです。`reply_settings` フィールドが返すフィールド値には、`everyone`、`mentionedUsers`、`following` が含まれます。投稿に会話のコントロールが設定されていない場合でも、フィールドに `everyone` 値が設定された投稿オブジェクトに表示されます。
### User Post および Mention Timeline エンドポイントの提供開始
本日、X API v2 に新しい [User Post Timeline および User Mention Timeline エンドポイント](/x-api/posts/timelines)を提供開始します。これらのエンドポイントにより、X 上の指定されたアカウントが作成した、または言及している投稿を要求できます。詳細はフォーラム投稿のお知らせをご覧ください。
### Follows Lookup エンドポイントの提供開始
本日、X API v2 に新しい [follows lookup エンドポイント](/x-api/users/follows)を提供開始します。これらのエンドポイントにより、ユーザー ID を使ってアカウントのフォロワーとフォロー中のユーザーを取得できます。詳細はフォーラム投稿のお知らせをご覧ください。
### Labs v2 エンドポイントの廃止
Labs v2 Recent Search および Hide Replies エンドポイントを廃止しました
以下のエンドポイントを廃止しました。これらのエンドポイントの Labs バージョンを使用していた場合は、リンクされた移行ガイドを使用して統合を更新し、新しい X API v2 バージョンの使用を開始できます:
* [Recent search v2](/x-api/posts/search/migrate/overview)
* [Hide replies v2](/x-api/posts/hide-replies/migrate)
新しい X API v2 への移行に関する追加情報も、[移行ハブ](/x-api/migrate/overview)で提供しています。
ご質問がある場合は、[Labs フォーラムカテゴリ](https://devcommunity.x.com/c/labs/57)までお問い合わせください。
### Labs v1 エンドポイントの廃止
2020 年 8 月 12 日に、新しい X API v2: Early Access を提供開始しました。このリリースで、Labs プログラムから X API v2 にいくつかのエンドポイントを昇格し、エンドポイントの Labs バージョンは廃止状態のまま 60 日間維持された後に廃止されることを発表しました。
本日は提供開始から 60 日目にあたり、以下のエンドポイントを廃止しました。これらのエンドポイントの Labs バージョンを使用している場合は、リンクされた移行ガイドを使用して統合を更新し、新しい X API v2 バージョンの使用を開始できます:
* Post Metrics v1
* Filtered Stream v1
* Sampled Stream v1
新しい X API v2 への移行に関する追加情報も、[移行ハブ](/x-api/migrate/overview)で提供しています。
ご質問がある場合は、[Labs フォーラムカテゴリ](https://devcommunity.x.com/c/labs/57)までお問い合わせください。
### 投稿消費ステータスバーの追加
新しい Developer Console の[メインダッシュボードページ](https://developer.x.com/en/portal/dashboard)で、月あたり 500,000 件の[Post Cap](/x-api/fundamentals/post-cap)に対する利用状況を確認できるようになりました。この上限は、Basic アクセスの以下の v2 エンドポイント (Filtered Stream および Recent Search) に対して、Project レベルで適用されます。
この機能を確認し、新しい v2 エンドポイントを使用するには、[新しい Developer Console 体験](https://developer.x.com/en/portal/opt-in.html)をアクティブにする必要があります。
### Hide Replies エンドポイントの提供開始
本日、v2 X API に新しい Hide Replies エンドポイントを提供開始します。このエンドポイントを使用すると、虐待的、邪魔、または誤解を招く返信を非表示にできます。これは、公共の対話の健全性を改善する重要な要素です。詳細はフォーラム投稿のお知らせをご覧ください。
X Developer Labs の同じエンドポイントは廃止状態となり、90 日後に廃止されます。[v2 エンドポイントへの移行方法](/x-api/posts/hide-replies#comparing-twitter-apis-hide-replies-endpoints)をご覧ください。
### X API v2 エンドポイントへの Early Access
本日、[新しい X API の最初のエンドポイントへの Early Access](https://blog.x.com/developer/en_us/topics/tools/2020/introducing_new_twitter_api.html) を発表しました!
新しい X API は、より迅速に新機能を提供できる新しい API 基盤、受け取るフィールドをより細かく制御できる更新されたデータ形式と新機能、新しい投稿、ユーザー、メディアフィールド、および以下を含む投稿の聞き取りと分析を可能にする更新されたエンドポイントセットを備えています:
* [Post lookup](/x-api/posts/post-lookup-by-post-ids)
* [User lookup](/x-api/users/user-lookup-by-id)
* [Recent search](/x-api/posts/recent-search)
* [Filtered stream](/x-api/posts/filtered-stream)
* [Sampled stream](/x-api/stream/stream-sampled-posts)
利用可能な新機能の完全なリストと移行リソースは、\[X API v2: Early Access ドキュメントページ][https://developer.x.com/en/docs/x-api/early-access](https://developer.x.com/en/docs/x-api/early-access)) でご覧いただけます。
計画している内容の詳細については、「\[Guide to the future of the X API][https://developer.x.com/en/docs/x-api/early-access)」をご覧ください。](https://developer.x.com/en/docs/x-api/early-access\)」をご覧ください。)
### Labs エンドポイントの廃止予定
本リリースで X API v2 の代替が提供開始されたため、特定の Labs エンドポイントを廃止します。
以下の Labs v1 エンドポイントは、本日のリリースから 60 日後に廃止されます:
* Post Metrics v1
* Filtered Stream v1
* Sampled Stream v1
以下の Labs v2 エンドポイントは、本日のリリースから 90 日後に廃止されます:
* Recent Search v2
### Hide Replies の改善
返信の非表示解除機能を追加しました。さらに、以前非表示にしていなかった返信も、このエンドポイント経由で再度非表示にできるようになりました。
詳細は [Hide Replies ドキュメント](https://developer.x.comhttps://developer.x.com/en/docs/labs)をご覧ください。
### Labs v1 エンドポイントの廃止
本日、Labs v1 の Posts and Users、Hide Replies、Recent Search エンドポイントを廃止します。
Labs v1 計画の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/update-on-labs-v1-endpoints/138641)をご覧ください。
### Quote Tweets メトリックの追加
本日、`quote_tweets` メトリクスは [/totals](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api#post-insights-engagement) エンドポイント経由で「unowned」投稿に対して利用可能になりました。つまり、アプリ専用の認証を使用してすべての投稿の引用数にアクセスできます。
この変更の詳細については、[フォーラム投稿](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131)をご覧ください。
### 新しい投稿メトリクスの追加
本日、X Developer Labs の Post Lookup エンドポイントの投稿オブジェクトに、2 つの新しい非公開メトリクスのサブフィールド `user_profile_clicks` および `url_link_clicks` を追加します。これらは、`tweet.fields` パラメーターに `non_public_metrics`、`organic_metrics`、または `promoted_metrics` のいずれかの値を指定して使用すると返されます。
詳細については、[Post Lookup API リファレンス](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets-id)をご覧ください
### リポスト数の変更
本日より、X ウェブ、iOS、Android では、投稿ごとに「リポストとコメント」の合計数を表示します。X API を使用する場合、X インターフェイスに一致する「リポストとコメント」の合計数は、`retweet_count` と利用可能な場合の `quote_count` を加算して計算できます。さらに、`quote_count` は、投稿を引用した投稿の合計数ではなく、投稿を引用したユニークアカウントの合計数となります。詳細は[フォーラム投稿](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131/2)をご覧ください。
### Organic および Promoted メトリクスグループ
Post Lookup エンドポイントの投稿およびメディアオブジェクトに `organic_metrics` および `promoted_metrics` を追加します。
### エンドポイントへのメトリクスの追加
Post Lookup および Recent Search エンドポイントの投稿およびメディアオブジェクトにメトリクスを追加します。
これらの変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/adding-metrics-to-the-tweets-and-recent-search-endpoints-in-labs/135315)をご覧ください
### COVID-19 エンドポイントの提供開始
本日、新しい COVID-19 Stream エンドポイントと、それに付随する Compliance エンドポイントを提供開始します。
これらの変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-covid-19-stream-endpoint-available-in-twitter-developer-labs/135540)をご覧ください。
### Replay API ユーザープロフィールの更新
本日より、Replay API は、Replay API の実行時に参照されたユーザーを反映するユーザープロフィールオブジェクトを配信します。現在のユーザープロフィールオブジェクトを配信するこの変更は、2019 年 11 月 25 日の Historical PowerTrack の最近の更新と同様です。
### 投稿注釈の追加
Posts および Recent Search エンドポイントの投稿オブジェクトに注釈を追加します。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/adding-annotations-to-tweets-and-recent-search-endpoints-in-labs/135193)をご覧ください。
### Developer Policy の更新
本日、[Developer Policy の重要な更新](https://developer.x.com/en/developer-terms/policy)を発表しました。[フォーラム](https://devcommunity.x.com/t/a-new-easier-to-understand-twitter-developer-policy/135038)と[ブログ](https://blog.x.com/developer/en_us/topics/community/2020/twitter_developer_policy_update.html)の投稿を通じて詳細を読み、改訂されたポリシーを確認することをお勧めします。Developer Policy は、X API を使用するための基盤の 1 つであり、ご自身のコミットメントを理解することが重要です。
### Hide Replies エンドポイントの提供開始
私たちは、X 上で人々が安心して会話できるようにすることを支援したいと考えています。その一環として、本日、新しい [エンドポイント](/x-api/posts/hide-replies)で Hide Replies 機能をサポートし、投稿作成者が始めた会話をより制御できるようにすることをお知らせします。
この新しいエンドポイントの詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/introducing-the-hide-replies-endpoint/134683)をご覧ください。
### Labs エンドポイント v2 のリリース
本日、Posts and Users、Recent Search、Hide Replies エンドポイントを Labs の v2 に提供します。Labs v1 エンドポイントを廃止し、この初回リリースから 90 日後に完全に廃止する予定です。v1 ドキュメントもこの期間中は利用できるようにします。[フィードバックチャネル](https://twitterdevfeedback.uservoice.com/)を通じて、このバージョン戦略に関するフィードバックをお寄せください。
Posts and Users に以下の変更をリリースします:
* クエリパラメーターとして[fields](/x-api/fundamentals/fields)を導入
* クエリパラメーターとしての[formats](https://developer.x.com/en/docs/labs#payload)を削除
* Posts and Users で単一 ID [lookup](https://developer.x.com/en/docs/labs/overview/versioning/migration-guide#id-lookup-path)用のパス変数を追加
* GET /users における単一およびマルチユーザー名[lookup](/x-api/migrate/overview#username-lookup-path)のパスおよびクエリパラメーターの調整
* フィールド名を `stats` から `public_metrics` に変更
その他の変更には以下が含まれます:
* Users から `most_recent_tweet_id` 拡張を削除
* 投稿の `source` フィールドからフィールドのパースをしやすくするため HTML タグを削除
Recent Search の中核の検索、ページネーション、その他の機能は同じままです。
v1 から v2 にアップデートする際の[移行資料](/x-api/migrate/overview)をいくつかまとめました。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/releasing-a-new-version-of-labs-endpoints/134219)をご覧ください。
### Compliance Firehose への Drop/Undrop イベントの追加
本日、Compliance Firehose API に新しい drop/undrop イベントタイプを追加しました。詳細は[ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/firehouse)をご覧ください。
### アクセストークン管理の変更
本日、[developer.x.com 上のアプリケーションダッシュボード](https://developer.x.com/content/developer-twitter/en/apps)でアクセストークンおよびアクセストークンシークレットの表示・管理方法に変更を加えます。
API 統合をより安全にするため、これらの値が最初に生成された後は、ダッシュボードでアクセストークンとアクセストークンシークレットを表示しなくなります。
最初の表示後、これらの認証情報は取得できなくなります。ダッシュボードでトークンを再生成できますが、これにより現在のトークンとシークレットは無効になります。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/upcoming-changes-to-access-token-and-secret-management/130851)をご覧ください。
### SPDY サポートの削除
2020 年 1 月 15 日より、X API (および他のすべての X ドメイン) へのすべての接続で SPDY 接続をサポートしなくなります。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/removing-support-for-spdy-protocol-on-twitter/132530)をご覧ください。
### Labs での Recent Search エンドポイントの提供開始
本日、[過去 7 日以内に投稿された投稿を検索する](/x-api/posts/recent-search)新しいエンドポイントをリリースします。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-recent-search-endpoint-available-in-labs/133076)をご覧ください。
### Twurl CLI の更新
X API CLI の新しい更新済みメジャーリリース `[twurl](https://github.com/twitter/twurl)` が利用可能になりました。このリリースには、いくつかのバグ修正と機能拡張が含まれ、Premium および X Developer Labs エンドポイント周辺の機能を追加するための Bearer Token サポートが導入されています。詳細は[フォーラム投稿](https://devcommunity.x.com/t/twurl-0-9-5-released/132966)をご覧ください。
### Stream への投稿注釈の追加
本日 X Developer Labs で、デフォルトの投稿ペイロードに新しいメタデータ要素をリリースします。これらの新しいフィールドは、投稿ペイロードの一部としてレンダリングされ、投稿に関するより多くの文脈情報を提供します。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/tweet-annotations-added-to-the-tweet-object-for-the-sampled-stream-and-filtered-stream-endpoints-in-labs/132407)をご覧ください。
### Historical PowerTrack ユーザープロフィールの更新
本日、「Batch Historical Posts」エンドポイント (Historical PowerTrack) を更新し、ジョブ処理時の値を反映するユーザープロフィールの位置情報、自己紹介、表示名情報を提供します。更新されたユーザーオブジェクトが配信されると、User/Actor オブジェクトに新しい「updated」文字列配列が含まれます。
最大 3 つの値があります: name、description、location:
`"updated": ["name", "description", "location"]`
詳細は [Historical PowerTrack のデータ形式に関するドキュメント](https://aem-author-production-version-6-3.twitter.biz/content/developer-twitter/en/docs/tweets/batch-historical/guides/powertrack-data-format.html)をご覧ください。
### Account Activity API への追加
本日、Account Activity API に新機能をリリースしました。これにより、開発者は、サブスクライブしているユーザーをメンションするアカウントがブロックされているかどうかを確認できるようになります。
`user_has_blocked` の[データオブジェクト構造](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure)と詳細は、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-release-account-activity-api-user-has-blocked-field/131157)をご覧ください。
### Labs での Sampled Stream エンドポイントの提供開始
本日、すべての公開投稿のサンプルをリアルタイムで投稿された通りに [ストリーミング](/x-api/posts/recent-search) する新しいエンドポイントをリリースします。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-sampled-stream-endpoint-available-in-labs/130958)をご覧ください。
### Labs での Filtered Stream エンドポイントの提供開始
本日、X Developer Labs で投稿を取得するための[新しいストリーミングエンドポイント](/x-api/posts/filtered-stream)と、フィルターを管理するエンドポイントをリリースします。これらのエンドポイントでは、月あたり最大 500,000 件の投稿 (最大 1 秒あたり 50 投稿) を取得でき、ストリームに最大 10 個のフィルタールールを設定できます (同時に適用可能)。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-filtered-stream-endpoints-available-in-labs-and-the-future-of-statuses-filter/129888)をご覧ください。
API リファレンスページに記載されたリクエストパラメーターは、オプションまたは必須として明確に示されています。さらに、リクエストで JSON ボディペイロードが許可されている場合、API リファレンスページにはそれが記述されます。
### Labs での投稿メトリクスの提供開始
所有/承認されたアカウントの任意の投稿または投稿のリストのエンゲージメントデータを取得できるようになりました。クエリする投稿は 30 日以内のもので、リポストではない必要があります。
[GET /tweets/metrics/private](https://developer.x.com/en/docs/labs/tweet-metrics/overview.html) は以下のメトリクスをサポートします:
* `impressions`
* `reposts`
* `quotes`
* `likes`
* `replies`
* `video views`
* `video view quartiles` (リクエスト元がメディアの作者でもある場合)
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-twitter-developer-labs-release-metrics-endpoint/129122)をご覧ください。
### DM 権限の変更
本日より、Direct Message を作成する必要があるアプリケーションは、「Read, Write, and Direct Messages」アプリ権限 (RW+DM) を持つ必要があります。RW アプリ権限のみで Direct Message を作成しようとするアプリケーションは、以下のエラーを受け取ります:
`{"code": 93,"message": "This application is not allowed to access or delete your direct messages."}`
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/updates-to-app-permissions-direct-message-write-permission-change/128221)をご覧ください。
### Pinned Post 拡張の追加
`pinned_tweet_id` は、user オブジェクト拡張を通じてユーザーの固定投稿を展開します。
### Quote Counts メタデータの追加
開発者は新しい Labs エンドポイントを使用して、引用の数を取得できます。
### Most Recent Post 拡張の追加
`most_recent_tweet_id` は、user オブジェクト拡張を通じてユーザーの最新の投稿を展開します。
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/update-to-twitter-developer-labs/128060)をご覧ください。
### TLS 1.2 の要件
本日より、X API (および他のすべての X ドメイン) へのすべての接続で TLS 1.2 が必要になります。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/removing-support-for-legacy-tls-versions-1-0-1-1-on-twitter/126648/2)をご覧ください。
### 新しい Account Activity API エンドポイント
本日より、アプリ専用 OAuth を使用してユーザーサブスクリプションを無効化するための新しい [Account Activity API エンドポイント](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference)を導入します。
この新しいエンドポイントは、開発者にとって、サブスクライブしているユーザーのアクセストークンを必要とせず、サブスクリプションを無効化するために bearer トークンだけを提供すればよいという利便性を提供します。
3-Legged OAuth でユーザーサブスクリプションを無効化するための既存のエンタープライズ Account Activity API エンドポイントは即時に廃止予定としてマークされます。このエンドポイントは 2020 年 1 月 15 日に廃止され、利用できなくなります。
開発者はこの API の詳細を[ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference)で学べます。
### Tweets エンドポイントの新しい拡張
\[GET /tweets][https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets.html](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets.html)) エンドポイントに 2 つの新しい拡張を追加しました:
`entities.mentions.username` は、投稿内の認識されたユーザーメンションのユーザー名を完全な user オブジェクトに展開します。
`referenced_tweets.id.author_id` は、要求した投稿の 1 つがリポスト、引用投稿、または返信である場合に、参照された投稿の作者の ID を展開します。この拡張は、参照された投稿 ID を完全なオブジェクトにも展開します。
### Labs での Tweets および Users エンドポイントのサポート
最初の 2 つのエンドポイントが Labs ポータル経由で利用可能になりました。これらのエンドポイントを使い始めるには、承認済みの開発者アカウントを持ち、Labs アクセスを申請している必要があります。
v1.1 同等機能との[主な違い](https://developer.x.com/content/developer-twitter/en/docs/labs/overview/whats-new)は以下を含みます:
* 単一オブジェクトの「show」機能とバッチ「lookups」用の単一エンドポイント
* \[Expansion parameters]) は 1 つのリクエストの一部として追加オブジェクト (例: メンションされたユーザー、参照された投稿など) の包含をサポート
* \[Format parameters]) は、より冗長な、または冗長でないペイロードを持つ異なるデータプロジェクションをサポート
* 認証方法 (ユーザーコンテキストまたは bearer トークン) に関わらず、レート制限はアプリレベル
この提供開始の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/twitter-developer-labs-is-open-to-all-developers/126717)をご覧ください。
### Terms および Privacy エンドポイントの廃止
Terms of Service および Privacy エンドポイントを完全に廃止しました。当社の [Privacy Policy](https://x.com/en/privacy) および [Terms of Service](https://x.com/en/tos) の現在の状況は、最新のウェブページで最もよく確認できます。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/terms-of-service-and-privacy-endpoints-will-no-longer-serve-content-after-june-10/125714)をご覧ください。
### User オブジェクトフィールドの変更
本日より、`user.lang` を含む一部の user オブジェクトフィールドは、[フォーラム投稿](https://devcommunity.x.com/t/upcoming-changes-to-user-object-and-get-users-suggestions-endpoints/124732)で以前にお知らせしたメタデータフィールドに対して「null」を返し始めます。
開発者は、この変更について[ドキュメント](/x-api/fundamentals/data-dictionary/reference#user)で学べます。
### Account Activity Replay API の提供開始
本日、[Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) のエンタープライズ層で利用可能なデータ復旧ツールである [Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) を導入します。
[Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) を使用すると、最大 5 日前までのイベントを取得できます。これは、[Webhook](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference) サーバーがイベントを取りこぼした場合のデータ復旧シナリオで利用してください
開発者はこの API の詳細を[ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)で学べます。
### Quotes でのネイティブメディアのサポート
本日より、X 上の引用にネイティブメディア (写真、動画、GIF) を追加できるようになり、引用ペイロードの entities セクションに追加のメディアメタデータとして表示されます。
開発者はこの詳細を[ドキュメント](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/tweet)で学べます。
### is:reply オペレーターの追加
本日、`is:reply` オペレーターが [enterprise search APIs](/x-api/enterprise-gnip-2.0/fundamentals/search-api) および有料版の [premium search エンドポイント](https://developer.x.com/content/developer-twitter/en/docs/tweets/search/api-reference/premium-search) で利用可能になりました。
`is:reply` ブールオペレーターは、投稿へのすべての返信をフィルターしたり、ルールに一致する明示的な返信を除外したりするのに使用できます。このオペレーターは `is:quote` オペレーターと同じように機能します。
Search API では、すべての「is:」および「has:」オペレーターは、キーワードやハッシュタグなどのスタンドアロンオペレーターと組み合わせて使用する必要があることに注意してください。
このオペレーターの詳細は[ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering)で学べます。
### Expanded URL エンリッチメントの変更
本日より、Expanded URL エンリッチメントには、投稿、Moment、またはプロフィールへのリンクの場合、unwound URL オブジェクトとメタデータ (title および description フィールドを含む) が含まれなくなります。その他の URL (ウェブサイトなど) は引き続きこのメタデータでエンリッチされ、url、expanded\_url、`display_url` は引き続き利用可能です。この変更は [Decahose](/x-api/enterprise-gnip-2.0/fundamentals/decahose-api)、[PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api)、[Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview)、および [Search APIs](https://developer.x.com/en/docs/x-api/v1/tweets/search/overview) に適用されます。
### PowerTrack での is:reply オペレーターの追加
本日、新しいオペレーター `is:reply` を導入します。これにより、会話を最も気にかけるものに絞り込むことができます。結果から返信を除外できるようになりました (リポストを除外する `is:retweet` および引用投稿を除外する `is:quote` の既存の機能に加えて)。この新しいオペレーターは、本日から [PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api)、[Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview)、および [Replay](/x-api/enterprise-gnip-2.0/powertrack-api#replay-api) で利用可能です。
`is:reply` ブールオペレーターは、投稿へのすべての返信をフィルターしたり、ルールに一致する明示的な返信を除外したりするのに使用できます。このオペレーターは `is:quote` オペレーターと同じように機能します。
このオペレーターの詳細は[ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering)で学べます。
### Developer Console でのアプリへのアクセス
本日、X アカウントにログインしていれば、developer.x.com の [X app ダッシュボード](https://developer.x.com/content/developer-twitter/en/apps)で既存の [X apps](/resources/fundamentals/developer-apps) を表示および編集する機能を開発者に追加しました。以前は、developer.x.com で既存の X アプリを表示および編集するには、[開発者アカウント](/resources/fundamentals/developer-portal)に申請するか承認を受ける必要がありました。
新しい X アプリを作成するには、引き続き承認済みの開発者アカウントが必要です。
### 動画字幕のサポート
本日、広告主およびパブリッシャーが、ads.x.com、Media Studio、およびパブリッシャーアップロード API 経由で、動画に字幕ファイル (SRT) を追加できるようになりました。字幕は、Android および Web 上の自動再生動画 (音声がない場合) で表示可能になります。iOS の機能は今後数週間でリリース予定です。
新しい字幕エンドポイントの詳細については、それぞれの API リファレンスページをご確認ください:
* [POST media/subtitles-create](/x-api/media/create-media-subtitles)
* [POST media/subtitles-delete](/x-api/media/delete-media-subtitles)
### Account Activity API エンドポイントの更新
本日、[Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) エンドポイント [GET subscriptions/count](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count) の更新を発表します。請求の詳細と API の使用についての可視性を高めるため、本日から、Account Activity API インスタンスに関連付けられたプロビジョニング済みサブスクリプションの数を JSON 内でプログラム的に取得できます。これにより、GET subscriptions/count API エンドポイント経由で、プロビジョニング済みサブスクリプションの数と、その制限にどれだけ近づいているかの両方を確認できます。
この更新は [Account Activity API ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count)に記載されています。
### POST エンドポイントへの新しいレート制限
本日、いくつかの標準 POST エンドポイントに新しいアプリレベルのレート制限を実装します:
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet/:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweets-id)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-post-endpoint-rate-limit-enforcement-begins-today/115355)をご覧ください。
### twitter-text ライブラリの更新
本日、X が絵文字をカウントする方法の最近の変更に対応するため、[twitter-text](https://github.com/twitter/twitter-text) ライブラリの更新を発表します。以前は絵文字が 2 文字以上としてカウントされていましたが、その数は 2 文字に削減され、ユーザーが 280 文字を最大限活用できるようになります。
この変更の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/new-update-to-the-twitter-text-library-emoji-character-count/114607)をご覧ください。
### レガシー DM エンドポイントの廃止
レガシー Direct Message エンドポイントを完全に廃止しました。廃止された DM エンドポイントとその代替のリストは \[このページ]\([https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference) でご確認いただけます。
この更新の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746)をご覧ください。
### DM メディアアクセスの変更
本日、[Direct Messages からの添付メディアの取得](https://developer.x.com/en/docs/x-api/v1/direct-messages/message-attachments/overview)プロセスにいくつかの変更を実装します。認証された [www.x.com](http://www.x.com) セッション経由での `media_url` または `media_url_https` へのアクセスをサポートしなくなります。`media_url_https` を取得するリクエストは、OAuth 1.0A を使用して常にユーザーのアクセストークンで署名する必要があります。
この更新の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/direct-message-api-change-to-how-apps-can-access-images-sent-in-direct-messages/112722)をご覧ください。
### User および Site Streams の廃止
[User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) および [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) を完全に廃止しました。
この更新の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746)をご覧ください。
### Usage API の新バージョン
本日、Usage API の新バージョンを提供開始します。この更新により、新しいシステムへの移行を行うことで API がより安定します。
システムの更新に伴い、開発者は 2018 年 5 月 1 日までしかデータを取得できなくなるため、ユーザーはデータの「穴」を経験することになります。したがって、来年は数か月分の履歴データが欠落します (2019 年 6 月まで)。
Usage API 内で、製品名が Historical PowerTrack Subscription から Historical PowerTrack 2.0 に変更されます。これは、製品名を他のユーザー向け文言と一貫させるものです。お客様は更新後も同じ形式の同じデータを受け取ります。この変更は `products.type` JSON オブジェクト内で確認できます。
ご質問がある場合は、アカウントマネージャーまでお問い合わせください。
### API の廃止
本日、[Account Activity API DM Beta](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) プロダクトが完全に廃止されました。
本日から、以下のサービスとエンドポイントはサービスが低下します:
* [User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [GET direct\_messages](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/list-events)
* [GET direct\_messages/sent](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message)
* [GET direct\_messages/show](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-message)
* [POST direct\_messages/new](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/new-message)
* [POST direct\_messages/destroy](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message)
User Streams および Site Streams は 8 月 23 日に完全に廃止されます。
レガシーの Direct Messages エンドポイントは 9 月 17 日に完全に廃止されます。
この更新の詳細については、[フォーラムのお知らせ](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746)をご覧ください。
### アプリ作成およびレート制限の変更
本日より、[apps.x.com](https://apps.x.com/) 経由で新しい [X apps](/resources/fundamentals/developer-apps) を作成できなくなります。今後は、[Developer Console](/resources/fundamentals/developer-portal) アカウント、または Developer Console アカウントをまだお持ちでない場合は、[アクセスを申請できるページ](https://developer.x.com/content/developer-twitter/en/apply-for-access)にリダイレクトされます。
また、2018 年 9 月 10 日に以下の POST エンドポイントに新しいアプリレベルのレート制限を実装することを発表しました。
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-retweet-id)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-favorites-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
最後に、お客様によるプラットフォームポリシーの違反疑いを開発者に報告するための新しいオプションを導入しています。
これらすべての更新の詳細については、[ブログ投稿](https://cli.re/g32qKr)をご覧ください。
### Developer Console でのアプリ管理
[Developer Console](/resources/fundamentals/developer-portal) アカウントをお持ちの場合は、[X apps](/resources/fundamentals/developer-apps) を作成および管理できるようになりました。詳細は\[フォーラム投稿]\([https://devcommunity.x.com/t/app-creation-and-management-now-available-in-the-Developer](https://devcommunity.x.com/t/app-creation-and-management-now-available-in-the-Developer) Console/107723)をご覧ください。
### Sign in with X および Account Activity の変更
本日より、Sign in with X プロセスで使用する[コールバック URL](/resources/fundamentals/developer-apps#callback-urls) の登録を必須化しました。この更新の詳細は[こちら](https://devcommunity.x.com/t/action-required-sign-in-with-twitter-users-must-whitelist-callback-urls/105342)をご覧ください。
また、Account Activity API に `tweet_delete_events` アクティビティを追加することを発表しました。この新しいアクティビティは、対応する削除イベントに対して送信され、開発者がお客様やアプリケーションユーザーに準拠した体験をより容易に提供できるようにします。この新しいアクティビティの詳細については、[フォーラム投稿](https://devcommunity.x.com/t/adding-delete-events-to-the-account-activity-api/106783)または[ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)をご覧ください。
### 利用規約とポリシーの更新
本日、[Terms of Service](https://x.com/en/tos)、[Privacy Policy](https://x.com/en/privacy)、および \[X Developer Agreement][https://developer.x.com/en/developer-terms/agreement-and-policy](https://developer.x.com/en/developer-terms/agreement-and-policy) にいくつかの変更を加えました。これには、プライバシー、セキュリティ、データ保護の更新が含まれます。詳細は[フォーラム投稿](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)をご覧ください。
### タイムゾーンフィールドの非公開化
本日、X user オブジェクトの timezone 値がプライベートフィールドになりました。今後、すべての\* `time_zone` および `utc_offset` データオブジェクトは null として返されます。詳細は[フォーラム投稿](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)をご覧ください。
\* これらは引き続き、認証済みユーザーのみに対して account/settings エンドポイントで利用可能です。
### Klout データの削除
本日、GDPR 更新の一環として、投稿ペイロードからすべての Klout データを削除しました。
### Profile Background および Account Activity の変更
本日、`profile_background_image_url` および `profile_background_image_url_https` のすべてのインスタンスをデフォルト値に変更します。詳細は[フォーラム投稿](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)をご覧ください。
上記の変更に加え、[Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) のペイロードに、アクティビティが配信されたサブスクリプションを参照するための新しいフィールドを追加します。この JSON オブジェクトは `for_user_id` と呼ばれ、そのアクティビティを生成したサブスクライブ済みユーザーの ID を値として含みます。この新しい JSON オブジェクトの例は、[Account Activity オブジェクト](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure)ページで確認できます。
### Quote ペイロードレンダリングの変更
本日、引用ペイロード内での URL のレンダリング方法に変更を加えました。
引用された投稿を参照できるようにするため、「quoted\_status\_permalink」エンティティと呼ばれる新しいエンティティを追加し、引用された投稿の「text」フィールドから t.co リンクを削除します。
新しい形式では、t.co リンクは「quoted\_status」オブジェクト内の引用された投稿の「text」フィールドに追加されなくなります。
さらに、引用された投稿の t.co URL、expanded\_url、display\_url を「urls」エンティティに含めなくなります。代わりに、「url」、「expanded」、「display」URL 属性を持つ新しい「quoted\_status\_permalink」オブジェクトに追加されます。つまり、「quoted\_status\_permalink」オブジェクトは、引用された投稿への t.co リンク専用となり、「entities.urls」配列は元の投稿または引用内で共有されたリンクを識別するために使用できます。
詳細は[フォーラム投稿](https://devcommunity.x.com/t/updating-how-urls-are-rendered-in-the-quote-tweet-payload/105473)および[更新されたドキュメント](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)をご覧ください。
### X Kit の廃止
[X Kit](https://developer.x.com/en/docs/x-for-websites) の廃止を発表しました。2018 年 10 月 31 日以降、X Kit はアクティブにメンテナンスされなくなります。詳細は[ブログ投稿](https://blog.x.com/developer/en_us/topics/tools/2018/discontinuing-support-for-twitter-kit-sdk.html)をご覧ください。
### GDPR に向けたプラットフォーム更新
本日、GDPR に関連するプラットフォームへのいくつかの更新を発表しました。詳細は[フォーラム投稿](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)をご覧ください。
### Additional Media Info オブジェクトの追加
投稿ペイロードに新しいオブジェクトを追加 (`additional_media_info` オブジェクト)、また、広告主が動画再生を X 所有のクライアントに制限することを要求したプロモーション投稿の動画詳細 (`video_info`) を制限します。この変更に関する追加情報は、[Extended Entities Objects > ネイティブ動画付きの投稿](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities)で確認できます。
### Premium Full-Archive Search の提供開始
[Premium Full-Archive Search エンドポイント](https://blog.x.com/developer/en_us/topics/tools/2018/access-the-full-history-of-tweets.html) の提供開始。
### Account Activity API の提供開始
([All Activities](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)) および ([Direct Messages](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)) Standard beta Account Activity API の両方を提供開始しました。この提供開始の詳細は[ブログ](https://blog.x.com/developer/en_us/topics/tools/2017/announcing-more-functionality-to-improve-customer-engagements-on-twitter.html)をご覧ください。User streams および Site streams の廃止と、2018 年 6 月 19 日 (火) のサンセット日を発表しました。
### twitter-text ライブラリの更新
twitter-text のバージョン 2.0 が [GitHub](https://github.com/twitter/twitter-text) で利用可能になりました。この更新は、2017 年 11 月 7 日に展開された文字数制限の変更に対応します。詳細は[フォーラム](https://devcommunity.x.com/t/shipped-twitter-text-2-0/98577)をご覧ください。
### Premium API の提供開始
Premium API を提供開始しました。
これらの新しい API は、当社のエンタープライズデータプラットフォームの品質と安定性に基づき、段階的な価格モデルでより広く利用できるようになっています。今回初めて、(標準エンドポイントの限定された 7 日間のデータではなく) 過去 30 日間の投稿を検索でき、オプションで profile geo、URL 展開、投票データのプレミアムエンリッチメントにアクセスできます。新機能の一部をご紹介します:
* リクエストあたりの投稿数の増加 (Sandbox + Premium)
* より複雑なクエリを可能にするはるかにリッチなクエリ言語 (Sandbox + Premium)
* 投稿の時系列カウントを返す counts エンドポイント (Premium)
* Expanded URLs および Profile Geo などのメタデータエンリッチメント (Premium)
この提供開始の詳細は[ブログ](https://blog.x.com/developer/en_us/topics/tools/2017/introducing-twitter-premium-apis.html)をご覧ください。
### 280 文字の投稿の提供開始
cramming が問題となっていた言語で、280 文字の投稿が正式に提供開始されました。詳細は[フォーラムのお知らせ](https://devcommunity.x.com/t/updating-the-character-limit-and-the-twitter-text-library/96425)または公式[ブログ投稿](https://blog.x.com/official/en_us/topics/product/2017/tweetingmadeeasier.html)をご覧ください。
### Statuses/Update からの DM コマンドの削除
`statuses/update` API エンドポイント経由で Direct Messages を送信する機能は完全に削除され、`enable_dm_commands` および `fail_dm_commands` パラメーターは効力を持たなくなります。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653 "on our forum")をご覧ください。
### OAuth ログインフローの変更
X のバックエンド OAuth API エンドポイントに変更を加え、`/oauth/authenticate` エンドポイントの動作を `/oauth/authorize` エンドポイントの動作に合わせるようにしました。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/recent-changes-to-twitter-s-oauth-login-flow-and-api-endpoints/94943)をご覧ください。
### Engagement API メトリクスの更新
Engagement API が、X 分析ダッシュボードで使用されているメトリクス集計方法と同じものを使用するように更新されました。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/changes-to-the-engagement-api/94523)をご覧ください。
### DM コマンド失敗の変更
DM `statuses/update` エンドポイント内の `fail_dm_commands` パラメーターのデフォルト値が *true* に切り替わりました。Direct Message を意図したすべての status update はエラーを返し始めます (`enable_dm_commands` が *false* の場合を除き、その場合は投稿として投稿されます)。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653)をご覧ください。
### 280 文字ツイートの取り扱い
280 文字ツイートのレスポンスペイロードは、ロングツイートと同じ方法で処理されます。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/testing-280-characters-for-certain-languages/94126)をご覧ください。
### Additional Media Info の追加
投稿ペイロードに新しいデータ (`additional_media_info` オブジェクト) を追加し、また、広告主が動画再生を X 所有のクライアントに制限することを要求したプロモーション投稿の動画詳細 (`video_info`) を制限します。この変更に関する追加情報は、[Extended Entities Objects > ネイティブ動画付きの投稿](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities)で確認できます
### 30-Day Search における url\_contains オペレーターのサポート終了
30-Day Search および Full-Archive Search で `url_contains:` オペレーターのサポートが終了しました。このオペレーターの廃止は、2016 年 8 月の Gnip 2.0 移行の一環として発表されていました。`url_contains:` オペレーターを使用するすべての Search クエリは無効として拒否されます。
### Search API における url\_contains オペレーターの今後の削除
30-Day Search API (30-Day および Full-Archive 両方) では、本日から 30 日後、または 2017 年 8 月 4 日以降、`url_contains:` オペレーターをサポートしなくなります (実際には、その日付後の最初のデプロイで `url_contains:` のサポートが終了します)。このオペレーターの廃止は、2016 年 8 月の Gnip 2.0 移行の一環として発表されていました。オペレーターサポートが終了すると、`url_contains:` を使用するクエリは無効として拒否されます。
### xAuth の廃止
xAuth 認証メカニズムがすべての X API から削除されました。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/retirement-of-xauth/88022)をご覧ください。
### HTTP ヘッダーの小文字強制
すべての HTTP ヘッダーは小文字に強制されました (`content-type`、`x-rate-limit-remaining`、`x-access-level` など)。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/upcoming-http-header-changes/86715)をご覧ください。
### DM コマンドのオプションパラメーター
`statuses/update` のオプションパラメーター `enable_dm_commands` を使用すると、移行期間が終了する前にアプリケーションが早期に DM コマンドサポートを削除できます。デフォルト値は *true* (つまり、現在のレガシー動作) ですが、新しい 11 月 1 日以降の動作を取得するには *false* に設定できます。`statuses/update` のオプションパラメーター `fail_dm_commands` を *true* に設定すると、API から DM コマンドが HTTP 403 (エラーコード 151) を返すようになります。デフォルト値は *false* です。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653)をご覧ください。
### ルールでの絵文字のサポート
絵文字を含むルールがエンタープライズ Search API で利用可能になりました
### Direct Message API の広範な提供
いくつかの新しい Direct Message API へのアクセスがより広く利用可能になりました。この更新の詳細は[ブログ](https://blog.twitter.com/developer/en_us/topics/tools/2017/new-apis-to-power-the-future-of-customer-engagement-in-direct-me.html)をご覧ください。
### MPEG-DASH 動画サポートの廃止
動画を含む投稿のペイロードから MPEG-DASH URL (.mpd) が削除されました。この更新の詳細は[フォーラム](https://devcommunity.x.com/t/retiring-mpeg-dash-video-support-on-march-9th-2017/82761)をご覧ください。
### 新しいエンリッチメントとペイロードの変更
新しいエンリッチメント! Poll Metadata がエンタープライズ API 経由で利用可能になりました。詳細は[ドキュメント](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)をご覧ください。
新しいペイロードフィールド: ユーザーが写真を投稿に追加する際に「Add description」オプションを選択すると、Image Alt-Text (description) フィールドがペイロードの `entities.media[]` および `extended_entities.media[]` セクションに表示される場合があります。これは、エンリッチされたネイティブ形式でのみ利用可能です。
デフォルトペイロード形式: Gnip 製品で新しく作成されたストリームは、デフォルトで original format JSON になります。
### Historical PowerTrack および Replay API の更新
Historical PowerTrack API および Replay API
* 引用フィルタリングがサポートされました
* 引用投稿は HPT および Replay 投稿ペイロード内で完全に再ハイドレートされるようになりました
### Counts の新しいペイロードフィールド
新しいペイロードフィールド: `quote_count` および `reply_count` が、Realtime および Historical API 全体のネイティブエンリッチ形式ペイロードで利用可能になりました
### Full-Archive Search における Geo オペレーターのサポート
Full-Archive Search API (FAS):
* 追加の geo オペレーターのサポートを追加:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
### PowerTrack でのルール ID によるルール管理
ルール管理 (GET および DELETE) がルール ID によって PowerTrack 2.0 および PowerTrack Replay 2.0 で利用可能になりました
### 30-Day Search における Geo オペレーターのサポート
30-Day Search API:
* 追加の geo オペレーターのサポートを追加:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
# デベロッパーガイドライン
Source: https://docs.x.com/ja/developer-guidelines
X API のデベロッパーポリシーおよびガイドライン。許可されるユースケース、制限される動作、コンプライアンス要件、アプリのベストプラクティスを取り扱います。個人情報の取り扱い、自動化ルール、コンテンツ表示要件、レート制限順守、違反時の対応についても詳しく解説します。
**違反は、アプリの停止、API アクセスの取り消し、またはアカウントの永久 BAN につながる可能性があります。** 構築の前に必ず公式ポリシーを確認してください。
API アクセスのための法的拘束力のある利用規約
X 上で構築するためのルール
ボットに特化したルール
禁止されている活動
***
## クイックチェック: 私のアプリは許可されている?
構築する前に、以下の質問を自分に問いかけてください。いずれかに **「いいえ」** と答える場合、あなたのアプリは X のポリシーに違反している可能性があります。
インタラクションについて、ユーザーが **明示的にリクエストした** か?
アプリの目的と動作は **ユーザーに明確** か? (自動アカウントはラベルを付ける必要があります。)
ユーザーは継続的なインタラクションから **簡単にオプトアウト** できるか?
自己宣伝以上の **真の価値** を提供しているか?
**公式 API のみ** を使用しているか (スクレイピング/ブラウザ自動化ではない)?
**レート制限内** で、利用ポリシーを遵守しているか?
迷ったら、「ユーザーはこの体験に満足するだろうか?」と自問してください。そうでなければ、アプローチを再考してください。
***
## よくあるシナリオ: 許可されるかどうか?
何が許可されるかを理解するための実例です。**これらのルールはすべてのアプリに適用されます** — ボット、モバイルアプリ、Web 連携、ブラウザ拡張機能、アナリティクスダッシュボード、その他 X API を使用する任意のツールを構築している場合でも該当します。
| シナリオ | 許可? | 理由 |
| ------------------------------------------- | :--------------------------: | --------------------- |
| 自動アカウントが予定されたコンテンツ (ニュース、天気、引用) を投稿する | | 情報提供、迷惑な @mentions なし |
| アプリがユーザーに代わって RSS フィードの更新を投稿する | | 役立つ情報発信 |
| アラートサービスが地震/災害通知を投稿する | | 公共安全の価値 |
| スポーツアプリがユーザーのタイムラインに試合更新を投稿する | | 情報提供 |
| アプリが株価/暗号通貨価格を定時に投稿する | | 情報提供、操作なし |
| アプリが複数のアカウントで同一のコンテンツを投稿する | | スパム / プラットフォーム操作 |
| アプリが可視性を得るためにトレンドトピックに投稿する | | トレンド操作 |
| 都市別の複数アラートアカウント (例: @WeatherNYC、@WeatherLA) | | 許可 — 重複しない、場所固有のコンテンツ |
| シナリオ | 許可? | 理由 |
| ----------------------------- | :----------------------------------: | ------------------------------------------------------- |
| アプリがヘルプを求める @mentions に応答する | | ユーザー起動のリクエスト |
| アプリがキーワードを含む誰にでも自動返信する | | 迷惑なインタラクション |
| アプリが自分の投稿に返信したユーザーに自動返信する | | ユーザーが先に関与 — 1 件の返信のみ。[条件が適用されます](#gray-areas-explained) |
| AI 駆動アプリが返信を生成して投稿する | | X からの **事前承認** が必要 |
| アプリがランダムなユーザーに「フォローして!」と返信する | | スパム、迷惑 |
| メンションされた時にスレッドを展開するユーティリティアプリ | | ユーザー起動のユーティリティ |
| シナリオ | 許可? | 理由 |
| --------------------------------------- | :--------------------------: | ------------------------------------------------- |
| アプリが有益な情報で DM に応答する | | ユーザー起動 |
| ユーザーが先に DM した時にアプリがアフィリエイトリンクを送信する | | ユーザー起動 — 開示が必要。[条件が適用されます](#gray-areas-explained) |
| アプリが新規フォロワーにウェルカムメッセージを自動 DM する | | 迷惑、フォロワーであっても |
| アプリが製品ローンチについてユーザーに一括 DM する | | スパム |
| サポート連携がユーザーの DM 後に「どのようにお手伝いできますか?」と尋ねる | | ユーザー起動の会話 |
| シナリオ | 許可? | 理由 |
| ---------------------------------- | :--------------------------: | ---------------------------------------------------- |
| サードパーティアプリがユーザーに投稿のいいねボタンをタップさせる | | アプリを通じたユーザー起動 |
| アプリがハッシュタグを含む投稿に自動いいねする | | 自動、ユーザー起動ではない |
| モバイルアプリが選択したユーザー向けの「自動いいね」機能を持つ | | 自動、ユーザー起動ではない |
| いいねを売るサービスや「一括いいね」パッケージを提供する | | エンゲージメントの販売は禁止 |
| アプリがキュレートされたリストからコンテンツをリポストする | | 情報目的なら OK、一括スパムなし。[条件が適用されます](#gray-areas-explained) |
| グロースツールがオーディエンスを増やすためにアカウントを一括フォロー | | 操作 |
| アプリがフォローしたすべての人をフォローバックする | | 一括/攻撃的なフォロー |
| アプリが一括でユーザーをリストに追加する | | 無差別なリスト操作 |
**いいねは認証済みユーザーによって直接起動される必要があります。** 自動、一括、または無差別ないいね — キーワード、ハッシュタグ、ユーザー、スケジュールによる自動いいねを含む — は禁止されています。アプリは「自動いいね」機能を提供することや、いいねをサービスとして販売することはできません。これはすべてのアプリ — ボット、モバイルアプリ、ブラウザ拡張機能、その他あらゆる連携 — に適用されます。
| シナリオ | 許可? | 理由 |
| ---------------------------- | :----------------------------------: | --------------------------------------------------- |
| 尋ねられた時にアプリが製品推奨を送信する | | ユーザー起動 |
| アプリがランダムな投稿にアフィリエイトリンクで返信する | | 迷惑なスパム |
| 参加にフォロー/リツイートを要求する懸賞アプリ | | リスクあり — エンゲージメント操作と見なされる可能性 |
| いいね/フォロー/リツイートを販売するサービス | | 厳密に禁止 |
| ユーザーのリクエストに応じて暗号通貨を送るチップサービス | | ユーザー起動 — 金融規制を遵守。[条件が適用されます](#gray-areas-explained) |
| シナリオ | 許可? | 理由 |
| ---------------------------------- | :--------------------------: | ----------------- |
| アプリがアナリティクスダッシュボード用にブランドメンションを追跡 | | 有効なユースケース |
| アプリがブラウザ自動化で X をスクレイピング (API ではない) | | **永久停止** — API のみ |
| アプリが AI/ML モデルを訓練するために X データを保存する | | 禁止 (Grok を除く) |
| アプリが 30 日間で 150 万件超の投稿を再配布 | | 再配布制限を超過 |
| アプリが X のパフォーマンスを競合とベンチマーク | | 禁止された競合分析 |
| 公共会話トレンドに関する学術研究 | | 適切なデータ処理で有効 |
**非 API 自動化 (スクレイピング、ブラウザ自動化) は永久停止につながります。** 必ず公式 X API を使用してください。
***
## 禁止された活動
これらの活動は、アプリの停止または永久 BAN につながります。例外はありません。
| カテゴリー | 例 |
| -------------- | ---------------------------------------- |
| **スパムと操作** | アカウント間の同一コンテンツ、偽のエンゲージメント、トレンド操作、一括投稿 |
| **迷惑なアウトリーチ** | ランダムなユーザーへの自動返信、一括 DM、招待されていない @mentions |
| **欺瞞的なボット** | 人間のなりすまし、ボットの正体の隠蔽、誤解を招くリンク/リダイレクト |
| **エンゲージメント販売** | いいね、フォロー、リツイート、ビューを販売するアプリ |
| **レート制限の悪用** | 制限の超過、過剰使用を促すアプリ設計 |
| **非 API 自動化** | ブラウザスクリプティング、スクレイピング、公式 API 外の自動化 |
| **アカウントファーム** | 同じ重複目的の複数アカウント |
| **監視** | 同意なしのユーザーのプロファイリング、追跡、モニタリング |
| **承認なき AI 訓練** | X データを使って ML モデルを訓練する (Grok を除く) |
| **機微情報の推測** | 健康、政治、宗教、その他の機微属性を推測する |
| **過剰な再配布** | 30 日間に 150 万件超の投稿 ID を共有する |
***
## 自動化ルール
このセクションは、ユーザーに代わって投稿、返信、または対話する **自動アカウント** (ボット) に特に適用されます。アナリティクスダッシュボード、リサーチツール、その他の非自動アプリを構築している場合、これらのラベル要件は適用されません — ただし、技術的な制限は依然として適用されます。
### 自動アカウントの要件
X API を使用するすべての自動アカウントは、これらの要件を満たす必要があります:
このラベルは、ボットのプロフィールで名前/ハンドル下に表示されます。透明性を確保するためにアプリ設定で有効にしてください。
ボットであることと運用者を明確に記載します。例: *"Bot by @yourcompany"* または *"Example Inc. が管理する自動アカウント"*
説明責任と連絡の目的で、ボットは人間が管理するアカウントに関連付けられる必要があります。
ユーザーが「stop」と言ったら、停止してください。一般的なオプトアウトフレーズのキーワード検出を実装してください。
スクレイピング、ブラウザ自動化、または非公式な手段は不可。違反は永久停止につながります。
レート制限を回避または悪用しようとしないでください。制限を適切に処理するようにアプリを設計してください。
### 自動アクション: 何が許可される?
| アクション | 許可? | ルール |
| --------------- | :----------------------------------: | ----------------------------------------------- |
| **ツイートの投稿** | | 迷惑な @mentions なし。同一クロスポスティングなし。 |
| **ユーザーへの返信** | | ユーザーが先に関与した場合のみ。**インタラクションあたり最大 1 件の返信**。 |
| **DM の送信** | | ユーザーが先に DM した後のみ。簡単なオプトアウトが必要。 |
| **投稿へのいいね** | | ユーザーが直接起動する必要があります。自動いいね、一括いいね、いいねの販売は禁止されています。 |
| **リポスト** | | 情報/エンターテイメント目的は OK。一括スパムなし。 |
| **引用ツイート** | | リポストと同じルール — スパムや操作なし。 |
| **フォロー/アンフォロー** | | 一括、攻撃的、または自動フォローなし。 |
| **リストへの追加** | | 一括または無差別な追加なし。 |
| **ブックマーク** | | 個人/自動利用は問題ありません。 |
| **検索/読み取り** | | レート制限内での標準利用。 |
***
## グレーゾーンの説明
多くの開発者がエッジケースについて質問しています。一般的なグレーゾーンに関するガイダンスはこちらです。
**以下の場合に許可:**
* ユーザーが明示的にリクエスト (例: 推奨を求める DM)
* アフィリエイト/スポンサー関係を明確に開示
* リンクが誤解を招かない (欺瞞的リダイレクトなし)
**以下の場合に不許可:**
* ランダムな投稿にアフィリエイトリンクで自動返信
* 尋ねていないユーザーに DM
* 商業関係を隠す
* 展開前に **X からの事前承認が必要**
* すべてのルールに従う必要があります (迷惑なメンションなし、適切にラベル付け)
* 起動前に [Policy Support フォーム](https://help.x.com/forms/platform) を介して X に連絡してください
* 承認があっても、人間のなりすましはできません
承認なしに AI 生成の返信を展開することは違反です。コンテンツ自体が有益であってもです。
自動 DM として **不許可** — フォローした場合でも、これは迷惑な接触に該当します。
**代替案:**
* 新規フォロワーを歓迎する固定ツイート
* 紹介情報とリンクを含むバイオ
* ユーザーが先に DM した場合のみ自動返信
**以下の場合に許可:**
* 各アカウントが **重複しない** 目的を果たす (例: @EarthquakeJP、@EarthquakeCA)
* コンテンツが意味のある違いを持つ (場所固有、言語固有)
* 制限を回避したり、同じメッセージを増幅するために使用しない
**以下の場合に不許可:**
* アカウント間で同一/類似のコンテンツを投稿
* 停止やレート制限を回避するために作成
**以下の場合に許可:**
* ユーザーが起動 (あなたにメンション、DM、または明示的にオプトイン)
* 明確なオプトアウトメカニズムが存在
* 応答が有益で、プロモーション目的ではない
* DM にプライバシーポリシーのリンクを含める
**以下の場合に不許可:**
* 公開で苦情を述べたユーザーに連絡する (迷惑)
* 応答が主にプロモーション目的
**注意して進める:**
* 参加要件としてフォロー/リツイートを要求することは、エンゲージメント操作と見なされる可能性があります
* [X のコンテストガイドライン](https://help.x.com/en/rules-and-policies/x-contest-rules) を遵守する必要があります
* 増幅するために複数のアカウントを使用しないでください
* 賞品が本物であり、配達されることを確認してください
特定のフレーズで返信するなど、エンゲージメントアクションを必要としない参加方法を検討してください。
***
## データ処理と表示の要件
これらの要件はデベロッパー契約の下で法的拘束力があります。不遵守は契約終了および法的措置につながる可能性があります。
### コンテンツの削除
リクエストに応じて、システムから X コンテンツを削除する必要があります:
| トリガー | 期限 |
| ---------------- | ----------------------------------- |
| X が削除をリクエスト | **24 時間** |
| ユーザーが削除をリクエスト | **24 時間** |
| コンテンツが X 上で停止/削除 | **24 時間** |
| API アクセスが終了 | **10 営業日** (すべての X データを削除する必要があります) |
[Compliance Firehose](https://docs.x.com/x-api/compliance/streams) を使用して、リアルタイムの削除イベントを受信し、自動的にコンプライアンスを維持してください。
### Off-X マッチング
**Off-X マッチング** とは、X データ (ユーザー名、ユーザー ID、投稿) をプラットフォーム外の識別子 (顧客データベース、メールリスト、デバイス ID など) に関連付けることを意味します。
**明示的なオプトイン同意で許可:**
* ユーザーが自分の X アカウントをサービスとリンクさせることに明示的に同意
* どのデータが何のためにマッチされるかの明確な開示
**同意なしの場合、以下のみマッチング可能:**
* ユーザーが直接提供した情報
* 公開されている X データ (投稿、バイオ、表示名、ユーザー名)
* 専門ディレクトリなどの公開リソース
**ユーザーを驚かせるようなマッチは絶対にしないでください。**
### 機微データ
X ユーザーに関する以下のカテゴリーの情報は、推測、推論、または保存 **してはなりません**:
| カテゴリー | 例 |
| ------------ | --------------- |
| **健康** | 病状、妊娠、障害 |
| **金融状況** | ネガティブな金融状況、信用問題 |
| **政治** | 政党所属、政治信条、投票 |
| **人種/民族** | 出身、民族 |
| **宗教/哲学** | 信念、所属 |
| **性生活/性的指向** | セクシュアリティに関する推測 |
| **労働組合** | 加入または所属 |
| **犯罪** | 疑われる、または実際の犯罪行為 |
**例外:** 個人識別子 (ユーザー ID、ユーザー名、リンク可能なデータなし) を保存しない集計分析は、適用法に従い、研究目的で許可される場合があります。
### X コンテンツの表示
| 要件 | 詳細 |
| ------------- | ---------------------------------------------------------------------------------------------- |
| **アトリビューション** | 適切な X ブランディングを使用してください。[ブランドガイドライン](https://about.x.com/en/who-we-are/brand-toolkit) に従ってください。 |
| **改変なし** | 表示フォーマット (リサイズ) のみ変更可。コンテンツの編集、タイムスタンプの削除、メタデータの除去はしないでください。 |
| **iframe なし** | X コンテンツを iframe で表示しないでください。公式の埋め込みを使用するか、直接レンダリングしてください。 |
| **削除の尊重** | X 上で削除されたコンテンツは 24 時間以内に削除してください。 |
***
## 技術的制限
これらの制限はすべての開発者に適用されます。超過すると、レート制限または停止につながる可能性があります。
| 制限 | 上限 |
| ---------------------- | ----------------------------------------------------------------------- |
| **投稿 ID の再配布** | 単一のエンティティに対して 30 日間で最大 150 万件の投稿 ID |
| **ハイドレートされたコンテンツの再配布** | 受信者あたり 1 日最大 50,000 件のハイドレートされた投稿またはユーザー |
| **レート制限** | エンドポイントとティアによって異なります — [API ドキュメントを参照](/x-api/fundamentals/rate-limits) |
| **AI/ML 訓練** | 禁止 (Grok を除く) |
| **非 API アクセス** | 禁止 — スクレイピングおよびブラウザ自動化 = 永久 BAN |
| **競合ベンチマーク** | 禁止 — X のパフォーマンスを競合と測定できません |
| **同一ユースケースの複数アプリ** | 禁止 — 制限を回避するために重複アプリを作成しないでください |
### 特別なユースケース
| ユースケース | 要件 |
| ------------------ | ------------------------------------ |
| **政府利用** | エンタープライズティアが必要 |
| **商用利用** | 適切な有料ティアが必要。無料ティアは非商用のみ |
| **学術研究** | 異なる再配布制限がある場合があります。詳細は X にお問い合わせください |
| **EU デジタルサービス法研究** | 特定の非商用研究規定が利用可能 |
***
## セキュリティとコンプライアンス
開発者としてのあなたの義務:
* X データを保護するために **業界標準のセキュリティ** プラクティスを使用してください
* API 認証情報やトークンを共有しないでください
* 認証情報を安全に保存してください (環境変数、シークレットマネージャー — コード内ではない)
* アプリで適切な認証を実装してください
X データに関わるセキュリティ侵害が発生した場合:
* **X に直ちに通知してください**
* 侵害を緩和する措置を講じてください
* X の調査に協力してください
* X からの非公開情報はすべて機密として扱ってください
* API レート制限、内部 X データ、または非公開機能を開示しないでください
* 機密情報を競争目的で使用しないでください
* X は **年に最大 1 回** あなたのコンプライアンスを監査することがあります
* 合理的なアクセスとドキュメントを提供する必要があります
* X データの利用方法の記録を保持してください
***
## まとめ: すべきこと・すべきでないこと
**自動アカウント向け:**
* 「自動化」プロフィールラベルを有効にする
* バイオで運営者を開示する
* ユーザーがインタラクションを起動するのを待つ
* 簡単なオプトアウトを提供する
* AI 生成の返信について承認を取得する
**すべてのアプリ向け:**
* 公式 X API のみを使用する
* レート制限と再配布制限を尊重する
* リクエストされた場合は 24 時間以内にコンテンツを削除する
* Off-X マッチングについてオプトイン同意を取得する
* X コンテンツを表示する際に適切なアトリビューションを使用する
* 認証情報を保護し、侵害を X に通知する
* X データ利用の記録を保持する
**自動アカウント向け:**
* 自動化された性質を隠す
* 迷惑な DM、返信、@mentions を送信する
* 「stop」リクエストを無視する
* アカウント間で同一のコンテンツを投稿する
* 自動いいね、一括いいね、またはいいねを販売する (いいねはユーザー起動である必要があります)
**すべてのアプリ向け:**
* スクレイピングまたはブラウザ自動化を使用する
* X データで AI/ML モデルを訓練する (Grok を除く)
* 機微なユーザーデータ (健康、政治、宗教など) を推測する
* 同意なしに X データをプラットフォーム外の ID にマッチする
* X コンテンツを iframe で表示する
* 制限を超えて再配布する
* 同じユースケースのために複数のアプリを作成する
* 監視またはユーザー追跡のために X データを使用する
# ポリシーと契約
Source: https://docs.x.com/ja/developer-terms
X のデベロッパーポリシーおよび契約、表示要件について、Developer Agreement、Developer Policy、Ads API 契約、制限された利用ケースを含めて解説します。
## 概要
デベロッパーによる X の資料およびコンテンツの利用は、当社の Developer Policy および各種契約の対象となり、これらに従うものとします。
# Ads API 契約
Source: https://docs.x.com/ja/developer-terms/ads-api-agreement
X Ads API 契約は、X 広告エンドポイントの利用について、広告パートナー向けの許容される統合、制限、義務を含めて規定します。
Ads API 契約を更新しました。以下の変更は 2025 年 2 月 23 日より発効しています。
## X Ads Products and Services Agreement
**発効日: 2025 年 2 月 23 日**
本 X Ads Products and Services Agreement(以下「**本契約**」)は、当該事業体(またはその権限のある代表者)により X に提出された「X Ads API Program」申請書に記載された事業体(本契約において「**Company**」と呼びます)と、Company が欧州連合、EFTA 加盟国、または英国の外にある場合(米国内である場合を含む)は X Corp.、Company が欧州連合、EFTA 加盟国、または英国内にある場合は X Internet Unlimited Company との間で、それ自体および関連会社(以下に定義)を代表して(いずれの場合も「**X**」)締結され、Company の Ad Products(以下に定義)へのアクセスおよび利用を規定します。本契約において、「**関連会社**」とは、直接的または間接的に X を支配し、X により支配され、または X と共通の支配下にある他の事業体を意味します。
以下の添付書類、およびその中に記載または参照されている連結条件を含む、本契約のすべての条項を注意深くお読みください。これらはすべて本契約の一部を構成します。「Yes, I Agree」と表示されたボックスにチェックを入れ、「SUBMIT」をクリックすること(あるいは例えば「I Accept」など「Yes, I Agree」と同等の言語をクリックすること)、または X Materials を利用することにより、Company は本契約の条項を読み、これに準拠し拘束されることに同意することを表明します。Company が本契約に拘束されることに同意しない場合、Company は X Materials にアクセスまたはその他の方法で利用することはできません。本契約は、(I) Company が「Yes, I Agree」にチェックを入れ「SUBMIT」をクリックして本契約を受諾した日、または (II) Company が最初に X Materials にアクセスした日のいずれか早い方(以下「**発効日**」)から発効します。ただし、Company の X Materials へのアクセスおよび利用の申請が X(その独自かつ絶対的な裁量による)によって承認されない場合、本契約は無効となり、効力を持たないものとします。あなたが Company を代表する個人である場合、あなたは、(A) 本契約を読み、理解していること、(B) Company に代わって本契約を承諾する適切な権限を有すること、および (C) Company に代わって本契約の条項に同意することを、承諾、表明、および保証します。Company を法的に拘束する権限を有しない場合、法定年齢に達していないか、その他の理由で X との拘束力ある契約を締結できない場合、または適用される法律により X Materials の利用もしくは受領を禁じられている場合、X Materials を利用することはできず、本契約を承諾することはできません。
### 1. はじめに、範囲、Individual Product 条件。
**1.1 はじめに。** X は、X の広告パートナー向けにさまざまな機能を可能にする一連の商品およびサービスを保守、運営、および提供しています。これらの機能を可能にする、またはこれらに関連する特定の商品、サービス、およびプログラム(それぞれ「**Individual Product**」)は次のとおりです: (i) X Ads API Program([Exhibit A](#Exhibit-A) で詳述);および (ii) X の Custom Audiences Program([Exhibit B](#Exhibit-B) で詳述)。これらの Individual Products を総称して「**Ads Products**」といいます。本契約は、Ads Products の集合的な利用および/またはアクセス、ならびに Individual Products の個別の利用および/またはアクセスを規定します。加えて、Company が本契約でカバーされる Ads Product に関連して X Marketing Partner(「**TMP**」)プログラムに参加する範囲において、[Exhibit C](#Exhibit-C) に定める条項が Company に適用されます。
**1.2 範囲。** 本契約に従い、Term の期間中、Company は X がアクセスを付与または提供した特定の Individual Products にアクセスして利用できます。Company は、X がアクセスを付与または提供したいずれの、またはすべての Individual Products の利用にも義務を負わず、X も、Company に対して任意の Individual Product または Ads Products の機能の利用および/またはアクセスを提供(または継続して提供)する義務を負いません。X は、独自の裁量により、いつでも任意の Individual Product、またはその機能の利用および/またはアクセスを付与または拒否することができます。Company が Ads Products の任意の機能にアクセスまたは利用する範囲において、本契約の条項がそのようなアクセスまたは利用を規定します。誤解を避けるため、本契約は本規定に記載された Ads Products の Company による利用のみを規定します。X と Company の間で書面で別途相互合意されない限り、Company が本契約とは別の X との契約および/または別の X プログラムに関連して X から(直接的または間接的に)提供されるあらゆるデータ、コンテンツ、またはその他の資料にアクセスおよび利用することは、専らそのような別の契約および/またはプログラムの条項(本契約の条項ではない)によって規定されます。
**1.3 Individual Product 条件。** 各 Individual Product は、本契約の条項に加えて、Company が該当する Individual Product にアクセスまたは利用する範囲で適用される特定の条項を含む場合があります。Company の任意の Individual Product および/または関連する X Materials(以下に定義)へのアクセスは、Individual Product 条件およびアクセス、コール、Individual Products の利用に関する技術的制限への Company の承諾および遵守を条件とします。Individual Product 条件は、[Exhibit A](#Exhibit-A) および [Exhibit B](#Exhibit-B) として添付されています。X は、下記第 15.15 節に定めるとおり、X の独自の裁量により、そのような Individual Product ポリシーまたは条件を設定および変更することがあります。
### 2. 定義。
**2.1** 「**Campaign**」とは、デスクトップ、モバイルウェブサイト、またはモバイルアプリケーションの広告キャンペーン、あるいはその一部を意味します。
**2.2** 「**Client**」とは、X 広告主(Company の顧客でもある)であって、それぞれの場合において X により承認された上で、1 つ以上の Ads Products を利用する者を意味します。
**2.3** 「**Company Marks**」とは、Company の名称、および Company が本契約に基づく X の利用のために X に提供した(またはその他の方法で本契約に基づく X の利用のために Company が承認した)Company のロゴ、商標、および/またはサービスマークを意味します。
**2.4** 「**Company Materials**」とは、Company が Ads Products を通じて X に提供する Company のデータ、成果物、またはユーザーコンテンツを意味します。
**2.5** 「**Company Service**」とは、X Materials またはその一部を表示するか、またはその他の方法で利用する Company のウェブサイト、アプリケーション、およびその他の提供物を意味します。
**2.6** 「**Data**」とは、X が Company に利用可能にするメトリクス、データ、およびその他の情報および/またはコンテンツを意味し、上記のいずれかを分析または利用することから派生する結果、利用統計、データ、またはその他の情報(集計またはその他の形式)を含みます。
**2.7** 「**End Users**」とは、Client を代表して Ads Products を利用する Client の従業員または権限のある代理人を意味します。
**2.8** 「**Marks**」とは、(文脈に基づき)X Marks および/または Company Marks を意味します。
**2.9** 「**Materials**」とは、(文脈に基づき)X Materials および/または Company Materials を意味します。
**2.10** 「**Personal Data**」とは、生存する個人に関連するデータであって、そのデータのみから、またはそのデータが管理者が所有している、もしくは所有することとなる可能性のある他の情報と組み合わせて、識別されるかまたは識別可能であるものを意味します。
**2.11** 「**X Ads**」とは、X Network 上への広告掲載を含む、X の広告商品およびサービスを意味します。
**2.12** 「**X Code**」とは、X が開発し、Company に提供する、(少なくとも)X サーバーを呼び出すコンピュータコードを意味します。
**2.13** 「**X Marks**」とは、X の名称、および X が本契約に基づく Company の利用のために Company に提供した(またはその他の方法で本契約に基づく Company の利用のために X が承認した)X のロゴ、商標、および/またはサービスマークを意味します。
**2.14** 「**X Materials**」とは、X によって生成された任意の X データ、成果物、またはユーザーコンテンツ(それらの派生物を含む)、および X によって生成、収集、開発されたか、または本契約に基づき X により Company に提供されるか利用可能にされる任意の X データ、成果物、またはユーザーコンテンツ(それらの派生物を含む)を意味し、Company の X とのパートナーシップから派生、これに基づく、またはこれに起因する任意のデータ、またはデバイスレベルのデータ、あるいは Company または X が承認した第三者が Company の X 広告キャンペーンから、またはこれに関連して収集、推測、派生、または取得する任意のコンバージョン、エンゲージメント、追跡、またはターゲティングデータを含みます。明確性のために、また限定なく、「X Materials」には、X Ads API([Exhibit A](#Exhibit-A) に定義)、X Code、Data、Ads Products、および Custom Audience(以下に定義)の作成に使用される X ユーザー ID が含まれます。
**2.15** 「**X Network**」とは、あらゆる形式のメディア、アプリケーション、およびデバイスを含む広告チャネルのネットワークを意味し、X はこれを通じて、現在知られているか将来開発されるあらゆる媒体で広告を配信することがあります。
**2.16** 「**X Marketing Partners Program**」とは、[Exhibit C](#Exhibit-C) で詳述される、X が提供するパートナーシップおよびブランディングプログラムを意味します。
**2.17** 「**X Service**」とは: (i) X が運営するリアルタイムコンテンツおよび情報サービス、(ii) そのようなサービスを可能にする技術およびシステム(X が現在提供しているかそのウェブサイトで提供する消費者向けおよび広告向けの商品およびサービス、ならびに X が所有、運営、および/または管理するモバイルアプリケーションおよびソーシャルプラグイン、Measurement Code、HTML タグその他のコード、インターネットポータル、ダッシュボード、システムおよび分析ツール、および関連サービスを含む API を集合的に含みます)、および (iii) X および関連会社が提供するその他すべての商品またはサービス(X Audience Platform および Data & Enterprise Solutions を含みますが、これらに限定されません)を意味します。
### 3. X Ads / Campaign Management、責任の引受け。
**3.1 X Ads / Campaign Management。** Company は、Company が独自の裁量および/または Company の Client の指示により、X Network 上の X Ads を最適化、変更、管理、開始、または操作すること、あるいは広告管理およびターゲティングの決定を行うこと(以下「**Campaign Management**」)を可能にする 1 つ以上の Individual Products にアクセスできる場合があります。Company がそのような Individual Products にアクセスまたは利用する場合: (a) Company は、X Network に掲載する予定の広告資料を速やかに提供する必要があります;および (b) Company は、X が該当する Individual Product を通じて利用可能な任意のコンテンツまたはプロパティ(X Network 上に提供されるか第三者を通じて提供されるかを問わず)に、Company および/または Client の広告資料を掲載することを X に承認します。Company は、Client のために当該広告資料を利用するために必要なライセンスおよび権限を、該当する Client から取得します。Company は Campaign Management を可能にする Individual Product の利用を義務付けられていませんが、そのような商品、サービス、または機能を利用する場合、Company は Campaign Management に起因または関連するあらゆるリスクを引き受け、あらゆる責任および負債を受け入れます。これには以下が含まれますが、これらに限定されません: (i) オーディエンスの作成と選択、データ入力エラー、戦術の選択、および関連するインベントリ、データ、その他の第三者コストに関するもの;(ii) Company が提供する広告が視聴者を誘導するプロパティ(例: ランディングページ)、およびそこからのリダイレクト;(iii) ランディングページで宣伝されるサービスおよび商品;および (iv) X に提供された広告資料、テクノロジー、および/またはクリエイティブを含みますが、これらに限定されない、関連する Company Materials。Company はここに、X が Company の Campaign Management に関して責任または負債を負わないことを認め、これに同意します。前述の一般性を制限することなく、X は Company の Campaign Management および Ads Products の機能に関する Company の従業員のトレーニングについて責任を負わず、Company が単独で責任を負います。
**3.2 Client の本条件への拘束、責任の引受け。** Company が Client または他の第三者を代表して Ads Products(またはその側面のいずれか、Campaign Management を含む)にアクセスまたは利用する場合、Company は以下を保証します: (i) そのような Client または他の第三者を代表して行動する権限を有し、そのような Client または他の第三者を、該当する Our Policies(下記第 6 節に定義。X Master Services Agreement(「**MSA**」を含み、これが Company が行う X Ads のすべての購入を規定します)、および該当する Ads Products(またはその側面のいずれか)へのアクセスおよび利用に適用される本契約の条項に拘束したこと、および (ii) その遵守について責任を負い、違反について責任を負うこと。
### 4. プライバシー。
**4.1 直接的なデータ収集。** Company は次のことを表明・保証します: (i) Company がユーザーから直接データを収集している場合(Company Service 上または通じてを含みますが、これに限定されない)、そのようなユーザーに法的に十分な通知を提供したこと(ユーザーからのデータが収集され X に利用可能にされるすべてのウェブサイト、モバイルアプリケーション、およびその他のサービスから、適用されるすべての法律および規制に準拠し、第三者が関連するウェブサイト、モバイルアプリケーション、およびその他のサービス上または通じてユーザーの活動(例: ブラウジングまたはショッピング)に関する情報を関心ベース広告目的のために収集していることを開示し、そのようなユーザーが関心ベース広告からオプトアウトするための法的に十分な指示をユーザーに提供する、法的に十分なプライバシーポリシーを目立つように掲載することを含みますが、これに限定されない);(ii) Company の当該データ収集に関連する Cookie および/またはトラッキングピクセルの利用に関するものを含む、当該ユーザーから法的に必要とされるすべての情報に基づく同意を取得したこと;および (iii) Company Materials は、関心ベース広告の受信からオプトアウトするオプションを行使したユーザーまたはデータ主体に関するいかなるデータも含まず、関連せず、Company が X に提供、アクセス可能にし、またはインポートするオーディエンスデータもそのようなデータを含まず、関連しないこと。
**4.2 Personal Data。** Company は、X Materials を直接的または間接的に Personal Data と、または直接的もしくは間接的に Personal Data に関連付けられている識別子と接続または結合しない、また接続または結合を試みないことを表明・保証します。加えて、Company は、X Materials が(直接的または推論により)Personal Data にリンクされることを禁止するために、合理的な保護策を講じます。
**4.3 プライバシー遵守。** Company は次のことを表明・保証します: (i) 犯罪の疑いのある行為または実際の犯罪行為、健康、財務状況の悪さ、政治的所属もしくは信条、人種もしくは民族的出自、宗教的もしくは哲学的所属もしくは信条、性生活、または労働組合への加入を含む機微な情報に関連する Company Materials を X に提供しないこと、また、提供する商品、メッセージ、またはサービスが X の広告ポリシー([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies))によって禁止されているウェブサイト、モバイルアプリケーション、またはその他のサービスから収集された Company Materials を X に提供しないこと、および (ii) (1) 13 歳未満の子供に関する Company Materials を X に提供しないこと、または (2) 現在 16 CFR 312 にある子供のオンラインプライバシー保護法で定義される子供を対象としたウェブサイト、モバイルアプリケーション、またはオンラインサービスからの Company Materials またはその他のデータを X に送信しないこと。Company は、[https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa) にある X Data Processing Addendum の条項を常に遵守することを承認し、これに同意します。
**4.4 第三者データ。** Company は、本契約に基づき Company が X に対して負う履行義務を支援するために、1 社以上の第三者(データパートナーおよび/または広告主(Client を含みますが、これらに限定されません)を含みますが、これらに限定されません)からユーザーに関するデータを間接的に取得している場合、本契約に含まれる要件(本第 4 節を含みますが、これに限定されません)に、各第三者を契約により拘束したことを表明・保証します。
### 5. 所有権、ライセンス、制限および制約。
**5.1 所有権。** Company と X との間では、Company は、Company Materials、Company Marks、および Company Service に関するすべての世界的な権利、権原、および利益を保有します。ただし、これらに含まれる X Materials、X Marks、および X Service(および前述のいずれかの派生物または強化)は除外します。これには、それらに含まれるすべての知的財産権が含まれますが、これらに限定されません。ここに明示的に付与されていない権利は、留保されます。Company と X との間では、X は、X Materials、X Marks、および X Service、ならびに (i) X Materials、(ii) X Marks、および (iii) X Service に基づく、関連する、それらから生じる、またはそれらと関連付けられるすべての将来の改良、開発、強化、派生物、および関連する権利(そのような改良、開発、強化、または派生物が、本契約の条項に従って任意の Company Materials から派生するデータ、洞察、情報、または学習を利用または参照して作成された場合、または X Service 上の Company の広告活動に関連するデータを利用して作成された場合を含む)に関する世界的なすべての権利、権原、および利益を所有します。これには、そこに含まれるすべての知的財産権が含まれますが、これらに限定されません。
**5.2 Company へのライセンス。** Term の期間中(Wind-Down Period を含む)、Company が Ad Products(またはその側面のいずれか)を利用またはアクセスする範囲で、X はここに、X が Company に提供する Ads Products(または任意の Individual Product)を利用するために必要であり、本契約に基づく権利を行使し義務を履行するために必要な範囲でのみ、X が本契約に基づいて Company に提供する X Materials および X Marks を利用および維持するための、限定的、ロイヤリティフリー、非独占的、サブライセンス不可、譲渡不可の権利およびライセンスを Company に付与します。それぞれの場合において、本契約の条項に従って(X Materials の利用に関する制限および/または制約を含みますが、これらに限定されません)。Company は、X Marks の利用が常に X Trademark Guidelines(下記第 6 節に定義)に準拠することに同意します。
**5.3 X へのライセンス。** Term の期間中(Wind-Down Period を含む)、Company が Ad Products(またはその側面のいずれか)を利用またはアクセスする場合、Company は、Company の指示(X Network 上でアクセス可能な広告インベントリでの広告の購入および/または掲載を通じてを含みますが、これに限定されない)を履行するために、Ad Products(または任意の Individual Product)を運営するために、および本契約に基づく権利を行使し義務を履行するために必要な範囲で、それぞれの場合において本契約の条項に従って、Company Materials および Company Marks を利用、コピー、表示、維持、移転、変更、複製、および送信するための、ロイヤリティフリー、非独占的、サブライセンス可能、譲渡不可の権利およびライセンスを X に付与します。
**5.4 制限および制約。**
5.4.1 X Materials は Ads Products の利用および/または提供のためにのみ、および本契約に基づき明示的に許可された他の目的のためにのみ Company に提供され、Company Materials も同様に X に提供されます。
5.4.2 本契約で明示的に許可されている場合、または X および Company が事前に書面で相互合意した場合を除き、Company は、他の当事者(Client を含む)にも、X Materials または X Materials から派生する情報、データ、洞察を、あらゆる内部または外部の目的(広告ターゲティング、広告最適化、リマーケティング、行動ターゲティング、リターゲティング、リダイレクト、いかなる方法でもユーザーまたはデバイスのセグメントのグルーピングを作成または増強すること、あるいはあらゆるモバイルデバイス識別子または任意のエンドユーザー、コンピュータ、ブラウザ、またはデバイスに接続されたその他の一意の識別子と関連付けられたものを含む、エンドユーザープロファイルを作成または追加すること、または広告ネットワークもしくは取引所、データブローカー、その他あらゆる広告もしくは収益化サービスを介してユーザーを広告でリダイレクトすることを含みますが、これらに限定されません)のために利用、複製、コピー、変更、派生、および/または再利用することを、許可されません。加えて、Company は、いかなる方法でも(X Materials またはこれから派生するデータを第三者ソースから派生したデータと組み合わせることを含みます)、X Materials をユーザーの識別または再識別のために利用しません。
5.4.3 Company は、他の当事者(Client を含む)にも、X の明示的な書面による許可なしに、X Materials(コンピュータコード、ピクセル、タグ、または X から Company に提供されるその他のデジタル製品を含みますが、これらに限定されません)を他の商品またはサービスに組み込むこと(本契約の履行に必要であり、本契約の条項によって許可される場合を除く)、翻訳、変更、リバースエンジニアリング、リバースコンパイル、逆アセンブル、派生物の作成、またはあらゆる X Materials のソースコード、基礎となるアイデア、アルゴリズムを発見しようとすることを、許可しません。
5.4.4 Company は、他の当事者(Client を含む)にも、X Materials の機能または機能性への干渉、変更、混乱、無効化(機能を制限または制御するために利用される仕組み、または X Materials のソフトウェア保護もしくは監視メカニズムを打破、回避、無効化、削除、またはその他の方法で回避することを含みますが、これらに限定されません)を許可しません。
5.4.5 Company は、他の当事者(Client を含む)にも、ここで明示的に許可されている場合を除き、X Materials の全部または一部を第三者に販売、賃貸、リース、サブライセンス、配布、再配布、シンジケート、派生物の作成、譲渡、その他の方法で移転またはアクセスを提供することを許可しません。
5.4.6 Company は、他の当事者(Client を含む)にも、X Materials 内または上の専有的な通知やマークの削除または変更を許可しません。
5.4.7 Company は、他の当事者(Client を含む)にも、サービスビューロー、レンタル、またはマネージドサービスとして X Materials の利用を提供すること、または他の個人や事業体が X Materials へのリンクを作成するか、他のサーバー、あるいはワイヤレスもしくはインターネットベースのデバイス上で X Materials を「フレーム」または「ミラー」することを許可すること、または該当する場合、その他の方法で X Materials のトークン、キー、パスワード、その他のログイン認証情報を第三者に利用可能にすることを、許可しません。
5.4.8 Company は、他の当事者(Client を含む)にも、違法、非承認、その他不適切な目的で X Materials を利用することを許可しません。
5.4.9 Company は、他の当事者(Client を含む)にも、X Materials(Data を含みますが、これに限定されません)を、Company の顧客、事業パートナー、または Ads Products に無関係な Company 従業員を含む第三者と(口頭または書面のいずれで)共有することを、ここに明示的に記述されている場合、または事前に X から書面で(電子メールを含む)許可されている場合を除き、許可しません。
5.4.10 Company は、他の当事者(Client を含む)にも、Company Materials、別契約に基づき X から受け取ったデータ、コンテンツ、その他の資料、または他の第三者資料、あるいは広告キャンペーン全体で X Materials を混合するか、X Materials との組み合わせ表示を作成することを、ここで明示的に詳述されている場合、または事前に X から書面で承認されている場合を除き、許可しません。
5.4.11 Company は、他の当事者(Client を含む)にも、Company Service および/または X Materials を広告ネットワークの一部として提供すること、あるいは X の事前の書面による同意なしに、X Materials のプログラム化されたエクスポートを可能にすること、または第三者(Client を含みますが、これらに限定されません)による、または第三者への X Materials の機械的消費を可能にすることを、許可しません。
5.4.12 Company は、他の当事者(Client を含む)にも、X Network にアクセスするユーザーを誤解させるまたは欺くような方法で(インセンティブ、ポイント、報酬、現金、賞品、その他金銭的価値のあるものを提供する方法、あるいは悪意的または詐欺的なその他の方法を含みます)Ads Products とやり取りするようユーザーを奨励または要求することを、許可しません。
### 6. 組み込まれた条件。
Company の任意の Individual Product および/または関連する X Materials へのアクセスは、以下のポリシー(総称して「**X Policies**」)への Company の承諾および遵守を条件とします。ただし、それぞれ、Company がアクセスおよび/または利用している Individual Product および X Materials に該当する範囲でのみ:
**6.1** プライバシーポリシー([https://x.com/privacy](https://x.com/privacy))
**6.2** 利用規約([https://x.com/tos](https://x.com/tos))
**6.3** 該当する X Master Services Agreement([https://legal.x.com/ads-terms/us.html](https://legal.x.com/ads-terms/us.html))([https://legal.x.com/ads-terms/international.html](https://legal.x.com/ads-terms/international.html)) または挿入注文書上で参照されるその他の X Master Services Agreement。
**6.4** 広告ポリシーガイドライン([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies))(コンバージョントラッキングおよび Custom Audiences のためのポリシー([https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences))を含む)
**6.5** 開発者契約およびポリシー([https://docs.x.com/developer-terms/agreement](/developer-terms/agreement))
**6.6** X 商標およびブランドガイドライン([https://about.x.com/who-we-are/brand-toolkit](https://about.x.com/who-we-are/brand-toolkit))
Company は、個別のポリシーが適用される Individual Products にアクセスまたは利用する範囲で、X Policies に同意します。Company は、X Policies が X の独自の裁量で随時変更されることがあることを承認し、これに同意します。Company に影響を与える X Policies への重大な変更があった場合、X はそのような変更について Company に通知(電子メール、または X Service 上に掲示することによる)を提供します。そのような更新または変更の後の X Materials および X Marks への Company の継続的なアクセスまたは利用は、その更新および変更の拘束力ある承諾を構成します。
### 7. 期間、終了権、停止権。
**7.1 期間。** 本契約は発効日に開始し、1 年間(以下「**Initial Term**」)有効となり、その後、Initial Term の満了の少なくとも 30 日前にいずれかの当事者が更新しない旨の書面による通知を提供するか、下記第 7.2 節に従って本契約を終了させない限り、その後 1 年ごとの追加の連続期間(それぞれ「**Renewal Term**」)で自動的に継続します。Initial Term およびすべての Renewal Terms は、集合的に「**Term**」を構成します。
**7.2 終了、停止。** Initial Term の完了および Renewal Term の開始時、いずれかの当事者は、他方への 30 日間の事前通知に基づき、都合により本契約を終了することができます。X は、次のいずれかに該当する場合、Company への書面による通知に基づき本契約を直ちに終了することができます: (a) Company が第三者との、自発的または非自発的、および/または法律の運用による、全部または一部の合併もしくは買収された場合(合併、買収、または資産売却の場合を含みますが、Company が存続または消滅法人であるかを問わず、これらに限定されません);または (b) Company が財産に対する管財人または類似の当事者を任命され、支払い不能となり、いかなる方法でも支払い不能を認め、事業を停止し、債権者のために譲渡を行い、または破産の申立てを行った場合。本契約または法律もしくは衡平法上利用可能な他の救済策を制限することなく、X はその独自の裁量により、次のいずれかを信じるまたは判断する場合、いつでも通知なしに、Ads Products、任意の Individual Product、および/または X Materials(またはその一部)への Company のアクセスもしくは利用を直ちに停止するか、本契約に基づき Company に付与されたすべてのライセンス、または本契約全体を終了することができます: (i) Company が Our Policies のいずれかに違反しているか、本契約のいずれかの条項に違反したか、違反しようとしているか、または遵守していない;および/または (ii) Company の Ads Products、Individual Product、および/または X Materials への継続的なアクセスが、X および/または X の Client の責任を引き起こす、または引き起こす可能性がある、あるいは X または X の Client のサービス、事業、または評判に損害を与える。
**7.3 終了の効果。** 本契約の満了または終了時: (a) ここに付与されたすべての権利およびライセンスは直ちに終了し、Company は X Materials へのアクセスおよび利用を直ちに停止します;(b) そのような満了または終了から 30 日以内に、Company は Company Service から、または Company の所持もしくは管理下にあるすべての X Materials(すべてのコピーおよびその一部を含みます)を、あらゆる形式および種類のメディアにおいて削除、除去、および安全に消去します;および (c) そのような満了または終了から 30 日以内に、Company は Company の所持もしくは管理下にある Confidential Information(下記第 9 節に定義)のすべてのコピーを削除し、安全に消去します。X は、本契約の終了の結果として、いかなる費用、経費、または損害についても責任を負いません。
**7.4 Wind Down 期間。** 前述にかかわらず、いずれかの当事者が本第 7 節に従って本契約を終了した場合、本契約の条項、および当事者のそれぞれの権利および義務は、X の独自の選択により(および Company への当該選択の書面による通知に基づき)、そのような終了時に進行中の Client 広告キャンペーンのみに関して(X および/または該当する Client が広告キャンペーンを実施することを選択した状況(そのような広告キャンペーンが終了時に実際に開始していない場合を含む)を含みますが、これに限定されません)、Wind-Down Period(以下に定義)中に引き続き適用されます。ここで使用される「**Wind-Down Period**」とは、Term の終了時に始まり、次のいずれか早い方まで継続する期間を意味します: (i) 当該終了日から 90 日;または (ii) 当該終了日時点で進行中(上記で説明したとおり)であったすべての Client 広告キャンペーンの完了。
**7.5 存続。** 本契約の満了または終了後もその性質上存続すべき条項は、第 3 節から第 15 節を含みますが、これらに限定されない条項として、存続するものとします。
### 8. セキュリティ、セキュリティ侵害、規制上の通知、データ削除、監査。
**8.1 セキュリティ。** Company は、本契約に基づく履行に関連して、業界標準のセキュリティ対策を利用します。これには、X Materials に含まれるデータの種類の送信および保管について、少なくとも業界標準のセキュリティ対策と同等以上に制限的な、データ送信および保管のための管理的、技術的、および物理的なセキュリティ対策を含みますが、これらに限定されません。Company は、また、合理的な技術的および組織的なセキュリティ対策(少なくともパスワード保護およびアクセスプロトコル制限を含む)を利用し、いかなる場合も、Company が同じまたは類似の性質を持つ自己のデータの送信および保護に関連して利用する注意より少ない注意で、X Materials へのアクセスを制限し、Company の権利の行使および/または本契約に基づく Company の義務の履行のためにそのような X Materials にアクセスする必要のある Company の従業員のみに Confidential Information および X Materials を制限します。
**8.2 セキュリティ侵害。** Company は、本契約に関連する、または本契約に基づく X Materials および/またはデータの露出をもたらしたか、もたらす可能性があったか、または露出する可能性のあるセキュリティ侵害またはその他の不適切なアクセスを認識してから 24 時間以内に、X に書面(電子メールを含む場合があります)で通知するものとします。Company は、あらゆる調査において X と協議・協力し、必要な通知を提供し、および/または X から合理的に要求される情報を提供します。
**8.3 規制上の照会。** Company は、セキュリティ侵害(または類似のインシデント)、Company の消費者データの誤用の疑い、または本契約に直接的もしくは間接的に合理的に関連する Company の運営のその他の側面に関する、政府または規制当局からの照会の通知を Company が受領してから 24 時間以内に、X に書面(電子メールを含む場合があります)で通知するものとします。
**8.4 データ削除。** Company は、Company が本契約に基づき Company の権利を行使し、および/または義務を履行するために当該 X Materials を保持する正当な事業上の必要性を有しなくなった時点で(該当する Client が Ads Products の利用を停止するか、その他の方法で Company Services の利用を停止する場合を含みますが、これに限定されません)、また、いかなる場合も次のいずれか早い方までに、システムからあらゆる X Materials を削除し、安全に消去します: (a) Company が最初に該当する Data を受領した日から 90 日、または (b) 本契約の満了または終了日から 30 日。加えて、Company は、いつでも、X の書面による要求(電子メールを介して配信される場合があります)に応じて直ちに、X が削除および安全な消去が必要または望ましいと判断する(X の独自かつ絶対的な裁量による)あらゆる X Materials を削除および安全に消去することに同意します。
**8.5 監査。** 合理的な事前書面通知(10 日以上)により、Term 中の各暦年で 2 回を超えず、また本契約が終了または満了した日以降の 6 か月間に 1 回、X の費用で、Company の権利を行使し、本契約に基づく義務を履行する際に Company が利用するプロセス、方法論、実践、およびシステムを監査するために、X に Company の施設へのアクセスが提供されるものとします。明確性のために、Company は、以下を承認し、これに同意します: (i) X は、そのような監査を代行する第三者監査人を任命することがあります;および (ii) ここに反する定めにかかわらず、X はそのような監査を促進するために必要な範囲でのみ、Company に関する関連する Confidential Information(本契約の条項を含みますが、これに限定されません)を当該第三者監査人と共有することがあります。
### 9. Confidential Information。
各当事者は、「秘密」または「専有」に指定された、あるいは合理的な人物が開示当事者による情報の秘密性の性質を理解する方法で開示されたすべての事業、技術、および財務情報(「**Confidential Information**」)に同意します。明確性のために、本契約に基づき X が Company に提供するすべての専有情報(X の技術、設計、技術、研究、ノウハウ、仕様、製品計画、価格設定、顧客情報、ユーザーデータ、現在または将来の戦略情報、現在または将来の事業計画、ポリシーまたは実践、従業員情報、およびその他の事業および技術情報(X Service の稼働時間、信頼性、トラフィックおよび成長メトリクス、ネットワーク品質、およびその他の利用統計に関する結果、分析、またはデータで、Company の X Materials または X Service の利用から派生する集約またはその他の形式、および/または技術文書、開発者ニュースレターおよび/またはオンラインポータルまたはフォーラムへのアクセスから派生するものを含みますが、これらに限定されません)に関する情報(有形または無形)を含みますが、これに限定されない)は、X の Confidential Information であり、X に専有です。前述を制限することなく、本契約の条項、X Materials、製品要件、および本契約に基づき X から Company に提供されるその他のドキュメンテーション、オンボーディングプロセス、またはその他の資料は、X Confidential Information とみなされます。ここに明示的に許可されている場合を除き、受領当事者は、開示当事者の Confidential Information を秘密に保ち、利用または開示しないものとします(当該当事者の本契約に基づく義務の履行に関連する場合を除く)。受領当事者は、次の情報については本節に基づく義務を負わないものとします(受領当事者が書面または証言によって、当該情報について次のことを立証できる場合): (i) 受領当事者またはその従業員もしくは代理人の過失によらず、公に容易に入手可能となったか、なっている;(ii) 当該情報を合法的に所持する第三者から受領したものであり、受領当事者はそのような第三者に対する開示制限の知識を有しない;(iii) 開示当事者によって開示制限なしに第三者に開示されている;(iv) 他方当事者による開示の前に、受領当事者が制限なく合法的に所持していた;または (v) そのような情報に依拠せず、受領当事者の従業員またはコンサルタントによって独立して開発された。受領当事者は、法律または裁判所命令によって要求される開示を行うことができます。ただし、受領当事者は開示当事者に当該命令の発行を通知し、開示当事者が手続きに参加することを許可するものとします。
### 10. 表明および保証。
Company は次のことを表明・保証します: (i) 本契約を締結するために必要なすべての法的および企業的権限を有すること;(ii) 本契約を法的、有効、かつ拘束力ある義務とするために必要なすべての行動を行ったこと;(iii) 本契約に基づく義務の履行を妨害する、または妨害する第三者との合意または了解を有していないこと;(iv) 本契約に基づき付与されるすべての権利およびライセンスを付与し、義務を履行するために必要なすべての許可、同意、権利、承認、およびライセンスを取得しており、維持していること(Company Materials を利用して X Service 上または他の方法で X が利用可能または利用可能となる広告インベントリに広告を掲載し、Company Service を提供するために X にライセンスを付与するために必要な、Company のすべての権利を含みますが、これに限定されません);(v) Company Service および Company Materials は、いかなる第三者の権利も侵害、不正流用、その他の方法で侵害せず、侵害しないこと;および (vi) 本契約に基づく Company の事業および履行(Company Service の提供を含む)は、適用されるすべての外国、連邦、州、および地方の法律、政府規則、および規制に準拠しており、準拠すること。Company はさらに次のことを表明・保証します: (a) Company Service、Company Materials、または本契約に関連する他の成果物、あるいはデータセキュリティ、データ利用、またはプライバシーに関する Company の実践に関する、実際の、係属中の、または脅威のある請求、訴訟、行動、または告発の知識を有しないこと;および (b) Company が Client を代表して Ads Products(またはその側面のいずれか)にアクセスまたは利用している場合、Company は当該第三者の代理人として、当該第三者に代わって当該 Company Materials を利用し、Company Materials に提供される当該第三者の資料の権利を X に譲渡し、そのような第三者を本契約の条項に拘束する権限を有すること。
### 11. フィードバック。Beta Services。
X が(独自かつ絶対的な裁量により)、プライベート、未リリース、開発中、または「アルファ」または「ベータ」に指定された機能および機能性(総称して「**Beta Services**」)へのアクセスを Company に提供する範囲において、Company は、Beta Services が X によってサポートされておらず、Beta Services(またはその一部)がいつでも公開されるか、または利用不可となる可能性があること(それぞれの場合、X の独自かつ絶対的な裁量による)を承認し、これに同意します。Beta Services は、法律で許容される最大限の範囲で「現状のまま」提供され、Company の Beta Services の利用は Company 自身のリスクおよび同意で行われます。すべての Beta Services は、X Confidential Information とみなされます。Company は、Beta Service への参加が、既存および/または将来のプログラム、商品、および/またはツールの調査、分析、および検証において X を支援すること、および Company が X に、当該プログラム、商品、および/またはツールの評価および改善を支援するためのコメント、フィードバック、その他の情報を提供する場合(以下「**Feedback**」)、X およびその指名する者は、Company または第三者へのいかなる義務または報酬もなく、Feedback(それらの派生物を含む)をあらゆる商用および非商用目的のためにコピー、変更、派生物の作成、公開表示、開示、配布、ライセンス供与、サブライセンス、組み込み、その他の方法で利用することが自由にできることに同意します。明確化のために、Feedback には Company の名前は含まれず、X は Company の名前を利用したり、Company の Beta Services のパフォーマンス結果を公に開示したりしません。Feedback には、X Materials、Ads Products、および/または Company の評価および利用に関する Company のコメントも含まれます。Company は、本契約のいかなる規定も、X が Company または任意の Client または End Users の商品またはサービスと競合する可能性のある商品またはサービスを開発することを妨げないことに同意します。
### 12. 保証否認。
本契約に基づき提供される X Materials、Ads Products、およびその他の X 商品およびサービス(Beta Services を含みますが、これらに限定されません)、および X Marks は、「現状のまま」および「利用可能な範囲」で、いかなる種類の保証もなく提供されます。X は、明示、黙示、法定、その他を問わず、商品性、非侵害、特定目的への適合性、および取引の過程または商慣行から生じる保証または条件を含む、あらゆる保証を否認します。X は、本契約に基づき提供される X Materials、Ads Products、およびその他の X 商品およびサービス(Beta Services を含みますが、これらに限定されません)、または X Marks が、Company の要件を満たすこと、あるいはそのような X Materials、その他の X 商品およびサービス、および/または X Marks の利用がエラーフリー、中断なし、ウイルスフリー、または安全であることを保証しません。この保証否認は、一部の法域では有効でない場合があり、Company は放棄または否認できない法律に基づく保証権を有する場合があります。当該保証は、本契約の発効日から 30 日間のみ及びます(法律で別途規定されている場合を除く)。
### 13. 補償。
Company は、以下の申立てに基づき、第三者が X に対して提起した請求、訴訟、または行動について、自らの費用で防御します: (i) Company Materials、Company Service、Company Marks、X による Company Materials または Company Marks の利用、または Company Materials および/または Company Service の生成に利用されるテクノロジーが、いかなる第三者の権利(知的財産権、プライバシー権、またはパブリシティ権を含みますが、これらに限定されません)を侵害する;(ii) Company が、Company のデータセキュリティ、データ利用、およびプライバシーの義務を含む、ここでの義務、表明、または保証のいずれかに違反した;または (iii) 本契約に定める条件、条項、および制限に違反する、X Materials および/または X Marks の Company による無許可の利用。Company は、当該請求に起因するあらゆる損失、損害、責任、罰金、費用、および経費から X を補償し、X を損害を受けないよう維持します。Company は、X に対する請求の防御に責任を負い、X が自ら選択した弁護士とともに参加する権利、および X に対するすべての請求から生じるすべての判決、和解、損害、損失、責任、費用、および経費(合理的な弁護士費用を含む)の支払いに責任を負います。ただし、Company は、当該和解が X をいかなる義務または責任からも解放するか否かにかかわらず、X の事前の明示的な書面による同意なしに、請求に関する和解に同意しません。X は、補償義務について Company に速やかな通知を行います(その通知を怠った場合、Company の義務は、当該通知の失敗から実質的な不利益を実証できる範囲でのみ免除されます)。
### 14. 責任の制限。
いかなる場合においても、X は、Company または Clients、End Users に対して、特別、付随的、模範的、懲罰的、または結果的損害、あるいは、収益の損失、利益の損失、商品またはサービスの代替費用、テクノロジーの損失、営業権、サービス権利、データの損失、または本契約に起因もしくは関連するサービス中断もしくはサービス利用の損失、または Company または Client、End User の本契約に基づき提供される X Materials、X Marks、または X の商品および/またはサービス(Ads Products を含みますが、これらに限定されません)の利用について、責任を負いません。そのような責任が契約、保証、不法行為(過失を含む)、厳格責任、その他に基づく請求から生じるかどうか、および X がそのような損失または損害の可能性について通知されたかどうかにかかわらず。適用される法律が本規定の責任のいかなる制限も禁止している場合、当事者は、その制限が適用される法律に適合するように自動的に修正されることに同意します。ただし、適用される法律に準拠するようにするための範囲でのみです。当事者は、本規定に定める責任の制限が合意されたリスクの配分であり、いかなる限定的救済策の本質的目的の失敗にもかかわらず適用されることに同意します。いかなる場合も、本契約に基づく X の総合的な責任は 50 米ドル (U.S. \$50) を超えないものとします。
### 15. その他。
**15.1 パブリシティ。** Company は、本契約、ここに定める活動のいずれか、または Company と X との間の関係に関するプレスリリース、ブログ投稿、その他の公的発表または開示を、X の事前の書面による同意(電子メールで提供される場合があります)なしに行うことはできません。
**15.2 ユーザーの保護。** Company は次のことを行いません: (a) 政府機関、法執行機関、その他の組織による X Service または X Materials に対する監視、あるいは X のユーザーまたはその投稿に関する、召喚状、裁判所命令、その他有効な法的手続きを必要とする情報、または X のユーザーの合理的なプライバシー期待と矛盾する可能性のある情報の取得を、故意に許可または支援すること;または (b) Universal Declaration of Human Rights([https://www.un.org/en/universal-declaration-human-rights/index.html](http://www.un.org/en/universal-declaration-human-rights/index.html) 所在)(特に第 12 条、第 18 条、または第 19 条を含みますが、これらに限定されません)に違反するために当該データを利用すると Company が合理的に信じる個人または事業体に、X Materials を表示、配布、その他の方法で利用可能にすること。X ユーザーに関する情報を求める法執行担当者は、[https://help.x.com/rules-and-policies/x-law-enforcement-support](https://help.x.com/rules-and-policies/x-law-enforcement-support) にある X の Guidelines for Law Enforcement を参照するようご案内します。
**15.3 政府による利用。** X Materials は、48 C.F.R. 2.101 で定義される「商用アイテム」であり、48 C.F.R. 12.212 で使用される「商用コンピュータソフトウェア」および「商用コンピュータソフトウェアドキュメンテーション」で構成されている場合があります。政府機関による X Materials の利用、変更、派生物、複製、リリース、実行、表示、開示、または配布は、本契約の条項によって明示的に許可されている場合を除き、禁止されています。加えて、米国政府機関による利用はすべて、48 C.F.R. 12.212 および 48 C.F.R. 227.7202-1 から 227.7202-4 に従って行われる必要があります。契約者/製造者は、X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA です。
**15.4 法令遵守、輸出/輸入。** 各当事者は、適用されるすべての外国、連邦、州、および地方の法律、規則、および規制を遵守します。Company は、Our Policies(ここに定義)または適用される法律に違反して X Services または X Data を輸出または再輸出してはなりません。X Materials は、米国輸出法の対象となり、配達または利用される国の輸入および利用法の対象となる場合があります。Company は、これらの法律を遵守することに同意します。これらの法律の下で、X Materials は、ライセンスまたは関連する政府当局の承認なしに、これらの法律によって制限された国、または外国国民(米国政府が禁輸措置を講じている国を含む)、または制限もしくは拒否されたエンドユーザー(米国財務省外国資産管理局によって禁止されている個人または団体を含みますが、これらに限定されません)に、あるいはいかなる制限された最終利用のためにも、販売、賃貸、ダウンロード、移動、輸出、再輸出、または国境を越えて移転してはなりません。
**15.5 変更。** X は、随時、独自の裁量により、Our Policies、Analytics Data Display Requirements([Exhibit A-2](#Exhibit-A-2) として添付)、「X Marketing Partner」プログラム関連の条項([Exhibit C](#Exhibit-C) として添付)、およびその他の技術文書、その他のガイドライン、または X Materials に関するポリシーを、X の開発者サイト([https://developer.x.com](https://developer.x.com)(随時修正されることがあります))、該当する X ポリシーが掲示されている URL に該当する変更を掲示することにより、またはその他の方法で Company に通知(電子メールによる場合があります)することにより、更新または変更することができます。いずれかの変更が Company にとって受け入れがたい場合、Company の唯一の救済策は、X Materials および X Marks のすべての利用を停止することです。
**15.6 通知。** 第 6 節および第 15.5 節に別途記載されている場合を除き、本契約により必要または許可される通知は、書面で行われ、次のとおり配信され、通知は指定されたとおり与えられたものとみなされます: (a) 個人的な配達により、個人的に配達された時点;(b) オーバーナイト宅配便により、受領の書面による確認時;(c) 認証または登録済みの郵便により、受領確認要求で受領の確認時;または (d) 電子メールにより、受信者が該当する電子メールを受信したことを認める時。通知は、以下に定めるアドレス、または各当事者が書面で指定する他のアドレスに送信されます。Company から X への違反に関する通知は、オーバーナイト宅配便または認証もしくは登録済みの郵便のみで送信する必要があります。Company への通知は、X に登録された Company のアドレスに送信されます。X Corp. への通知は次に配信されます: X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA, Attn: Legal Department、Head of Ads API および [legalnotices@x.com](mailto:legalnotices@x.com) への必須の複写と共に。X Internet Unlimited Company への通知は次に配信されます: Legal Department, X Internet Unlimited Company, One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland。
**15.7 譲渡。** Company は、X の明示的な書面による同意なしに、本契約または本契約に基づき付与された権利もしくは義務の全部または一部を、自発的に、非自発的、および/または法律の運用により(合併、買収、資産売却の場合を含みますが、Company が存続または消滅法人であるかにかかわらず、これらに限定されない)第三者に譲渡してはなりません。本項に違反する譲渡の試みはすべて無効となり、X は本契約を直ちに終了することができます。本契約は、各当事者の許可された承継人および譲受人の利益のために拘束され、それらに継承されます。
**15.8 下請人なし。** Company は、事前に X から書面(電子メールで提供されることがあります)で承認された場合を除き、本契約に基づく義務または職務のいずれかを履行または遂行するために第三者を利用してはなりません。
**15.9 パートナーシップなし。** 本契約は、パートナーシップ、代理、または合弁事業を作り出したり、暗示したりするものではありません。本契約に基づく約束または権利のいずれの当事者による放棄も、当該当事者によって正当に承認された書面に記載されない限り、有効ではありません。
**15.10 第三者受益者なし。** 本契約に第三者受益者はないものとします。
**15.11 可分性。** 本契約のいずれかの部分が管轄権のある裁判所によって無効または執行不能と判断された場合、その規定は許容される最大限の範囲で執行され、本契約の残りの規定は完全な効力を有し続けます。
**15.12 放棄。** 一方の当事者による、他方の当事者による本契約のいずれかの規定の違反の放棄は、当該当事者による他のまたは以後の違反の放棄として作用または解釈されないものとします。X による本契約に基づく約束または権利の放棄は、X によって正当に承認された書面に記載されない限り、有効ではありません。
**15.13 集団訴訟の放棄。** 法律で許容される範囲において、あなたは、いかなる主張された集団訴訟、集合訴訟、または代表訴訟手続きにおいても、原告または集団構成員として参加する権利も放棄します。
**15.14 準拠法および裁判管轄。** X Corp. が本契約の締結事業体である場合、本契約の条項および Company と X との間の紛争は、抵触法/法選択の原則にかかわらず、テキサス州法により規定されます。国際物品売買契約に関する国際連合条約は、本契約に適用されません。本契約に起因もしくは関連する、あるいはその違反、終了、執行、解釈、または有効性(仲裁するこの合意の範囲または適用可能性の決定を含む)に関する紛争、請求、または論争が生じた場合、Company は X に紛争の通知を提供し、X および Company が非公式に紛争を解決するために協議する 10 営業日の解決期間を提供することに同意します。10 営業日の解決期間の後、X と Company が紛争を解決できない場合、Company は本契約に起因する紛争または請求を、テキサス州北部地区の米国地方裁判所または米国テキサス州タラント郡に所在する州裁判所に提起することに同意し、あなたはこれらの法廷における対人管轄に同意し、不便な法廷に関する異議を放棄します。前述にかかわらず、X が、独自の裁量で、あなたに対して有する請求、訴因、または紛争を、請求について管轄権と裁判地を有するあなたが居住する国の管轄裁判所に提起することができることに同意します。
米国において公務上権限のある連邦、州、または地方政府機関であり、法的に上記の準拠法、裁判管轄、または裁判地条項を受け入れることができない場合、それらの条項はあなたに適用されません。そのような米国連邦政府機関については、本契約およびそれに関連するいかなる訴訟も、米国法(抵触法への参照なし)により、連邦法がない場合および連邦法で許容される範囲内で、テキサス州法(法選択を除く)により規定されます。
X Internet Unlimited Company が本契約の締結事業体である場合、本契約の条項および Company と X との間の紛争は、抵触法/法選択の原則にかかわらず、アイルランド法により規定されます。当事者は、当事者が事業を行うか設立された州にかかわらず、国際物品売買契約に関する国際連合条約も、統一コンピュータ情報取引法 (UCITA) も本契約に適用されないことに同意します。本契約に起因もしくは関連する、あるいはその違反、終了、執行、解釈、または有効性に関する紛争、請求、または論争は、あなたと当社との間の反対の合意にかかわらず、アイルランドの管轄裁判所においてのみ提起され、抵触法規定を考慮せずアイルランド法により規定されます。前述にかかわらず、X が、独自の裁量で、あなたに対して有する請求、訴因、または紛争を、請求について管轄権と裁判地を有するあなたが居住する国の管轄裁判所に提起することができることに同意します。
X に対する請求提起は 1 年以内です。適用される法律が、その請求に対する通常の時効を合意で短縮することを許可しないと規定していない限り、本契約に起因または関連するいかなる請求も、紛争を生じさせる事象または事実の発生日から 1 年以内に X に対して提起する必要があります。この期間内に請求を提起しない場合、当該事象または事実に基づく、あらゆる種類または性質の請求または訴因を追及する権利を永久に放棄し、そのような請求または訴因は永久に禁じられ、X はそのような請求について責任を負いません。
**15.15 差止による救済。** 各当事者は、X の知的財産(X Materials を含みますが、これに限定されません)および/または X の Confidential Information を保護する本契約の規定の違反または違反のおそれが生じた場合、金銭的損害賠償が不十分な救済策となることに同意し、当該違反または脅威の場合、X は既得の他の救済策に加えて、担保金を提供する必要なく、予備的または差止による救済(他方当事者が当該規定に違反する行為を行うことを禁止する命令を含む)、および X のすべての権利を維持するために適切な特定履行を受ける権利を有します。
**15.16 更新。** X は、独自の裁量で、随時本契約および本契約で参照されるポリシーの条項を更新することがあり、Company に電子メールで通知するか、以下に特定される URL に掲示することによる通知を提供します。当該通知は、そのような更新の発効日を示します。本契約の条項は、[https://docs.x.com/developer-terms/ads-api-agreement](/developer-terms/ads-api-agreement) にて Company がいつでも閲覧できるものとします。該当する通知に定められた発効日以降の Company による Individual Product の継続利用は、当該更新の Company の承諾を示します。
**15.17 完全合意。** 本契約(添付の Exhibit を含む)は、本契約の対象事項に関する当事者間の完全な合意を構成し、そのような対象事項に関する事前または同時期のすべての提案、了解、通信、および合意(口頭または書面を問わず)に優先し、置き換えます。本契約への変更は書面で行われ、それぞれの当事者を拘束する権限を有する代表者によって署名される必要があります。
## Exhibit A: Individual Product 条件 / X Ads API
これらの Individual Product 条件で定義されていない大文字で始まる用語は、本契約の本文で定められた意味を有します。Company が「X Ads API Program」に参加する範囲において、本 Exhibit A(Exhibit A-1 および Exhibit A-2 を含む)の以下の条項が適用されます:
### 1. X Ads API はじめに、アクセス。
**1.1 はじめに。** X の広告アプリケーションプログラミングインターフェース (API)、および付随するドキュメンテーション、コード、および関連資料(総称して「**X Ads API**」)は、Company に対して、X Ads の Campaign Management を可能にする「読み書き」アクセス、および/または X Ads Campaigns のパフォーマンスに関する Data の特定のレポートへの「読み取り」アクセスを提供します。
**1.2 API アクセス。** X は(独自かつ絶対的な裁量により)、Company に「読み取り」または「読み書き」の X Ads API アクセスを付与するかどうかを決定します。X は、X Ads API アクセスを付与するためのレビュープロセスを実装することがありますが、これは義務ではありません。
### 2. Ads API ライセンス。
X が Company に X Ads API アクセスを提供することを決定し、Company が本契約の条項の継続的な遵守を条件として、X は Company に、Term の期間中、次の目的のために限定的、非独占的、譲渡不可、サブライセンス不可、取消可能なライセンスを付与します: (a) X Ads API を利用して、Client の End Users に、当該 Client の X Ads Campaigns に関連する Data へのアクセスを提供する目的で Company Service を実装すること(Company が「読み書き」の API アクセスを有する場合、Company Service を通じて X Ads の Campaign Management を可能にすること);(b) 当該 Client の X Ads Campaigns を最適化する目的でのみ、Analytics Data Display Requirements(本 Exhibit A の下記第 3 節に定義)に従い、Client の End Users に対して集約された形式で Company Service 内で Data を表示すること;(c) Company Service 内で表示するために書式を整えるためにのみ Data を変更すること;(d) X が書面で承認し、Analytics Data Display Requirements に準拠する形式で、X が書面で承認したエクスポートメカニズムを介して Data のエクスポートを Company Service で可能にすること;および (e) X が X Ads API および/または Data に関連する利用のために利用可能にする X Marks を、Data の出典として X を帰属表示するためにのみ、または本契約に基づき他の方法で明示的に許可される場合にのみ利用および表示すること(それぞれの場合において、X Trademark Guidelines に従って)。
### 3. 表示要件、統合、およびその他の要件。
Company の X Ads API および Data の実装および利用は、以下に常に準拠する必要があります: (a) Exhibit A-1 として添付される製品要件(「**Product Requirements**」);(b) Exhibit A-2 として添付される表示要件(「**Analytics Data Display Requirements**」);(c) 提供されているか将来 X から Company に提供される X Ads API のすべての技術文書(エンドポイント仕様または要件を含みますが、これらに限定されない);(d) X Ads API および Data に関連する、X が指定するオンボーディングプロセス;(e) Our Policies;および (f) X から Company に提供される X Ads API および Data に適用されるその他のガイドラインおよびポリシー。
### 4. 遵守。
Company は、X が Company に提供または伝達するすべての指示を遵守します。これには、X Ads API のアクセス、コール、および利用に関する制限、およびトークン、レート制限、キー、パスワード、その他 X Ads API のログイン認証情報に関する追加の制限または制約が含まれますが、これらに限定されません。当該指示は、X の独自かつ絶対的な裁量により決定されます。Company は、X による Company Service の検査およびアクセスの要求を遵守します。これには、X Ads API の Company Service への統合、および Data の Company Service 内での表示が、Product Requirements および Analytics Data Display Requirements、X の品質管理、および/または本契約のその他の条項に準拠していることを確認するために、X Ads API の実装に関連する Company Service のコードを X に提供することが含まれますが、これに限定されません。X は、X Services を改善するために、Company の X Ads API の利用状況を監視することがあります。
### 5. X Ads インベントリの割り当ての管理。
明確性のため、本契約の他の条項の一般性を制限することなく、本契約のいかなる規定も、Company または Company Service が、X Ads API を通じて、特定のインベントリまたは X Ads のカテゴリーへのアクセスを持つことを表明または暗示することを意図するものではありません。X は(独自かつ絶対的な裁量により)随時、Company または Company Service がアクセスできる X Ads インベントリの割り当てを制限することを選択できます(例: X の販売チャネル、直接または非直接クライアント関係、代理店関係などに関する戦略的決定によるものを含む、制限なしに)。
### 6. X Ads 機能、API 呼び出し、および機能性の管理。
明確性のため、本契約の他の条項の一般性を制限することなく、本契約のいかなる規定も、Company または Company Service が、X Ads API を通じて、特定の X Ads 機能、API 呼び出し、または機能性へのアクセスを持つことを表明または暗示することを意図するものではありません。X は(独自かつ絶対的な裁量により)随時、Company または Company Service がアクセスできる X Ads 機能、API 呼び出し、および/または機能性を制限することを選択できます(いかなる理由でも、または理由なく)。
### 7. 地理データ。
Company は、他者による利用を許可することも含めて、X Ads API を利用またはアクセスして、Data またはその他に含まれる場所またはその他の地理的位置情報を集約、キャッシュ、または保存してはなりません。
### 8. 削除。
X が X Ads API またはその他を通じて要求した場合、Company は速やかに次のことを行います: (a) X が削除済みまたは期限切れと報告する Company Service からの Data を削除;(b) X が共有オプションが変更されたと報告する Data の取り扱いを変更;および (c) X が変更されたと報告する Company Service 上の Data を変更。Company は、Company Service によって X Service に送信される X Ads の品質に責任を負います。X は、Company または Clients による問題のある利用について、X Ads API へのアクセスを取り消す権利、および/または、該当する場合、特定の X Ads を X Service から削除する権利を留保します。
### 9. 更新。
Company は、X が随時、独自かつ絶対的な裁量により、X Ads API を更新または変更することがあることを承認します(それぞれの場合、「**Update**」)。X と Company の間で事前に書面(電子メールで足りる)で相互に別途合意されない限り、Company は、X Ads API の最新のバージョンを実装および利用し、X が Update を Company に通知した日から 30 日以内に、当該 Update の結果として必要となる Company Service への変更を、Company の単独の費用および経費で行う必要があります。Company は、Update を可能にするために X が提供するすべてのツール(該当する場合)を実装します。Update は、Company Service が X Ads API にアクセスまたは通信する方法、あるいは Data を表示する方法に悪影響を与える可能性があります。当該 Update の後の X Ads API への Company の継続的なアクセスまたは利用は、その Update の拘束力ある承諾を構成します。
### 10. サポート。
Company は、Company Service の利用に関する Clients およびその End Users へのすべてのサポートおよび技術支援を提供する責任を負います(Ads Product に関する問題を含む)。X は、Company または任意の Clients またはその End Users に対して直接サポートまたは技術支援を提供する義務を負わず、Company は、X が当該サポートを提供できることを Client またはその End Users に対して表明しません。
## Exhibit A-1: Product Requirements
Company Service は、マーケターがより効率的に X Ads キャンペーンを最適化し、X のリアルタイムの会話を活用し、ユーザーエクスペリエンスを向上させる X Ads を開発することを可能にする必要があります。
したがって、Company Service は常に以下の要件を満たします:
### 1. 製品価格設定。収益化なし。
Company Service への有料アクセスは、固定または可変の支出比率手数料構造で価格設定される必要があります。Company は、Company Service を通じた X Ads および/または Data へのアクセスに対して、Company Service の標準料金を超えるプレミアムを Clients に課金してはなりません。
### 2. 透明性。
**2.1 支出。**
2.1.1 Company が Clients およびその End Users に配信する価格レポートは、(i) X のネイティブメトリクスでの X Ads 支出(該当する場合、CPE/CPF など)、および (ii) Company Service の利用のために課される手数料を明確に記載し、項目別にする必要があります。加えて、Company は、ラストクリック帰属メトリクス(例: CPC)またはその他のレポートメトリクス(例: CPM)に隣接して、常に CPE または CPF メトリクス(またはその他の該当する X のネイティブメトリクス)を含める必要があります。
2.1.2 Company Service は、X Ads API を介して提供されるすべてのメトリクスについて Company がレポートを作成できる能力を含む、セルフサーブレポートダッシュボードを含めます。
**2.2 Data。** Company は次のことを行います: (i) その時点で有効な Analytics Data Display Requirements に従い、X Integration(本 Exhibit A-1 の下記第 6.3 節に定義)に関連する Company Service 内で最新の Data を維持するために商業的に合理的な努力を利用すること;および (ii) Client の X Ads Campaigns および/または関連する分析データに関する情報に固有の重大な遅延を、Clients およびその End Users に明確に開示すること。
### 3. アカウント。
各 End User には、Company Service にアクセスするための独立したアカウント(一意のユーザー名およびパスワードを含む)が与えられる必要があります。
### 4. Company Service。
特定の Client 用の Company Service のカスタマイズされたバージョン(特定の Client 用の Company Service のホワイトラベルバージョンを含みますが、これに限定されません)は、事前に X によって書面(当該目的のためには電子メールで足りる)で承認される必要があります。
### 5. Clients およびアカウント管理。
**5.1** Client には、X Ads Campaigns を Company Service から迅速かつ容易に切り離し、X Ads アカウントの排他的、直接的な管理を取り戻すことのできる能力が与えられる必要があります。
**5.2** Client およびその End Users のみが、Company Service を介して当該 Client のアカウントデータまたは機能を閲覧することを許可されます。
### 6. その他の要件。
**6.1** X の機能を複製する Company Service の機能は、該当する X Trademark Guidelines に従い、X の命名法および機能名を利用する必要があります。
**6.2** 当事者が事前に書面で相互に別途合意しない限り、Company は、Company Service のユーザーインターフェースに具現化された当該資料の集約された派生物を除き、Clients およびその End Users または他の第三者に Data へのアクセスを提供してはなりません。
**6.3** Company は、X Ads API の実装、および Data の Company Service 内での統合および表示(総称して「**X Integration**」)が、本節に記載されているプロセスにより事前に X から承認されるまでは、X Materials を第三者(任意の Clients またはその End Users を含みますが、これらに限定されない)に商業化、販売、またはアクセスを提供してはなりません。Company は、X が X Integration をレビューできるように Company Service へのアクセスを X に提供します。X は、X Integration が承認または拒否されるかどうかを書面(電子メールで足りる)で Company に通知します(X の独自の裁量による)。Term の期間を通じて、Company は、X Integration に影響を与える Company Service への変更を X に提出し、X はその独自の裁量で書面(電子メールで足りる)で承認または拒否する権利を有します。
## Exhibit A-2: Analytics Data Display Requirements
これらの Analytics Data Display Requirements は、Company が Company Service 内で Data を表示する方法を規定します。Company は、これらの Analytics Data Display Requirements を常に遵守することに同意します。
### 定義されたメトリクス
Data を表示する Company Service に表示されるすべてのキャンペーンは、さまざまなキャンペーン目的(それぞれ「**Campaign Objective**」)に関連付けられた特定の X 定義メトリクスを含める必要があります。これらのメトリクスは、[https://docs.x.com/x-ads-api/analytics#metrics-by-objective](https://docs.x.com/x-ads-api/analytics#metrics-by-objective)(または X が随時選択する他の後継 URL)にあるエンドポイントおよび計算式に基づいて Company によって計算される必要があります。
### 表示ガイドライン
**1.** 特定の Campaign Objective に該当する定義されたメトリクス(本 Exhibit A-2 の「定義されたメトリクス」節で説明のとおり)は、Company Service 内でキャンペーンが表示されるたびに示される必要があります。
**2.** Company Service がオーガニックな投稿の分析データを表示する場合、Company は、Company のオーガニックな投稿の分析データの実装、利用、および表示に関して、[https://docs.x.com/developer-terms/agreement](/developer-terms/agreement) にある X 開発者契約およびポリシーを遵守する必要があります。
**3.** Company Service が、第三者のネットワーク上または第三者のパブリッシャーによって実行されたキャンペーンに関するメトリクス(すなわち「クロスチャネルメトリクス」)を Data と並べて表示する場合、以下の要件および制限が適用されます:
**3.1** Company Service 内で Data と並べて表示されるクロスチャネルメトリクスは、当該キャンペーンに該当する X 定義の Campaign Objective メトリクス(本 Exhibit A-2 の「定義されたメトリクス」節で説明のとおり)と同じカテゴリーのキャンペーン目的メトリクスのみを含めることができます。
一例のみとして - 広告主が第三者のネットワーク上でアプリインストールキャンペーンを実行している場合、当該アプリインストール Campaign Objective に該当する X 定義メトリクスと同じカテゴリーのクロスチャネルメトリクスのみを Data と並べて表示できます。
**3.2** クロスチャネルメトリクスを表示するためにデータを集約することは、集約されたメトリクス(すべての第三者ネットワーク/パブリッシャーにわたって)を、該当する X 定義の Campaign Objective メトリクス(本 Exhibit A-2 の「定義されたメトリクス」節で説明のとおり)と同じキャンペーン目的に関連付けられたメトリクスのカテゴリーに対して参照できる場合を除き、許可されません。一例のみとして - ネットワーク A、ネットワーク B、ネットワーク C の総エンゲージメントを集約することは、すべてのチャネルにわたるエンゲージメント率が同じ計算式を使用して計算されていない場合は許可されません。
**4.** Company Service が X 以外の第三者から提供されるメトリクスのカテゴリー(以下「**第三者提供メトリクス**」)を表示する場合、以下の要件および制限が適用されます:
**4.1** 上記第 3 節で定めるクロスチャネルメトリクスの表示に適用されるものと同じ要件および制限が、任意の第三者提供メトリクスの表示に適用されます。
**4.2.** Company Service 内でキャンペーンの Data と並べて表示される第三者提供メトリクスは、当該キャンペーンに該当する X 定義の Campaign Objective メトリクス(本 Exhibit A-2 の「定義されたメトリクス」節で説明のとおり)と同じカテゴリーのキャンペーン目的メトリクスである必要があります。一例のみとして:
* Company が第三者のソースからリンククリックおよびクリック率メトリクスを表示する場合、Company は第三者提供のリンククリックおよびクリック率メトリクスと並べて、X のクリックおよびクリック率メトリクスを表示します。
* Company またはその Client が、プロモーテッド投稿からのウェブサイトクリックを追跡するために第三者のトラッキングソリューションを使用し、そのデータが Company Service に表示される場合、Company は、当該第三者提供データと並べて、X からのリンククリック、クリック率、リンククリックあたりの費用、および CPA(利用可能な場合)を表示する必要があります。
**4.3** 本 Exhibit A-2 の第 4.2 節にかかわらず、第三者提供メトリクスが X Conversion Tracking Partner(以下に定義)によって提供される第三者トラッキングソリューションからのものである場合、X は、X から書面で事前に別途合意されない限り(それぞれの場合)、X Ads API を通じて配信された Data のみを(X Conversion Tracking Partner によって配信された対応するデータではなく)Company Service に表示することを要求します。誤解を避けるため、Company は、X Ads API を通じて配信された Data と並べて、または X Ads API を通じて配信された Data の代わりに、X Conversion Tracking Partner からのデータを表示しません。本 Exhibit A-2 で使用される、「**X Conversion Tracking Partner**」とは、承認された X コンバージョントラッキングパートナー(X が独自かつ絶対的な裁量により指定するもの)を意味します。
## Exhibit B: Individual Product 条件 / Custom Audiences
これらの Individual Product 条件で定義されていない大文字で始まる用語は、本契約の本文で定められた意味を有します。Company が X Custom Audiences Program を利用またはアクセスする範囲において、本 Exhibit B の以下の条項が適用されます:
### 1. Custom Audiences。
**1.1 はじめに。** X Custom Audiences Program は、X Service 上での広告 Campaigns のターゲティングのためのユーザーの特定のセグメント(それぞれ「**Custom Audience**」)のインポートおよび作成を可能にします。当事者は、X Custom Audiences Program を利用するために、Company、その Client、または X によって承認された第三者サービス(「**Data Partner**」)が、X がユーザーとのマッチングを完了し Custom Audiences を作成するために、ユーザーまたはデバイスのハッシュ化されたセット(電子メール、Cookie、デバイス ID、トラッキングピクセルなどを含む場合が多い)を X に提供する必要があることを認めます。特定のクライアントを代表して作成された Custom Audiences は、各 Client の X Ads アカウントに保存され、Company または Client が X Service 上での広告のターゲティングまたはリターゲティング(該当する場合)に利用します。
**1.2 データ利用およびオプトアウト。** Custom Audiences Program に関連して利用されるデータについて、[https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa) にある Data Protection Addendum に記載された義務に加えて、Company は同意し、該当する場合、その Data Partner が次のことに同意することを確保します: (i) Company または当該 Data Partner(該当する場合)は、当該データの利用に必要なすべての権利、同意、放棄、ライセンスを確保している、および (ii) Company または当該 Data Partner(該当する場合)は、データが収集される任意のユーザーに、ユーザーの関心へのターゲット広告を配信する目的で Company が X に提供するデータの収集、利用、共有を完全に開示する法的に十分な通知を提供しており、ここに記載されている方法で X の関心ベース広告からユーザーがオプトアウトする方法についての法的に十分な指示を提供している([https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads](https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads))。Company が Custom Audiences Program に関連して、および/または Custom Audience の作成のために利用するデータには、Company、その Data Partner、または Company を代表する第三者による自身のデータの利用からオプトアウトすることを選択したユーザーからのデータは含まれません。当該ユーザーが X に提供されたオーディエンスに含まれた後で Company がユーザーのオプトアウトを受領した場合、Company は速やかに、ただし 24 時間ごとに 1 回以上の頻度で、当該ユーザーが含まれた任意の Custom Audience から当該ユーザーを削除する必要があります。Company は、X によって選択され、Data Partner(該当する場合)に受け入れられる形式でデータを提供します。本契約の条項に加えて、Company の X Custom Audiences プログラムの利用は、[X Master Services Agreement](https://legal.x.com/ads-terms.html) および Custom Audiences Program T\&C、および適用されるポリシー(X の Policies for Conversion Tracking and Custom Audiences を含む)([https://legal.x.com/ads-terms.html](https://legal.x.com/ads-terms.html) および [https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences))の条項に従います。
**1.3 追加のプログラム要件。** Company の X Custom Audience Program へのアクセスおよび利用は、X が Company に提供する技術指示およびプログラムポリシー(以下「**Program Integration Spec**」)への Company の遵守を追加的な条件とします。Company と X は、Company が Custom Audiences を X にインポートまたはアップロードするプロセスについて相互に合意します。
### 2. 共有可能なオーディエンス。
上記第 1.1 節に反する定めにかかわらず、Company へのサービスとして、Company の要求および Company の独自の裁量により、X は Company が Company のために作成された Custom Audiences を、グループ化された X 広告主アカウントおよび/または X @ハンドル、および/または X Service 上の第三者と「共有」することを許可することがあります。ここで使用される、オーディエンスを「共有」することは、Company が X に、グループ化された X 広告主アカウントおよび/または X @ハンドル、および/または第三者が「共有された」Custom Audience に対してアクセス、利用、および広告 Campaigns のターゲティングを行うことを可能にするよう指示することを意味しますが、これに限定されません。Company は、Company が X に与える指示に従って当該オーディエンスデータを共有するために必要なすべての権利および権限を有することを表明・保証します。Company がオーディエンスデータを提供し、および/または第三者(Client を含みますが、これらに限定されない)を代表して Custom Audiences を管理する場合、Company は、当該第三者の代理人として、当該第三者を代表して当該データを利用し、ここに記載された権利を X に付与し、そのような第三者を本契約の条項に拘束する権限を有することを表明・保証します。前述にかかわらず、本節のいかなる規定も、X が「共有」Custom Audiences を可能にする機能(またはその一部)を、いつでも Company または他の第三者(Client を含みますが、これらに限定されない)に利用可能にすることを要求するものではありません。
## Exhibit C: Individual Product 条件 / X Marketing Partner (TMP) Program
これらの Individual Product 条件で定義されていない大文字で始まる用語は、本契約の本文で定められた意味を有します。Company が「X Marketing Partner プログラム」(以下「**TMP**」)に参加する範囲において、本 Exhibit C(Exhibit C-1 を含む)の以下の条項が適用されます:
### 1. X Marketing Partner Program。
X が Company の「Advanced」分類ステータスの申請を承認し、Company が Term 中にそのような分類ステータスを維持する場合、X は、独自かつ絶対的な裁量により、いつでも Company を TMP(または X が随時選択する他の後継プログラム名)の一部として認定することを選択できます。明確性のために、X は、Company が「Advanced」分類ステータスを達成または維持しているかにかかわらず、TMP に参加するように Company を選択する必要はありません。さらに、X は、独自かつ絶対的な裁量により、いつでも、Company への通知に基づき、いかなる理由でも、TMP への Company の参加を終了または停止することを選択できます。この場合、TMP への参加に関連する任意の便益を受ける Company の資格は、直ちに終了します(X からのそのような選択の追加通知なしに)。X Marks の Company の利用を規定する X Trademark Guidelines に加えて、Company は、TMP への参加に関連して X から提供される Badges(Exhibit C-1 に定義)の利用を規定する Exhibit C-1 に定める条項も遵守する必要があります。すべての Badges(Exhibit C-1 に定義)は、本契約に基づく X Marks とみなされます。
### 2. TMP 外での Badges の利用なし。
誤解を避けるため、Company が X により(独自かつ絶対的な裁量により)TMP のメンバーとして現在認定されていない場合、(i) Company は TMP への参加に関連する便益(Badges(Exhibit C-1 に定義)の利用を含みますが、これに限定されない)を受ける資格がなく、また (ii) Company は TMP に参加している、または TMP との関連があることを示唆することを禁止されます。
## Exhibit C-1: X Marketing Partner Program 条件
以下に定める X Marketing Partner Program 条件は、以下に記載または参照される連結条件を含み、参照によりここに組み込まれます(総称して「**TMP Partner Terms**」)。これは、「X Marketing Partner」プログラムへの参加を規定します。Company が X により、その独自かつ絶対的な裁量で、「X Marketing Partner」プログラムに参加する資格があると認定される範囲において、Company は、「X Marketing Partner」プログラムへの参加中、TMP Partner Terms の条項を常に遵守することに同意します。これらの TMP Partner Terms は、本契約の対象となり、本契約により規定されます。本 Exhibit C-1 で使用される大文字で始まる用語で、TMP Partner Terms 内で別途定義されていないものは、本契約で付与された意味を有します。
### 1. TMP プログラム。
X が Company を「X Marketing Partner」として認定したことの Company への通知に基づき、Partner は、[https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners) に記載されている「X Marketing Partner」プログラムのメンバーとなり、TMP バッジおよび TMP に関連して X が利用可能にする他の関連するマーク(総称して「**Badges**」)へのアクセスが与えられます。その利用は本契約の条項に従います。
### 2. X からのライセンス。
これらの TMP Partner Terms の条項に従い、Company が本契約を継続して遵守することを条件として、X はここに、Company に対し、TMP における「X Marketing Partner」としての Company の資格を宣伝することのみを目的として、Badges をコピーおよび表示するための、非独占的、ロイヤリティフリー、譲渡不可、サブライセンス不可、取消可能なライセンスを付与し、Company はこれを受け入れます。
### 3. 制限。
本契約への厳格な遵守は常に必要とされ、本契約に違反した Badges の利用は、Badges の Company の利用に関するライセンスを自動的に終了します。
**3.1** Company は、Badges の比率、色、フォントを変更すること、または Badges に要素を追加または削除することを含みますが、これらに限定されない、いかなる方法でも Badges を改変してはなりません。
**3.2** Company は、X によるスポンサーシップまたは推奨の誤った感覚を示唆する方法で Badges を利用してはなりません。
**3.3** Company は、X、その商品またはサービスを中傷する方法、または X の独自の裁量で、Badges における X の営業権を減少または損なう可能性のある方法で、Badges を利用してはなりません。
**3.4** Company は、TMP への Company の参加に関連する X の、または Company の商品および/またはサービス以外の商品またはサービスを指すために Badges を利用してはなりません。
**3.5** Badges は、それ自体で表示され、マークの各側面、およびその他の視覚的、グラフィック的、またはテキスト要素との間に合理的な間隔が必要です。
**3.6** Badges は、Badges 全体の可読性または表示を妨げる方法で提示または配置されるべきではありません。
**3.7** Company は、すべての Badges を [https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners)(または X が随時選択する他の後継 URL)にリンクするか、または Badges を表示する資料に次の帰属表示を表示する必要があります: 「『X Marketing Partner』プログラムバッジ、X、および X ロゴは、X Corp. またはその関連会社の商標です。」
### 4. プログラム要件。
Badges の利用はさらに、[X Trademark Guidelines](https://about.x.com/who-we-are/brand-toolkit)、および TMP への参加に関連して X から Company に伝達される他の要件(総称して「**TMP Program Requirements**」)の対象となり、常にこれらにより規定されます。Company は、TMP Program Requirements(参照によりここに組み込まれ、X への要求によりハードコピーで利用可能)に同意します。TMP Program Requirements は、ここに付与された Badges へのライセンスを拡張または延長するものではありません。Company は、X により明示的に承認された目的のためにのみ Badges を利用でき、Company の利用は (i) これらの TMP Partner Terms、および (ii) TMP Program Requirements の最新のバージョンに準拠する必要があります。これらの TMP Partner Terms と TMP Partner Requirements の間に矛盾または不一致がある場合、これらの TMP Partner Terms が優先します。
### 5. X へのライセンス。
Company はここに、X に、(i) TMP に関連して利用するために Company の商標を利用および表示すること、(ii) X の非商用、内部的な評価、テスト、および監査のために TMP に関連する Company の商品および/またはサービスを利用すること、(iii) TMP における「X Marketing Partner」としての Company の資格を X が強調できるようにするためのケーススタディまたはその他の資料を開発および公開すること(TMP に関連する Company の商品および/またはサービスを含みますが、これらに限定されない)、および (iv) TMP における「X Marketing Partner」としての Company の資格に関連する TMP に関連するマーケティング資料を作成すること(TMP に関連する Company の商品および/またはサービスを含みますが、これらに限定されない)のための、支払い済み、非独占的、世界的、サブライセンス可能なライセンスを付与します。
### 6. プログラム資格。
**6.1 プログラム資格。** X は、随時、TMP における Company のメンバーシップをレビューし、X の独自かつ絶対的な裁量で、Company を任意の特定のコンピテンシーおよび/または TMP 全体から再認定または資格取消しする権利を留保します。
**6.2 Company の商品またはサービスへの変更。** Company が TMP に関連する Company の商品および/またはサービスに重大な変更を加える計画がある場合、Company は、そのような変更のリリース前に、Company の更新された商品またはサービスをレビューして、TMP の資格を引き続き満たすかどうかを判断するために、X に少なくとも 30 暦日を提供します。更新された商品またはサービスは、Badges のさらなる利用の前に X によって再認定される必要があります。X は、新しいコンピテンシーの認定を求める Company の要求に対応するために、商業的に合理的な努力を行います。Company が、自発的または非自発的、および/または法律の運用により、第三者との、全部または一部の合併、買収、その他の支配権の変更(合併、買収、または資産売却の場合を含みますが、譲渡当事者が存続または消滅法人であるかにかかわらず、これらに限定されない)を受ける場合、Company は、Badges のさらなる利用の前に、TMP に関連する Company のすべての商品および/またはサービスを、X による再認定のために X に提出する必要があります。
### 7. 停止および終了。
X は、その独自の裁量により、いつでも、いかなる理由でも、Company への通知の提供により、これらの TMP Partner Terms、ここに Company に付与された権利、および/または TMP への Company の参加を直ちに終了または停止することができます。Company は、X への 90 暦日の通知を提供することにより、TMP への Company の参加を終了することができます。これらの TMP Terms の終了および/または TMP への Company の参加の終了時、ここに付与されたすべてのライセンスは直ちに失効し、Company はすべての Badges の利用を停止する必要があります。いずれの当事者も、本契約に基づき許可された TMP Partner Terms のこれらの終了のみから生じる損害について、相互に責任を負いません。
### 8. 変更。
X は、その独自の裁量により、これらの TMP Partner Terms および/または Badges の条項をいつでも変更する権利、および Badges の未承認または非準拠の利用に対して適切な措置を講じる権利を留保します。Badges の利用に関する質問がある場合は、支援のために [trademarks@x.com](mailto:trademarks@x.com) までご連絡いただくか、次にお手紙をお送りください: X Corp., Attention: Legal Department, 865 FM 1209, Building 2, Bastrop, TX 78602, USA。
# X 開発者契約
Source: https://docs.x.com/ja/developer-terms/agreement
X 開発者契約は、ライセンス、制限、コンプライアンス義務を含め、X API と開発者プラットフォームを利用するための法的条件を定めています。
最終更新日: 2026 年 4 月 27 日
「Accept & Subscribe」をクリックすること、Paid Services の定期購読料の支払いを継続すること、または Licensed Material にアクセスもしくは利用することにより、あなたは本契約の条件に同意するものとします。サブスクリプションは、以下に記載のとおりキャンセルされるまで自動更新されます。サブスクリプションには確認済みの電話番号が必要です。他のプラットフォーム経由でサブスクリプションを申し込んだ場合は、そのプラットフォームを通じてサブスクリプションを管理してください。
本 X 開発者契約(以下「**本契約**」)は、あなた(本契約において「**あなた**」と呼びます)と X との間の拘束力のある法的合意であり、Paid Services(以下に定義)を含む Licensed Material(以下に定義)へのアクセスおよび利用を規定します。
Licensed Material(以下に定義)にアクセスまたは利用すること、本契約の条件を承諾するボタンをクリックすること、または Paid Services の定期購読料の支払いをすることにより、あなたは本契約の条件に拘束されることに同意します。本契約の条件を理解していない、またはその一部を承諾しない場合、Licensed Material を利用またはアクセスすることはできません。X との拘束力ある契約を締結できる法定年齢に達していない場合、または適用される法律により Licensed Material の利用もしくは受領を禁じられている場合、Licensed Material を利用すること、または本契約を承諾することはできません。Paid Service を購入して利用するには、次のいずれかに該当する必要があります: (i) 18 歳以上であるか、居住する法域の法律で定められた成年年齢以上であること、(ii) その Paid Service を購入して利用することについて親または保護者の明示的な同意があること。あなたが親または法定後見人であり、自分の子供(または後見の対象である子供)が Paid Service を購入または利用することを許可する場合、あなたは本契約の条件があなたに適用されることに同意し、本契約を遵守し、Paid Services における子供の活動および子供が本契約の条件を遵守することについて責任を負います。いずれの場合も、[**X 利用規約**](https://x.com/tos) の Who May Use the Services セクションに記載されているとおり、X 利用規約で定義される「Services」を利用するには少なくとも 13 歳以上である必要があります。企業、組織、政府、その他の法人を代表して本契約を承諾する場合、または Licensed Material を利用する場合、あなたはその企業、組織、政府、その他の法人を本契約に拘束する権限を有することを表明・保証するものとし、この場合、本契約で使用される「あなた」および「あなたの」という文言はそのような法人を意味します。本契約の条件に同意しない場合、あなた(およびあなたの人員)は Licensed Material にアクセスしたり利用したりすることはできません。\*\*\*\*
**I. 定義。**
本契約において、以下の定義が適用されます:
1. 「**Developer Site**」とは、[**https://developer.x.com/**](https://developer.x.com/) にある X の開発者サイトを意味します。
2. 「**ダイレクトメッセージ**」とは、X アプリケーション上で、あるユーザーが X のダイレクトメッセージ機能を使用して他の特定のユーザーに送信するプライベートメッセージを意味します。
3. 「**知的財産権**」とは、著作権、著作者人格権、特許権、商標権、およびその他の知的財産権または類似の権利(登録の有無を問わず)を、世界中で意味します。
4. 「**Licensed Material**」とは、単独または集合的に、X API および X コンテンツを意味します。
5. 「**Paid Service(s)**」とは、あなたが定期的な料金の支払いと引き換えにアクセスする Licensed Material の機能や機能性であって、該当する機能や機能性および本契約に該当するものを意味します。本契約で別途定めがない限り、「Licensed Material」への言及はすべて Paid Service(s) を含むものと解釈されます。
6. 「**Payment Portal**」とは、あなたが Licensed Material の利用にオプトインし、Paid Services のサブスクリプションを管理し、Paid Services の支払い方法を管理し、アカウント情報を更新するために提供されるオンラインポータルを意味します。
7. 「**Services**」とは、X コンテンツを表示するか、Licensed Material をその他の方法で利用するあなたのサービス、ウェブサイト、アプリケーション、その他の提供物(調査を含む)を意味します。
8. 「**投稿**」とは、X アプリケーションを介して配信される短形式のテキストおよびマルチメディアベースのメッセージを意味します。
9. 「**X**」とは、(a) あなたの主要な事業所在地が欧州連合、EFTA 加盟国、および英国以外にある場合は、X Corp.(865 FM 1209, Building 2, Bastrop, TX 78602, USA)、または (b) あなたの主要な事業所在地が欧州連合、EFTA 加盟国、または英国内にある場合は、X Internet Unlimited Company(One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland)を意味します。
10. 「**X API**」とは、X のアプリケーションプログラミングインターフェース(それぞれを「**API**」)、ソフトウェア開発キット(それぞれを「**SDK**」)、および Developer Site を通じて X が提供する関連ツール、ドキュメンテーション、データ、テクノロジー、コード、その他の資料を意味します。
11. 「**X アプリケーション**」とは、一般に「X」として知られている X のリアルタイム情報サービスを意味し、X が現在ウェブサイトおよび X が所有・運営・管理するモバイルアプリケーション、ソーシャルプラグイン、およびアプリケーションプログラミングインターフェースにおいて提供するサービスを含みます。
12. 「**X コンテンツ**」とは、投稿、各投稿に対して生成される一意の識別番号、X エンドユーザーのプロフィール情報、および X API またはその他の X によって承認された手段を通じてあなたに提供される他のデータおよび情報、ならびにそれらのコピーおよび派生物を意味します。
13. 「**X マーク**」とは、Developer Site を含め、本契約に従って利用するためだけに X があなたに提供する X の名称、商標、およびロゴを意味します。
14. 「**ユーザー**」とは、あなたの Services の訪問者、ユーザー、または顧客を意味します。
**II. X API および X コンテンツ。**
**A. X からのライセンス。** 本契約および該当する Incorporated Developer Terms(以下に定義)の条件を遵守することを条件として、X はここに、以下の目的にのみ限定した、非独占的、ロイヤリティフリー、譲渡不可、サブライセンス不可、かつ取消可能なライセンスをあなたに付与します:
1. X から明示的に承認された範囲で、X API を使用して X コンテンツを Services に統合するか、X コンテンツの分析を実施すること;
2. 本契約で許可される範囲で、Services を通じてユーザーに X コンテンツを合理的な量だけコピー・表示すること;
3. Services 上での表示のために書式を整える目的でのみ X コンテンツを変更すること;および
4. 本契約に定めるところに従い、X アプリケーションを X コンテンツの出典として帰属表示するために X マークを利用し表示すること。
**B. X へのライセンス。** あなたはここに、[**埋め込み投稿**](https://developer.x.com/docs/twitter-for-websites/embedded-tweets/overview) または [**埋め込みタイムライン**](https://developer.x.com/docs/twitter-for-websites/timelines/overview) を使用して X コンテンツを表示するあらゆるウェブページまたはアプリケーションに、ウェブスパイダーおよび/またはクローラーを含む任意の手段でアクセスし、インデックス化し、キャッシュするための、非独占的、ロイヤリティフリー、譲渡不可、かつサブライセンス不可の取消可能なライセンスを X に付与します。
**C. 組み込まれた条件。** Licensed Material へのアクセスおよび利用は、以下の追加の条件およびポリシー(総称して「**Incorporated Developer Terms**」)にも従い、これに準拠する必要があります:
1. [**X 開発者ポリシー**](/developer-terms/policy);
2. [\*\* API 制限された利用ルール\*\*](/developer-terms/restricted-use-cases);
3. [**X ルール**](https://help.x.com/rules-and-policies/x-rules);
4. X コンテンツの表示に関しては、[**表示要件**](https://developer.x.com/developer-terms/display-requirements.html);
5. X マークの利用および表示に関しては、[**X ブランドガイドライン**](https://about.x.com/who-we-are/brand-toolkit);および
6. あなたのアカウントで自動化されたアクションを行うことに関しては、[**Automation Rules**](https://help.x.com/rules-and-policies/x-automation)。
**III. 利用に関する制限。**
**A. リバースエンジニアリングおよびその他の制限。** あなたは、以下を行わず、また試みず(他者による行為も許可しません): (a) X API をリバースエンジニアリング、逆コンパイル、逆アセンブル、または翻訳することや、X API またはその一部に含まれるかまたはその基礎となるソースコード、営業秘密、ノウハウを導き出そうとすること;(b) X API の機能または機能性、あるいは X API の監視メカニズムに干渉、変更、混乱、無効化を行うこと;(c) Licensed Material を利用またはアクセスして、X アプリケーションの代替または類似のサービスや商品を作成しようとすること、または作成すること;(d) 本契約で明示的に許可される場合を除き、Licensed Material の全部または一部を第三者に販売、賃貸、リース、サブライセンス、配布、再配布、シンジケート、派生物の作成、譲渡、その他の移転、またはアクセス提供すること;(e) X API をサービスビューロー、レンタル、またはマネージドサービスとして提供すること、または他の個人もしくは事業体に、X API へのリンクを作成させたり、他のサーバー、ワイヤレスもしくはインターネットベースのデバイス上で X API を「フレーム」または「ミラー」させたり、その他の方法で X API へのトークン、キー、パスワード、その他のログイン認証情報を第三者に利用可能にすること;(f) Licensed Material を違法、非承認、その他不適切な目的で利用すること;(g) Licensed Material を利用して個々の X ユーザーの非公開情報を導き出したり取得したりすること;(h) X アプリケーション、X API、またはその中に含まれる X コンテンツの完全性やパフォーマンスに干渉または妨害すること;(i) X コンテンツから専有的な注記やマークを削除または改変すること;(j) X アプリケーション、X API、X コンテンツ、または関連するシステムやネットワークへの不正アクセスを試みること;(k) 基盤モデルまたはフロンティアモデルをファインチューニングまたはトレーニングするために X API または X コンテンツを利用すること;または (l) X アプリケーションの外部でユーザーを広告のターゲットにする、または広告を配信する目的で、X コンテンツを単独または第三者のデータと組み合わせて利用したり、そこから派生する分析を利用したりすること。
**B. 商用利用の制限。** Services が「非商用」に指定されている場合、Licensed Material を Commercial Use(以下に定義)してはなりません。Commercial Use の制限は、公式に登録された非営利団体または NGO には適用されない場合があります。「**Commercial Use**」とは、Licensed Material の任意の利用または X API へのアクセスであって、(a) 事業(すなわち、商品またはサービスを通じて収益を得ることを主目的とする事業体)によって、または事業のために行われるもの、あるいは (b) 収益化される商品またはサービスの一部として(たとえば、ウェブサイト広告、ライセンス料、アプリ内プロモーション、スポンサーシップなど)行われるものを意味します。
**C. 監視または計測なし。** これに反する定めにかかわらず、以下の情報は、非商用の内部目的(たとえば、Services の機能性を改善するため)にのみ使用できます: (a) X アプリケーションの集計ユーザーメトリクス(X アプリケーションのアクティブユーザーまたはアカウント数など);(b) X アプリケーションのレスポンス性;および (c) X API のパフォーマンスに関して分析、利用、または関連することから導き出された結果、利用統計、データ、その他の情報(集計または個別)。そのようなすべての情報は、Confidential Information(以下に定義)です。
**D. レート制限。** あなたは、X API のアクセス、コール、および利用に関する制限(「**レート制限**」)を超えたり回避したりしようとはせず、または合理的なリクエスト量を超え、過剰または濫用的な利用を構成する方法、あるいは本契約に準拠しない方法で X API を利用してはなりません。あなたがレート制限、X API の利用を制限するための管理策、または本契約の条件を超えたり回避しようとしたと X が合理的に判断した場合、Licensed Material を利用する能力が一時的に停止されるか、恒久的にブロックされる可能性があります。X は、Licensed Material および X アプリケーションを改善するため、また本契約および Incorporated Developer Terms へのあなたの準拠を確保するために、X API の利用状況を監視することがあります。
**E. 位置情報データ。** あなたは、また他者にも、X コンテンツに含まれる位置情報データおよびその他の地理情報を、それが付随する X コンテンツと連動する場合を除き、集約、キャッシュ、または保存させてはなりません。位置情報データおよび地理情報は、X コンテンツによってタグ付けされた場所を識別するためにのみ利用できます。
**F. X マークの利用。** X マークをあなたの登録企業名、ロゴ、またはサービス名や商品名に含めてはなりません。X マークの派生物を作成したり、X との推奨、支援、または関連を作り出し、または合理的に示唆する形で X マークを利用したりしてはなりません。X マークのすべての利用およびその利用から生じるすべての信用は、X の利益に帰属します。Licensed Material から専有的な注記や X マークを削除または改変してはなりません。
**G. セキュリティ。** あなたは X API のセキュリティを維持し、X API へのトークン、キー、パスワード、その他のログイン認証情報を第三者に利用可能にしてはなりません。ウイルス、ワーム、その他の有害なコードや資料によるアクセスを含め、X API の機能や機能性への不正アクセスや利用を防ぐために業界標準のセキュリティ対策を利用します。X コンテンツについては、業界標準の組織的および技術的な保護策を用いて機密性を保ち、不正アクセスから安全に守るとともに、同種のデータを保管する際に用いる注意と少なくとも同等以上の注意をもって扱うものとします。Licensed Material に関するセキュリティの侵害または潜在的な脆弱性を知った場合または疑った場合、直ちに X に通知し、調査に協力し、必要な通知の支援を行い、X から合理的に要求される情報を提供します。Licensed Material へのあなたのアクセスから生じるそのような侵害または潜在的な脆弱性を速やかに是正します。
**H. デジタルサービス法。** 本契約における反対の定めにかかわらず、デジタルサービス法(規則 (EU) 2022/2065)(以下「DSA」)第 40 条に記載された手続きに従って Licensed Material へのアクセスを提供される場合、Licensed Material のアクセスおよび利用は、欧州連合内の体系的なリスクの検出、識別、および理解に貢献する研究を行うことのみに、および DSA に基づく X の義務を遵守するために必要な範囲内でのみ制限されます。Licensed Material のそのような利用は、本契約第 III(B) 節に記載されているとおり非商用です。X API を通じて取得した Licensed Material(その派生物を含む)を、承認された申請内で指定された者以外の個人または団体に開示、複製、ライセンス供与、またはその他の方法で配布してはなりません。ただし、(i) 情報が第 40 条に記載された「認定研究者」の地位および手続きに従って Digital Services Coordinator または DSA によって具体的に許可された他の当事者に開示される場合、または (ii) 法律により開示が要求される場合は除きます。
**I. トークン。** X は、X アプリケーション上の機能または機能性へのアクセスや利用を可能にするトークンを含め、あなたに提供するトークンの数を制限することがあります。
**J. アクセスティア。** X は、Licensed Material に対して異なるアクセスティア([developer.x.com](http://developer.x.com) に記載)を提供しており、あなたはご自身の利用ケースに最も適したティアに加入するものとします。X は、随時 Licensed Materials の利用状況をレビューし、Enterprise アクセス([developer.x.com](http://developer.x.com) に記載)の申請を含め、加入しているアクセスティアの変更を要求することができます。
**K. I-Framing の禁止:** いかなる状況においても、Licensed Material、X コンテンツ、X API、X アプリケーションの要素を、あなたの Services または他のプラットフォーム上で、iframe、インラインフレーム、または類似の埋め込みメカニズム内に埋め込んだり、表示したり、その他の方法で組み込んだりしてはなりません。この禁止は絶対的であり、表示、統合、または再配布のために X コンテンツをフレームで囲む試みを含みますが、これに限定されません。この条項への違反は、第 VII.I 節に記載されているとおり、開発者契約および Licensed Material(X API、X Data License、Developer Console など)へのアクセスの即時終了につながる可能性があります。
**L. セルフサーブでの利用。** Pay-Per-Use、Basic、および Pro プラン([developer.x.com](https://developer.x.com) に記載)は、趣味の開発者、商用プロトタイピング、初期開発、初期段階の X プロダクト統合、および限られた数のエンドユーザーをサポートするアプリケーションを対象として設計されています。この範囲を超えて X API を利用する場合、Enterprise プラン([developer.x.com](https://developer.x.com) に記載)に申請(または既に加入)する必要があります。
**M. 商用利用:** 趣味のプロジェクト、商用プロトタイピング、初期開発、初期段階の X プロダクト統合、または限られた数のエンドユーザーを対象としたアプリケーションの範囲を超えて X API を利用する場合、Enterprise プラン(developer.x.com に記載)に申請(または既に加入)する必要があります。
**IV. 更新および削除。**
**A. 更新。** X は、Licensed Material のいかなる機能や機能性も、全部または一部を随時更新、変更、または中止することがあります(それぞれを「**Update**」といいます)。あなたは Licensed Material の最新バージョンを実装・利用し、Update の結果として必要となる Services への変更を、自己の負担で行うものとします。Update は、Services が X API にアクセスまたは通信する方法、あるいは X コンテンツを表示する方法に悪影響を与えることがあります。X は、Update の結果として生じるいかなる損害についても責任を負いません。
**B. 削除。** X コンテンツが削除、保護されたステータスの取得、またはその他の方法で X アプリケーションから停止、差し止め、変更、または削除された場合(位置情報の削除を含む)、あなたは、X または該当する X ユーザーの書面による要求から可能な限り速やかに、いかなる場合でも 24 時間以内に、その X コンテンツを削除または変更(該当する場合)するあらゆる合理的な努力を行うものとします。ただし、法律または規制によって禁止されておらず、かつ X の明示的な書面による許可がある場合を除きます。
**V. 所有権、ベータ、およびフィードバック。**
**A. 所有権。** 本契約で明示的に別途規定されている範囲を除き、いずれの当事者も、他方当事者が所有またはライセンスを受ける知的財産権について、いかなる権利、権原、または利益も取得しないものとします。Licensed Material はライセンスされるものであり、販売されるものではなく、X(または該当する場合はそのライセンサーまたは X アプリケーションのユーザー)は、本契約で明示的に付与されていないすべての知的財産権を含むすべての権利を保持し留保します。あなたは、X の所有権と矛盾するいかなる行為も行いません。これには、X の X マークの所有権への異議申立、本契約で付与されたライセンスの有効性への異議申立、または本契約で具体的に承認された場合を除いて X マークをコピーまたは利用することが含まれますが、これに限定されません。あなたが法律の運用またはその他の方法により X マークまたは混同を招くほど類似したマークに関する何らかの権利を取得した場合、X に費用をかけず直ちにそれらの権利を X に譲渡します。
**B. ベータ。** X は、随時、一般に利用可能となっていないアルファ、ベータ、リサーチスタディ、パイロット、マーケティングサービス、その他のプログラム(それぞれ「**Beta**」)への早期アクセスを提供することがあります。Beta は Confidential Information とみなされます。Beta への参加は自己責任で行われ、追加の要件の対象となる場合があり、既存または将来のプログラム、商品、および/またはツールの調査、分析、検証において X を支援する場合があります。
**C. フィードバック。** X は、X、Licensed Material、Beta、または X の他の商品もしくはサービスに関してあなたが X に提供するフィードバック、コメント、または提案(以下「**Feedback**」)を、あなたまたは第三者に対する報酬または義務なしに、いかなる方法でも自由に利用できます。Feedback は Confidential Information とみなされます。あなたはここに、Feedback に関するすべての権利、権原、および利益を X に不可逆的に譲渡します。
**VI. 秘密保持。**
あなたは、Licensed Material に関連する非公開情報、ソフトウェア、および仕様(以下「**Confidential Information**」)にアクセスを付与される場合があります。あなたは、本契約に基づく権利の行使のために必要な範囲でのみ Confidential Information を利用できます。X の事前の書面による同意なしに、Confidential Information を第三者に開示してはなりません。Confidential Information を不正な利用、アクセス、または開示から、同種の自己の秘密情報を保護するために利用するのと同じ方法で、いかなる場合でも合理的な注意より低くない注意をもって保護します。
**VII. 期間、サブスクリプション料金、支払い、停止、および終了。**
**A. 期間。** 本契約の期間は、(i) 本契約の条件を承諾した日、または (ii) Licensed Material のいずれかへのアクセスもしくは利用を開始した日のいずれか早い方から開始し、以下に記載されているとおり早期に終了しない限り、Licensed Material のアクセスおよび利用を停止するまで継続します。
**B. サブスクリプション条件。** Licensed Material の一部として提供される Paid Services は、Developer Site および Payment Portal に記載されているとおり、特定の機能、便益、またはサービスへのアクセスを提供する定期購読サービスとして利用可能となります。Paid Service を購入する場合、以下に記載する支払い条件に従って、月ごとにサブスクリプション料金を前払いで支払うものとします。Payment Portal を介して Paid Service にアクセスするためにサブスクリプションを申し込む場合、あなたは、該当する Paid Service があなたまたは X によってキャンセルされるか、または本契約が別途終了するまで、選択した支払い方法で定期的な支払いを承認することに明示的に同意します。Paid Service のサブスクリプションは、本契約に従ってキャンセルされるまで、毎月自動的に更新されます。あなたの支払い情報は、Paid Service に該当する各サブスクリプション期間の開始時に、Payment Processor(以下に定義)によって自動的に処理されます。支払い情報が拒否された場合、該当する Paid Service に対して新しい支払い情報を提供するまで、サブスクリプションがキャンセルされる場合があります。新しい支払い情報を提供し、支払いアカウントが正常に請求された場合、新しいサブスクリプション期間は、正常な請求が行われた日ではなく、元の更新日に基づきます。Paid Services の価格は随時変更されることがあります。X は、Paid Services の価格に対する重大な変更について合理的な事前通知を提供します。この通知は Developer Site を介して提供される場合があります。サブスクリプション料金については、価格変更は価格変更日以降の次のサブスクリプション期間の開始時に有効となります。価格変更に同意しない場合、価格変更が有効となる前に該当する Paid Service のサブスクリプションをキャンセルすることによって、変更を拒否する権利があります。
**C. 支払い条件。** X は、Paid Service、デバイス、オペレーティングシステム、地理的な場所、その他の要因によって異なる支払いオプションを提供することがあり、これらは随時更新される場合があります。これらの支払いオプションには、第三者の支払処理業者(以下「**Payment Processor**」)を利用したウェブ支払いが含まれることがあります。Paid Service にアクセスする際、あなたは以下に同意します: (i) 該当するサブスクリプション期間中、税金、追加料金、クレジットカード手数料、銀行手数料、外貨取引手数料、外国為替手数料、通貨変動に関連する追加金額とともに、Paid Service に対する記載された価格を定期的に支払うこと;および (ii) 特定の支払い方法の利用に関して Payment Processor によって課される該当する利用規約、プライバシーポリシー、その他の法的合意または制限(追加の年齢制限を含む)を遵守すること。Developer Site で Paid Service をキャンセルしない限り、サブスクリプション料金は該当するサブスクリプション期間の更新期間の開始時に自動的に適用されます。銀行、クレジットカード、デビットカード、および/または他の支払い情報が常に最新、完全、正確であることを確認することは、あなたの責任です。Payment Processor を介して Paid Service の支払いを行う場合、X は、いつ支払いが行われたか、サブスクリプションが期限切れまたは自動更新される予定日、購入したプラットフォーム、その他の情報など、あなたの取引に関する情報を受け取ることがあります。X は、Payment Processor、あなたの銀行、あなたのクレジットカード会社、または任意の支払いネットワークによる誤りまたは遅延について責任を負いません。X への支払いはすべて、本契約で別途明示的に規定されている場合、または法律で要求されている場合を除き、返金不可能です。
**D. 税金および料金。** すべての料金は、現在有効な、または将来施行または課される、取引、Licensed Material の提供、または X コンテンツの提供に対する税金および類似の料金を除外しています。これには、売上税、使用税、または付加価値税、商品サービス税、消費税、関税、料金、または類似の料金が含まれます。これらの税金には、VAT、GST、売上税、源泉徴収税、その他該当する税金が含まれる場合がありますが、X の純利益のみに基づく税金は除外されます。あなたは、そのような税金、関税、および料金のすべての支払い、および当該金額の支払いから生じる関連する罰金や利息に責任を負います。加えて、特定の法域で X が負担するデジタルサービス税(「DST」)または類似の法域固有の税金や規制料金に関連するコストを回収するために、追加料金が請求される場合があります。この追加料金は、該当する場合、請求書に別項目として表示され、X の独自の裁量で決定される該当する料金の割合として計算されます。X は、税率もしくは料率の増加、または関連する管理コストに対応して、事前の通知なしにいつでもこの追加料金を調整することがあります。あなたの所在地によっては、X は Paid Services の購入から生じる取引税に関連する情報の収集および報告に責任を負う場合があります。あなたは、X が税金の徴収および報告義務を果たすために、あなたのアカウントおよび個人情報を関連する税務当局に提供することを許可します。
**E. Paid Services のサブスクリプションのキャンセル。** Paid Services のサブスクリプションは、現在のサブスクリプション期間の終了の少なくとも 24 時間前にサブスクリプションをキャンセルしない限り、毎月自動的に更新されます。特定の機能、便益、および/またはサービスが変更または中止された状況を含め、部分的なサブスクリプション期間について返金またはクレジットは提供されません。サブスクリプションプランは前払いで、返金不可(法律で要求される場合を除く)であり、本規定のキャンセル手続きに従ってサブスクリプションがキャンセルされない限り、各サブスクリプション期間の終了時に自動的に更新されます。Developer Site を介していつでも Paid Services のサブスクリプションをキャンセルすることができ、その時点でのサブスクリプション期間の終了時に、Paid Services(またはその機能や機能性)へのアクセスが失われます。Paid Services をキャンセルすると、サブスクリプションはキャンセルした時点から現在のサブスクリプション期間の終了まで有効なままです。法律で要求される場合を除き、現在のサブスクリプション期間の残り日数について返金またはクレジットを受け取ることはありません。Paid Services のすべての支払いは最終的であり、適用される法律で要求される場合を除き、返金または交換はできません。X は、Paid Service の性質、品質、または価値、あるいはその可用性または供給について保証しません。未使用または部分的に使用された Paid Service(たとえば、部分的に使用されたサブスクリプション期間)については、返金またはクレジットは提供されません。**すべての取引は最終的です**。ただし、以下に記載されているとおり、法律により撤回する権利がある場合を除きます\*\*。\*\*
1. **EU または UK に居住するユーザーの撤回権および返金。** サブスクリプションで Paid Services を購入する場合、あなたはサブスクリプションベースで購入することに明示的に同意し、購入日から即座にサブスクリプションが開始することに同意します。EU 加盟国または英国の消費者である場合、購入から 14 日以内であれば、いかなる理由でも購入契約から撤回できることに同意します。
2. **台湾に居住するユーザーには撤回権がありません。** Paid Services を購入すると、サブスクリプションベースで購入し、購入日から即座にサブスクリプションが開始し、Paid Service は開始時点で完全に履行されます。台湾の消費者である場合、上記 VII.E 節に従って Paid Services のサブスクリプションをキャンセルできることに同意しますが、それ以外にサブスクリプションを撤回する権利はなく、返金は行われません。
**F. Paid Services は X アカウント間で譲渡不可。** Paid Service の各購入は単一の X アカウントに適用されます。つまり、購入は Paid Service を購入した際に使用していたアカウントのみに適用され、アクセスまたは管理する他のアカウントには適用されません。複数のアカウントを保有または管理し、各アカウントで Paid Services へのアクセスを望む場合、各アカウントで個別に Paid Service を購入する必要があります。他者があなたの X アカウントを使用して、その人が注文していない Licensed Material にアクセスすることを許可してはなりません。米国財務省の外国資産管理局が管理する制裁を含む経済制裁、または他の該当する制裁当局によって、米国人が取引することを許可されない者(「**Prohibited Person**」)である場合、Paid Service を購入したり、Licensed Material を利用したりしてはなりません。これには、次の国および地域に居住する、国民である、または通常居住する者が含まれますが、これに限定されません: キューバ、イラン、ウクライナのクリミア地域、北朝鮮、シリア。あなたは、Prohibited Person ではないことを表明・保証します。
**G. 制限および義務。** Licensed Material を自国で合法的に利用でき、該当する Paid Service または Licensed Material について X がサポートする国に居住している場合にのみ、Paid Service を購入・利用し、Licensed Material を利用することができます。X は、独自の裁量で、特定の国での Licensed Material へのアクセスまたは Paid Service の購入能力を制限することがあります。X は、サポートする国のリストを随時変更する権利を留保します。X は、Paid Services の取引を拒否したり、Paid Service または Licensed Material の販売または利用をキャンセルまたは中止したりする権利を、独自の裁量で留保します。
**H. 停止。** X は、通知なしに直ちに Licensed Material へのアクセスおよび利用を停止することがあります。 (a) X が合理的に以下を判断する場合:(i) あなたによる Licensed Material の利用が Licensed Material に損害を与えるか、過度の負担を与える;(ii) 本契約に違反した;(iii) X に対してリスクまたは可能性のある法的責任を生じさせる;(iv) X によるあなたへの Licensed Material の提供が、商業的にもはや実行可能でない;(b) 長期間の非活動;(c) 管轄権のある裁判所、規制当局、または法執行機関から要求または指示された場合;または (d) Paid Services の支払いを怠った場合。X は、そのような停止の結果として生じるいかなる損害についても責任を負いません。
**I. 終了。** X は、独自の裁量でいかなる理由でも本契約を終了することがあります。そのような早期終了があなたによる本契約違反の結果である場合を除き、X によるそのような早期終了は、現在のサブスクリプション期間の終了時に有効となります。あなたが本契約の条件に違反した場合、X は理由あってあなたへの通知後直ちに本契約を終了することができ、あなたは Paid Services に対する日割り返金を受け取ることはありません。Developer Site で Paid Services のサブスクリプションまたは Licensed Material の利用をキャンセルできます。本契約の終了時: (a) 本契約で付与されたすべてのライセンスは直ちに失効し、あなたはあらゆる Licensed Material の利用を停止する必要があります;および (b) あなたが所持するあらゆる形式および種類のメディア上のすべての Licensed Material およびそのコピーを恒久的に削除する必要があります。X の要求に応じて、いかなる理由でも、速やかに(いかなる場合もそのような要求から 10 営業日以内に)、本節の前述の (b) の規定への準拠の証拠(例: 削除確認のスクリーンショット)を提供します。本契約の当事者は、本契約で許可される本契約の終了のみから生じるいかなる損害についても、相互に責任を負いません。
**VIII. コンプライアンス監査。**
X または相互に合意した第三者の代理人(秘密保持義務を負う)は、本契約の履行に関連するあなたの管理下または所持下にある記録を、合理的な事前通知に基づき、通常営業時間内の合理的な時間に、監査に先行する 2 年間の本契約の遵守および X に支払われる料金の検証を目的として、検査および監査する権利を有します。X は、不遵守の合理的な理由がない限り、12 か月ごとに 1 回を超えて監査権を行使しないものとし、その監査はあなたの事業活動を不合理に妨げないものとします。あなたはそのような監査に十分な協力と支援を提供し、所持するすべての Licensed Material、該当する契約、および記録へのアクセスを提供します。前述の一般性を制限することなく、監査の一部として、X は、あなたの現在の Licensed Material の展開状況をリストした、権限のある代表者によって署名された書面による報告書を要求し、あなたはこれを提供することに同意します。監査の完了後 30 営業日以内に、そのような監査によって明らかになった不足額を X に支払います。加えて、そのような監査があなたによる 5% 以上の不足支払いを明らかにした場合、そのような監査の合理的な費用も X に払い戻します。本節の要件は、本契約の終了後 1 年間存続します。
**IX. 免責。**
適用される法律で許容される最大限の範囲において、Licensed Material は「現状のまま」「所在のまま」、すべての欠陥とともにあなたに提供され、X は、明示、黙示、法定、その他を問わず、商品性、非侵害、特定目的への適合性、および本契約、取引の過程、または商慣行から生じる保証または条件を含む、あらゆる保証を否認します。X は、Licensed Material、または本契約に基づき提供される他の X 商品もしくはサービスがあなたのいかなる要件も満たすこと、あるいはそのような Licensed Material または他の商品もしくはサービスの利用がエラーフリー、中断なし、ウイルスなし、または安全であることを保証しません。あなたは、Licensed Material の利用および提供するコンテンツについて責任を負います。この保証否認は、一部の法域では有効でない場合があり、法律に基づき放棄または否認できない保証権をあなたが有する場合があります。
**さらに、あなたは、Paid Services が「現状のまま」および「利用可能な範囲」で提供されることを理解し同意します。**
**X. 補償。**
あなたは、(a) 本契約と矛盾する方法での Licensed Material の利用、または (b) あなたの Services のパフォーマンス、プロモーション、販売、配布から生じる範囲で、第三者による X に対するあらゆる手続、要求、請求、訴訟(製造物責任請求を含みますが、これに限定されません)に対して、自己の費用で X を防御し、あらゆる責任、損害、費用(合理的な弁護士費用を含みますが、これに限定されません)から X を補償します。X が本節に基づく補償または防御をあなたに求める場合、X は、補償または防御を求める X に対して提起された請求について、速やかにあなたに書面で通知します。X は、自らが選定する弁護士による請求の防御の完全な支配を引き受けることができます。X の権利に影響を及ぼす、X による過失の認定を構成する、またはいかなる方法でも X を拘束する第三者との契約を、X の事前の書面による同意なしに締結してはなりません。X がそのような請求の防御の支配を引き受けた場合、X はあなたの事前の書面による承認なしに、あなたからの支払いを必要とするそのような請求を和解させません。
**XI. 責任の制限。**
いかなる場合でも、X は、あなたまたはユーザーに対して、間接、特別、付随的、模範的、懲罰的、または結果的損害、あるいは本契約に起因または関連する使用、データ、事業、営業権、または利益の損失または損害について責任を負いません。いかなる場合も、本契約に基づくあらゆる請求に対する X の総合的な責任は 50 米ドル (\$50.00) を超えないものとします。前述の制限、除外、および免責は、そのような責任が契約、保証、不法行為、厳格責任その他に基づく請求に起因するかどうか、および X がそのような損失または損害の可能性について通知されたかどうかにかかわらず適用されます。適用される法律が本規定の責任のいかなる制限も禁止している場合、当事者は、その制限が適用される法律に適合するように修正されたとみなされることに同意します。当事者は、本規定に定める責任の制限が合意されたリスクの配分であり、いかなる限定的救済策の本質的目的の失敗にもかかわらず適用されることに同意します。
**XII. 契約の更新。**
X は、本契約または Incorporated Developer Terms を随時更新または修正することがあります。あなたは、定期的に Developer Site で更新を確認します。X は、これらのサイトで更新された条件を掲示すること、サービス通知を介して、または他の適切な手段(たとえば、アカウントに関連付けられたメールアドレスへのメール)により、これらの条件への重大な修正について通知します。変更は遡及的ではなく、Developer Site で利用可能な本契約の最新バージョンが、Licensed Material へのあなたのアクセスおよび利用、および対応する取引を規定します。Licensed Material への継続的なアクセスまたは利用は、そのような更新および修正への拘束力ある承諾を構成します。
**XIII. 紛争解決および集団訴訟の放棄。**
**A. 本節は、あなたが欧州連合、EFTA 加盟国、または英国以外に居住している場合(米国に居住している場合を含む)にのみ適用されます。この節を注意深くお読みください。あなたの法的権利、特に裁判所に訴訟を提起する権利に重大な影響を与える可能性があります。**
1. **準拠法および裁判管轄地の選択。** テキサス州法(その抵触法規定を除く)は、当事者間の反対の合意にかかわらず、本契約およびあなたと X との間で生じるいかなる紛争にも適用されます。本契約に関連するすべての紛争、本契約に起因もしくは関連する紛争、請求、または論争、Licensed Material のマーケティング、および/または Licensed Material への参加は、テキサス州北部地区の米国地方裁判所または米国テキサス州タラント郡に所在する州裁判所においてのみ提起されるものとし、あなたはこれらの法廷における対人管轄に同意し、不便な法廷に関する異議を放棄します。前述にかかわらず、X が、独自の裁量で、あなたに対して有する請求、訴因、または紛争を、請求について管轄権と裁判地を有するあなたが居住する国の管轄裁判所に提起することができることに同意します。
米国において公務上 Licensed Material を利用する連邦、州、または地方政府機関であり、法的に上記の準拠法、裁判管轄、または裁判地条項を受け入れることができない場合、それらの条項はあなたに適用されません。そのような米国連邦政府機関については、本契約およびそれに関連するいかなる訴訟も、米国法(抵触法への参照なし)により、連邦法がない場合および連邦法で許容される範囲内で、テキサス州法(法選択を除く)により規定されます。
2. **X に対する請求提起は 1 年以内です。** 適用される法律が、その請求に対する通常の時効を合意で短縮することを許可しないと規定していない限り、本契約に起因または関連するいかなる請求も、紛争を生じさせる事象または事実の発生日から 1 年以内に X に対して提起する必要があります。この期間内に請求を提起しない場合、当該事象または事実に基づく、あらゆる種類または性質の請求または訴因を追及する権利を永久に放棄し、そのような請求または訴因は永久に禁じられ、X はそのような請求について責任を負いません。
3. **集団訴訟の放棄。** 法律で許容される範囲において、いかなる主張された集団訴訟、集合訴訟、または代表訴訟手続きにおいても、原告または集団構成員として参加する権利も放棄します。
4. **本節の変更。** この紛争解決節は、X によって提供されるサービスまたは通信のキャンセルまたは購読解除を含む、あなたと X との関係の終了後も存続します。
5. **差止による救済。** 前述にかかわらず、あなたは、X の知的財産または Confidential Information を保護する本契約の違反または違反のおそれが生じた場合には、金銭的損害賠償が X にとって不十分な救済策となることに同意します。そのような違反または脅威が生じた場合、X は、既得のその他の救済策に加えて、担保金を提供する必要なく、予備的または差止による救済(そのような規定への違反となる措置をあなたが取ることを禁止する命令を含む)、および該当する場合は特定履行を受ける権利を有します。当事者は、当事者が事業を行うか設立された州にかかわらず、国際物品売買契約に関する国際連合条約も統一コンピュータ情報取引法も本契約に適用されないことに同意します。X による本契約に基づく約束または権利の放棄は、X によって承認された書面に記載されない限り、有効ではありません。
**B. 本節は、あなたが欧州連合、EFTA 加盟国、または英国に居住している場合にのみ適用されます。この節を注意深くお読みください。あなたの法的権利、特に裁判所に訴訟を提起する権利に重大な影響を与える可能性があります。**
1. **準拠法および裁判管轄地の選択。** 法律で許容される範囲において、本契約に関連するすべての紛争、本契約に起因もしくは関連する紛争、請求、または論争、Licensed Material のマーケティング、および/または Licensed Material への参加は、当事者間の反対の合意にかかわらず、アイルランドの管轄裁判所においてのみ提起され、抵触法規定を考慮せずアイルランド法により規定されます。前述にかかわらず、X が、独自の裁量で、あなたに対して有する請求、訴因、または紛争を、請求について管轄権と裁判地を有するあなたが居住する国の管轄裁判所に提起することができることに同意します。
2. **X に対する請求提起は 1 年以内です。** 適用される法律が、その請求に対する通常の時効を合意で短縮することを許可しないと規定していない限り、本契約に起因または関連するいかなる請求も、紛争を生じさせる事象または事実の発生日から 1 年以内に X に対して提起する必要があります。この期間内に請求を提起しない場合、当該事象または事実に基づく、あらゆる種類または性質の請求または訴因を追及する権利を永久に放棄し、そのような請求または訴因は永久に禁じられ、X はそのような請求について責任を負いません。
3. **集団訴訟の放棄。** 法律で許容される範囲において、いかなる主張された集団訴訟、集合訴訟、または代表訴訟手続きにおいても、原告または集団構成員として参加する権利も放棄します。
4. **本節の変更。** この紛争解決節は、X によって提供されるサービスまたは通信のキャンセルまたは購読解除を含む、あなたと X との関係の終了後も存続します。
5. **差止による救済。** 前述にかかわらず、あなたは、X の知的財産または Confidential Information を保護する本契約の違反または違反のおそれが生じた場合には、金銭的損害賠償が X にとって不十分な救済策となることに同意します。そのような違反または脅威が生じた場合、X は、既得のその他の救済策(金銭的損害賠償を含む)に加えて、担保金を提供する必要なく、予備的または差止による救済(そのような規定への違反となる措置をあなたが取ることを禁止する命令を含む)、および該当する場合は特定履行を受ける権利を有します。当事者は、当事者が事業を行うか設立された州にかかわらず、国際物品売買契約に関する国際連合条約も統一コンピュータ情報取引法も本契約に適用されないことに同意します。X による本契約に基づく約束または権利の放棄は、X によって承認された書面に記載されない限り、有効ではありません。
**XIV. その他。**
**A. 譲渡。** X の事前の書面による同意なしに、本規定に基づき付与された権利または義務の全部または一部を、自発的に、法律の運用、契約、合併(あなたが存続または消滅する法人であるかにかかわらず)、株式または資産の売却、統合、解散、政府による措置その他により譲渡してはなりません。X は、米国外に居住する X ユーザーの情報について責任を負うアイルランドの会社である X Internet Unlimited Company のために、修正および同意に署名する権限を有します。本節に違反する譲渡は、無効となり、X は本契約を終了することができます。
**B. ユーザーの保護。** X によって書面で明示的に承認されていない限り、以下の目的で X コンテンツまたは X コンテンツから派生した情報を利用したり、故意に表示、配布、その他の方法で利用可能にしたりしてはなりません: (a) X ユーザーまたは X コンテンツの調査または追跡を含みますが、これに限定されない、監視の実施もしくは提供、または情報収集;(b) X ユーザーの合理的なプライバシー期待と矛盾する方法で、違法もしくは差別的な目的または方法での分析または調査の実施もしくは提供;(c) 抗議、集会、コミュニティ組織的な会合を含みますが、これに限定されない、機微なイベントの監視;または (d) 健康(例: 妊娠)、財務状況の悪さ、政治的所属もしくは信条、人種もしくは民族的出自、宗教的もしくは哲学的所属もしくは信条、性生活もしくは性的指向、労働組合への加入、犯罪の疑いのある行為もしくは実際の犯罪行為に関する X コンテンツ、または法律で禁止されている他の機微な個人情報カテゴリーを含む、機微な個人情報に基づく個人のターゲティング、セグメント化、またはプロファイリング。
**C. 政府による利用。** 政府関連の団体(それぞれ「**Government End User**」)であるユーザー、またはそれらの団体を代表して行動するユーザーに X コンテンツを表示、配布、またはその他の方法で利用可能にする場合: (a) Enterprise プラン([developer.x.com](https://developer.x.com) に記載)に申請(または既に加入)する必要があります;(b) X にレビューのために利用ケースを提出する際に、そのようなすべての Government End User を識別する必要があります;および (c) その後、Services が Government End User に、または新しい利用ケースのために X コンテンツを表示、配布、またはその他の方法で利用可能にする前に、新しい Government End User または既存の Government End User との新しい利用ケースについて、X に書面で通知する必要があります。X は、Government End User に X コンテンツを利用可能にすることを禁じることがあります。監視の実施または情報収集を主要な機能または任務とする Government End User に対して、X コンテンツまたは X コンテンツから派生した情報を利用したり、故意に表示、配布、その他の方法で利用可能にしたりしてはなりません。法執行機関が現在進行中の調査の目的で X またはそのユーザーに関する情報を要求する場合、[**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support) にある X の Guidelines for Law Enforcement をご参照いただくことができます。X API および X コンテンツは、48 C.F.R. 2.101 で定義される「商用アイテム」であり、48 C.F.R. 12.212 で使用される「商用コンピュータソフトウェア」および「商用コンピュータソフトウェアドキュメンテーション」で構成されています。政府機関による X API または X コンテンツの利用、修正、派生物、複製、リリース、実行、表示、開示、または配布は、本契約の条件で明示的に許可されている場合を除き、禁止されています。加えて、米国政府機関による利用はすべて、48 C.F.R. 12.212 および 48 C.F.R. 227.7202-1 から 227.7202-4 に従って行われる必要があります。米国州または地方政府機関の従業員または代表者として公務上 X API または X コンテンツを利用しており、法的に本規定の補償、裁判管轄、裁判地、その他の条項を受け入れることができない場合、それらの条項は法律で求められる範囲でその団体に適用されません。契約者/製造者は、X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA です。
**D. 法令遵守、輸出および輸入。** 各当事者は、贈収賄および/または汚職に関するすべての法律を含む、適用される外国、連邦、州、地方の法律、規則、および規制を遵守します。Licensed Material は米国輸出法の対象となり、配達または利用される国の輸入および利用法の対象となる場合があります。あなたはこれらの法律を遵守します。これらの法律の下で、Licensed Material は、ライセンス、または関連する政府当局の承認なしに、これらの法律によって制限された国、または外国国民(米国政府が禁輸措置を講じている国(現在キューバ、イラン、北朝鮮、北スーダン、シリア)を含む)、または制限もしくは拒否されたエンドユーザー(米国財務省外国資産管理局によって禁止されている個人または団体を含みますが、これに限定されません)に、あるいはいかなる制限された最終利用のためにも、販売、賃貸、ダウンロード、移動、輸出、再輸出、または国境を越えて移転してはなりません。あなたは、Services に必要なすべての権利およびライセンスを維持します。
**E. データ保護附属書。** 各当事者は、[**https://gdpr.x.com/en/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html) にある X Controller-to-Controller Data Protection Addendum を遵守します。これは、X によって随時更新される場合があります。
**F. 存続。** 本契約の第 III 節(利用に関する制限)、第 V 節(所有権およびフィードバック)、第 VI 節(秘密保持)、第 VII(I) 節(終了)、第 VIII 節(コンプライアンス監査)、第 IX 節(保証否認)、第 X 節(補償)、第 XI 節(責任の制限)、第 XIII 節(紛争解決および集団訴訟の放棄);および第 XIV 節(その他)は、本契約の終了後も存続します。
**G. 完全合意。** 本契約は、本契約の対象事項に関する当事者間の完全な理解を構成し、対象事項に関する当事者間の書面または口頭の他のすべての合意に優先し、置き換えます。本契約のいずれかの条項が裁判所によって強制不能とされた場合、本契約の残りの条項は引き続き有効です。本契約に基づく放棄は、書面で放棄を許可する当事者によって署名されない限り、有効ではありません。ある機会に付与された放棄は、他の機会における放棄として作用しません。本契約は、パートナーシップ、代理、または合弁事業を作り出したり、暗示したりするものではありません。
# 表示要件: 投稿
Source: https://docs.x.com/ja/developer-terms/display-requirements
アプリで X の投稿を表示する際の表示要件。ブランディング、帰属表示、投稿の構成要素、インタラクティブ性、レンダリングすべきメタデータを含みます。
## 一般原則と投稿の構成要素
投稿は当社の最も目立つブランド要素の一つであるため、正しく表示することが重要です。投稿、タイムライン、その他の X コンテンツを表示する際は、以下の表示要件に従ってください。
投稿を表示するだけの目的でこれらのガイドラインに従う場合、表示や商標に関する追加の許可を得るために X に連絡する必要はない場合があります。ただし、提案する使用方法とコンテキストを X にレビューしてもらうために提出することもできます。(場合によっては、元のコンテンツ作成者からの許可が別途必要になることがあることに注意してください。X は第三者/ユーザーのコンテンツの使用許可を提供しません。)
以下の一般原則はすべての表示媒体に適用されます。ただし、媒体固有の要件も適用されるため、以下のセクションで説明しています。
以下の画像は、投稿のすべての主要な構成要素を示しています。
### 推奨事項
* 実在のアカウントからの、改変されていない本物の投稿を表示してください。
* X の [利用規約](https://x.com/tos?lang=en)、[X ブランドアセット&ガイドライン](https://about.x.com/en_us/company/brand-resources.html)、(該当する場合は)[開発者契約および開発者ポリシー](/developer-terms/agreement)に従ってください。
* X ロゴを表示してください。
### 禁止事項
* ユーザーからの明示的な許可なしに、X コンテンツを商品やサービスの宣伝(例: 広告で X コンテンツを表示する、または商品やサービスの推奨を示唆する形で X コンテンツを表示する)に使用しないでください。
* X による支援、承認、または X との誤った関連付けを示唆するために X コンテンツを使用しないでください。
* 他のソーシャルプラットフォームのボタンやアイコンを含めないでください。
* 投稿のテキストを変更しないでください。
* プラットフォーム上に存在しない投稿のモックアップを使用しないでください。
***
## オンライン表示 / モバイル、Web、その他
私たちは、X の使いやすさと力をすべての人に届けることに全力で取り組んでいます。すべての投稿を最適に表示できるよう、[埋め込み投稿および/または埋め込みタイムライン](https://publish.x.com)の使用を強く推奨します。これらのプロダクトを使用して X コンテンツを公開すると、投稿とタイムラインは、写真、動画再生、編集された投稿、OAuth なしでの最新の X データの取得などの高度な機能を含めて、自動的に正しくレンダリングされます。埋め込み機能を使用できない場合は、投稿とタイムラインをオンラインで表示する際に、以下の要件に従う必要があります。
### 投稿者
* 投稿者のプロフィール画像、@ユーザー名、表示名は常に表示され、ユーザーの X プロフィールへリンクされている必要があります。
* 投稿者の @ユーザー名は常に「@」記号付きで表示される必要があります。
* 投稿者のアバターは、投稿者の名前および @ユーザー名の左側に配置される必要があります。右から左に読まれる言語の投稿の場合は、投稿者のアバターは投稿者の表示名および @ユーザー名の右側に配置される必要があります。
### 投稿テキスト
* 投稿テキストは、投稿者の表示名および @ユーザー名の下の行に表示され、変更や修正をしてはなりません。
* タッチデバイスでは、投稿テキストと投稿者の周囲の空白部分は、投稿のパーマリンクへリンクしている必要があります。
* 投稿テキスト内の投稿エンティティは、X 上の適切な場所に正しくリンクされている必要があります。例:
* ユーザー @メンションは、メンションされたユーザーのプロフィールへリンクする必要があります。
* ハッシュタグは、そのハッシュタグをクエリとする X 検索へリンクする必要があります。
* 投稿テキスト内のリンクは、URL エンティティ API レスポンスの display\_url フィールドを使用して表示し、元の t.co の url フィールドへリンクする必要があります。
### タイムスタンプ
* 投稿のタイムスタンプは表示され、投稿のパーマリンクへリンクしている必要があります。
### 投稿アクション
* すべての投稿アクションアイコン(リプライ、リポスト、いいねを含む)は、ユーザーが投稿にインタラクションできるように常に表示されている必要があります。これらのアクションは [Web Intents](/x-for-websites/web-intents/overview) または認証された X API を使用して実装する必要があります。投稿アクションの代わりに、タイムスタンプの隣に「X で表示」を表示し、ユーザーを投稿のパーマリンクへリンクすることもできます。
* 他のソーシャルアクションや第三者のアクション(例: 購読、コメント、いいね)を投稿に付加してはなりません。
* 表示される投稿がリポストの場合、リポストしたユーザーの表示名とリポストアイコンを、投稿テキストの上または下に表示する必要があります(例: 「Jane Doe がリポスト」)。表示名は、リポストしたユーザーのプロフィールへリンクしている必要があります。
* [リプライの表示ガイドライン](/developer-terms/reply-requirements) に従ってください。
### 投稿の編集
* X では、元の投稿から最初の 30 分間に最大 5 回まで、投稿を編集することができます。[埋め込み投稿](/x-for-websites/embedded-posts/overview) を使用する場合、投稿が埋め込みの前に編集されたか後に編集されたかによって、表示が若干異なります。
* 投稿が先に埋め込まれてから編集された場合、それらの編集を X プラットフォーム上で発生した通りに表示する必要があります:
* 編集された投稿の以前のバージョンを表示している場合、投稿の新しいバージョンが存在することをタイムスタンプの下に記載し、その注記の右側に、投稿の編集履歴を展開するリンクを提供する必要があります。
* その後、投稿の完全な編集履歴を表示する必要があります。
投稿が先に編集されてから埋め込まれた場合、投稿が編集されたことをタイムスタンプに記載し、タイムスタンプは X 上のライブ投稿へリンクしている必要があります。
### ブランディング
* 公式の X ロゴは、個別の投稿の右上隅、またはタイムラインに直接付随する形(例: タイムラインの上部)で、合理的に視認できる状態で常に表示される必要があります。ロゴの高さ「x」は、画像に示されているものと同等である必要があります。ブランドガイドラインとアセットについては、X の [ブランドリソースページ](https://about.x.com/en_us/company/brand-resources.html) をご覧ください。
### モバイルディープリンク
* ネイティブモバイルアプリからのディープリンクは、ネイティブの X アプリケーションに遷移する必要があります。デバイスにネイティブの X アプリケーションがインストールされていない場合、リンクは Web ブラウザ経由で X.com に遷移する必要があります。
### タイムライン
* すべてのタイムラインは、ユーザーが個別の投稿の詳細を表示できるようにする必要があります(例: 投稿タイムスタンプをリンクするか、投稿エリア全体をリンクする)。
投稿の近くに広告を掲載する予定の場合は、[開発者ポリシー](/developer-terms/policy) に準拠するようにしてください。
いずれかのルールに準拠できない理由がある場合は、X コンテンツを表示する前に、[Policy Support フォーム](https://help.x.com/forms/platform) から直接ご連絡ください。X の名前および商標の使用に関するご質問や詳細については、[trademarks@x.com](mailto:trademarks@x.com) までお問い合わせください。
***
## ブロードキャスト表示 / 15 分間の名声
放送メディアでの X の使用を歓迎し、推奨します。当社の要件は、X ユーザーが自身のコンテンツに対して適切な帰属表示を受けられるようにし、視聴者に最高の体験を提供するために役立ちます。
### 推奨事項
* ユーザーのフルネーム、@ユーザー名、投稿テキスト、プロフィール画像を表示してください。
* 投稿が放送に表示されている限り、投稿の近くに X ロゴを含めてください。X ロゴのサイズは、上記の画像のサイズと同程度で、コンテンツに対して適切な比率になっていることを確認してください。
* 投稿の全文を使用してください。
* 画像を表示する場合、投稿テキストと合わせて、ユーザーの表示名、@ユーザー名、および X ロゴも含める必要があります。
### 禁止事項
* ユーザーからの明示的な許可なしに、広告で X コンテンツを表示したり、商品やサービスの推奨を示唆する形で X コンテンツを表示したりしないでください。
* 投稿の内容やユーザーの識別情報を削除、隠蔽、または改変しないでください(ハイパーリンクの削除は除きます)。
* タイムスタンプを除外しないでください。
* 制作物のタイトルに X の商標を全部または一部でも使用する場合、まず [trademarks@X.com](mailto:trademarks@X.com) までご連絡いただき、X との使用について確認してください。
***
## 口頭またはナレーション
### 投稿
投稿を画面表示せずに読み上げる場合、X ロゴを表示する必要はありませんが、口頭で X に帰属表示する必要があります。投稿は編集せずに、元の記載通りに読み上げてください。
### ユーザー名
X のユーザー名に言及する際は、X への言及を含めてください。例: 「X の at-username でフォローしてください」または「レディー・ガガは X の at-ladygaga でフォローできます」
### ハッシュタグ
X のハッシュタグに言及する際は、X への言及を含めてください。例: 「X で『election2016』のハッシュタグを使用してください」または「この放送の X 上でのハッシュタグは bbcaq です」。
# Geo ガイドライン
Source: https://docs.x.com/ja/developer-terms/geo-guidelines
X API のジオタグ付き投稿と位置情報データの取り扱いに関するガイドライン。geo 機能、place オブジェクト、ユーザーのプライバシーに関する考慮事項を含みます。
Last Update: October 22, 2014.
## はじめに
Posting With Location は、X API における位置情報タグ付け機能です。この機能は、投稿をよりコンテキストに沿ったものにすることで、ユーザーにとってより意味のある体験を提供します。たとえば、「花火!」という投稿だけでは伝わりにくいですが、位置情報が付加されると「カリフォルニア州サンフランシスコの SoMa 地区から『花火!』」となり、格段に伝わりやすくなります。開発者エコシステムと協力して、この機能を活用した素晴らしい体験を作り上げていくことを楽しみにしています!
## ユーザーのプライバシーと位置情報に対するユーザーによる制御
良好で安全な体験を確保するため、開発者はユーザーの位置情報を取り扱う際、プライバシーに十分配慮するとともに、「Posting with Location」体験の基本的な一貫性を提供する必要があります。ユーザーのプライバシーを保護し、ユーザーが自身の行動の影響を理解できるようにするために、以下の重要なポイントに留意してください。
## 一般的なガイドライン
* ユーザーは Posting With Location 機能を利用するためにオプトインする必要があります(位置情報を「オン」にする)。
* ユーザーは、投稿とともに正確な位置情報を表示することについて明示的な許可を与える必要があります。クライアント上で位置情報機能が「スティッキー」である場合(つまり、一度オンにすると常に投稿に位置情報が付随する場合)、地名 (place\_ids) のみを表示し、投稿ごとに、または特定の代替設定として、ユーザーが正確な緯度・経度についてさらにオプトインできるようにすることを推奨します。
* 投稿するためにユーザーの位置情報データにアクセスする場合、ユーザーの明示的な許可なく、その情報を投稿とは別に保存してはなりません。
* 投稿と関連付けてどの程度の位置情報が(表示される場合)表示されるのかが、ユーザーに明確に伝わっている必要があります。これを実現する一つの方法は、投稿が公開される前に、その情報がどのように表示されるかを示す地図を表示することです。正確な緯度・経度がクライアント上でユーザーが公開する情報の一部(またはその唯一の情報)である場合、正確な座標が公開されることをユーザーに明確に伝える必要があります。
* ユーザーは、投稿を作成するたびに位置情報のオン/オフを切り替えられる必要があります。
* X の [開発者ポリシー](/developer-terms/policy.html) の条項に従う必要があります。これには、X API から取得した位置情報データやその他の地理情報を、投稿の一部として以外は集約、キャッシュ、保存してはならず、また当該位置情報データや地理情報を単体で使用してはならないという要件が含まれます。
## 具体例
例 1: *正確な緯度・経度を追加しない場合(これは現在の X Web クライアント UI です)*
1. ユーザーが投稿を作成する際に「位置情報を追加」というリンクを表示する。
2. バックグラウンドで X の [reverse\_geocode](https://developer.x.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode.html) API を呼び出し、緯度、経度、位置情報の精度、ユーザーの希望する粒度(デフォルトは「neighborhood」)を渡す。
3. デフォルトの場所の名前を表示する(X は意味のある順序で並べようとします。並び順は、X クライアントが変更を加えずにそのままリストを表示できるようになっています)。
4. ユーザーがリストから別の場所を選択できるようにする(例: 「SoMa, San Francisco」から「South Beach, San Francisco」へ変更)。
5. 重要: 正確な位置情報を表示する場合は、ユーザーに対して透明性を確保してください。正確な位置情報が表示されることをユーザーが確実に理解できるようにする必要があります。
6. 投稿を作成するたびに、ユーザーが位置情報のオン/オフを選択できるようにする。
例 2: *既存のジオタグ実装*
多くの X クライアントアプリでは、元のジオタグ機能(place\_ID を提供せずに緯度・経度のみをブロードキャストする)が実装されています。API のデフォルト動作はこの挙動を模しており、開発者は現在の挙動を維持するために既存のアプリに変更を加える必要はありません。実際、緯度・経度の座標を X に渡すだけで、X はその緯度・経度を自動的に逆ジオコーディングし、データが利用可能なエリアについては緯度・経度に加えて place\_ID を表示します。
正確な座標が使用され X 上で表示されることが、ユーザーに透明性をもって伝わるようにしてください。既存のアプリのベストプラクティスとしては、ユーザーが投稿ごとに位置情報のオン/オフを切り替えられるようにすることが挙げられます。また、正確な座標の代わりに place\_ID のみを共有することをデフォルトの「スティッキー」設定として、ユーザーが選択できるようにすることもできます。
## X によるユーザー位置情報データの保存
X は、クライアントから渡されたデータを次のように保存します:
* ユーザーがフォロワーに公開表示することを選択したすべてのデータを X は保存します。これは、投稿の作成日時を示すタイムスタンプを X が保存する方法と似ています。つまり、ユーザーが正確な座標を含めて投稿した場合、その投稿が存在する限り、X はその正確な位置情報を投稿とともに保存します。ユーザーは、設定ページの「位置情報履歴を消去」ボタンをクリックすることで、投稿から位置情報データを消去できます。詳細は [こちら](https://support.twitter.com/articles/122236-how-to-tweet-with-your-location) をご覧ください。
## まとめ
投稿に位置情報を追加すると、ユーザーの視点から見た文脈と価値が大きく増します。ただし、クライアントにおける位置情報の実装においては、プライバシーとユーザーへの透明性を、位置情報中心のプロダクトを設計する上での重要な考慮事項として慎重に扱う必要があります。
プライバシー、位置情報、その他の geo 機能に関するご質問やご意見がございましたら、[お問い合わせください。](https://support.twitter.com/forms/platform)
# X 開発者ポリシー
Source: https://docs.x.com/ja/developer-terms/policy
X 開発者ポリシーは、X API の許容される利用について、コンテンツ、自動化、プライバシー、セキュリティ、および禁止行為に関するルールを含めて概説します。
## X + 開発者
X は開発者を愛しています。このコミュニティが X データの力を活用して生み出すツールやサービスに、私たちは大変喜び、驚いています。このコミュニティへのコミットメントの一環として、私たちは開発者にとってオープンで公平、X 上の人々にとって安全、そして X プラットフォーム全体にとって有益なデータアクセスの提供を目指しています。これらの目標をさらに推進するため、API と X コンテンツの適切な利用に関する当社のルールと期待を人々が理解できるようにするためのガイドとして、開発者ポリシーを策定しました。
本開発者ポリシー(以下「**ポリシー**」)は、X のアプリケーション、サービス、ウェブサイト、ウェブページ、およびコンテンツからなるエコシステムとやり取りする開発者向けのルールとガイドラインを提供します。これは、X API および X コンテンツへのアクセスと利用を規定する X との契約の一部です(開発者契約または X との他の書面による契約の一部として)。ポリシー違反は契約違反とみなされます。本ポリシーは、通知なく随時変更されることがあります。本ポリシーで使用される大文字で始まる用語で、本ポリシー内で定義されていないものは、[開発者契約](/developer-terms/agreement) またはマスターライセンス契約でそれぞれに付与された意味を持ちます。
## このポリシーの使い方
このポリシーは、できるだけ従いやすくなるように構成されています。X API および X コンテンツを利用する際は、以下のポリシーセクションの情報を常に念頭に置いてください:
1. **プラットフォーム利用ガイドラインに従う** - X API と X コンテンツへのアクセスが承認されることは、最初のステップにすぎません。X プラットフォームの計画された利用について、ポリシーへの準拠を確保する方法について疑問がある場合は、まず当社のプラットフォーム利用ガイドラインをご確認ください。
2. **成功へ準備を整える** - あなたはすべての X ポリシーに準拠する責任があります。X API と X コンテンツにアクセスする前に、本ポリシーおよびこの文書でリンクされているポリシーを確認し、理解することが重要です。ポリシーを確認する時間を投じることで、後々何時間もの手戻り作業を防げるかもしれません。
3. **プライバシーとコントロールは不可欠** - X 上の人々のプライバシーを保護し擁護することは、当社のコア DNA に組み込まれています。したがって、人々の合理的なプライバシー期待と矛盾する形で X データを使用することを禁止します。X API に基づいて構築したり X コンテンツにアクセスしたりする際、あなたはこのコミットメントを守るための特別な役割を担っています。最も重要なのは、人々のプライバシーを尊重し、データの利用方法について透明性とコントロールを提供することです。
これら 3 つの主要なセクションのそれぞれの意味について、以下でさらに詳細を説明しています。X API と X コンテンツの利用が当社のポリシーに準拠していることを確認するために、慎重にご確認ください。
本ポリシー(またはその他の X ポリシー)に違反していると当社が判断した場合、X API と X コンテンツへのアクセスを一時停止または恒久的に取り消すことがあります。
最後に、X は、X アプリケーションの改善、商用利用の確認、承認された利用ケースおよび本ポリシーへの準拠を確保するために、X API の利用状況を監視することがあることをご了承ください。
お読みいただきありがとうございます。そして、私たちと共に開発してくださることに感謝します!皆さんが何を作り上げるか、楽しみにしています!
## プラットフォーム利用ガイドライン
X のポリシーをレビューし、正しい方法で API アクセスを設定しましたか?あなたのサービスは X のプライバシーおよびコントロールガイドラインに従っていますか?これら 2 つの質問に「はい」と答えられるなら、X API と X コンテンツを利用する準備が整っています。X のプラットフォーム利用ガイドラインは、サービスのライフサイクル全体を通じて、初日から X コンテンツの利用がコンプライアンスに準拠していることを確保するために必要な支援を提供します。統合が X 上の人々および X プラットフォーム全体にとって安全で有益な方法で運用されていることを確認するために、これらのルールを定期的にレビューすることをお勧めします。
## スパム、ボット、自動化
**スパムを作成したり、あらゆる形式のプラットフォーム操作に関与したりするための X API および開発者向けプロダクトの使用は禁止されています。** [プラットフォーム操作およびスパム](https://help.x.com/rules-and-policies/platform-manipulation) に関する X ルールをレビューし、サービスが当社のポリシーに違反せず、また人々が違反することを可能にしないようにしてください。
[**投稿の投稿、アカウントのフォロー、ダイレクトメッセージの送信などの書き込みアクションを実行するサービスは、Automation Rules に従う必要があります。**](https://help.x.com/rules-and-policies/x-automation) 特に以下を守ってください:
* [自動リプライやダイレクトメッセージ](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444) を送信する前に、常に明示的な同意を得る
* あなたからの連絡を受けたくないというオプトアウトの要求を直ちに尊重する
* [大量フォロー](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769) を含む、一括、攻撃的、またはスパム的な行為を絶対に行わない
* [複数のアカウント](https://blog.twitter.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html) で同一または実質的に類似したコンテンツを絶対に投稿しない
**API ベースのボットアカウントを運用している場合、そのアカウントが何であるか、および誰が責任を持つのかを明確に示さなければなりません。** アカウントがボットであるかどうかについて、人々を誤解させたり混乱させたりしてはいけません。これを行う良い方法は、プロフィールのバイオにそのアカウントがボットである旨の記述を含めることです。
## X パフォーマンスのベンチマーキング
**ベンチマーキング、競合、または商用目的のために、X の可用性、パフォーマンス、機能、または利用状況を測定するために X API を使用してはなりません。** たとえば、以下のような目的で X API を絶対に使用しないでください:
* 月間アクティブ (MA) 数や日次アクティブ (DA) 数など、X の集計メトリクスの算出
* 1 日あたりの投稿総数やアカウントエンゲージメント数など、X 投稿の集計メトリクスの算出
* X のレスポンス性の測定または分析
* 以下で許可されている場合を除き、X 上のスパムやセキュリティの測定または分析
**私たちは、X における会話の健全性の向上に役立つ研究をサポートします。** X から明示的な書面による許可を得ない限り、X ポリシーに違反する行動やコンテンツを測定、分析、または識別しようとする研究や発見を公に開示すること、あるいはそのようなサービスを X API または X コンテンツを使用して開発、作成、または提供することはできません。
**DSA 研究者:** デジタルサービス法第 40 条に基づくアクセスに関して X に連絡する必要がある場合は、[**EU-Questions@X.com**](mailto:EU-Questions@X.com) までご連絡ください。研究者アクセスを申請したい場合は、[申請フォーム](https://forms.gle/btDwenPF7M3hgSvw7) をご提出ください。
## 投稿の公開表示
**サービスを利用する人々に対して公に、または表示するすべての X コンテンツの完全性を維持する必要があります。** [X for Websites](https://developer.x.com/docs/twitter-for-websites/overview) を使用してコンテンツを表示しない場合は、X API を使用して表示するために利用可能な最新バージョンを取得する必要があります。表示されているコンテンツが X API を通じて利用できなくなった場合、合理的に可能な限り速やかに、または X もしくは該当する X アカウント所有者からの削除リクエストの受領後 24 時間以内、あるいは適用される法律により求められる期間内に、サービスからそれを削除する必要があります。
**X コンテンツをオフラインで表示する場合は、従うべき特定のルールがあります。** 投稿をオフラインで表示する場合は、ブロードキャストでの投稿の使用に関する [ガイドライン](https://developer.x.com/developer-terms/display-requirements) に従ってください。
**投稿を埋め込みまたは表示している場合、サイトの 1 日あたりのインプレッション数が 1,000 万を超える場合は、X API アクセスについて当社に連絡する必要があります。** X は、X API の利用条件として追加の条件を要求する権利を留保します。X for Websites 開発者の利用に関するその他の制限には、以下が含まれます:
* **埋め込み投稿および/または埋め込みタイムライン**
* 関心ベース広告およびパーソナライゼーションを含む、あなたのウェブサイトでの閲覧行動に関するデータの X による収集と利用を完全に開示する、法的に十分な通知を人々に提供する必要があります。また、そのような収集と利用に関して、法的に十分な同意を人々から取得する必要があります
* [こちら](https://help.x.com/x-for-websites-ads-info-and-privacy) で説明されている通り、X の関心ベース広告およびパーソナライゼーションを人々がどのようにオプトアウトできるかについて、法的に十分な指示を提供する必要があります
* **X for Websites ウィジェット**
* X の [cookie 使用](https://help.x.com/rules-and-policies/x-cookies) で説明されているとおり、Cookie またはその他の情報のデバイスへの保存およびアクセスに関する明確かつ包括的な情報が人々に提供され、それに同意していることを確認する必要があります(そのような情報の提供および同意の取得が法律で求められている場合)
* **13 歳未満の子供を対象としたサービス**
* 13 歳未満の子供を対象としたサービスは、[こちら](https://developer.x.com/docs/twitter-for-websites/privacy) で説明されているとおり、埋め込み投稿および/または埋め込みタイムラインにおける X のカスタマイズをオプトアウトパラメータを「true」に設定してオプトアウトする必要があります
## コンテンツの再配布
**X コンテンツを取得する最良の場所は、直接 X からです。したがって、当社は X コンテンツの第三者への再配布を制限しています。** X コンテンツを第三者(ダウンロード可能なデータセットや API を介した提供を含む)に提供する場合、投稿 ID、ダイレクトメッセージ ID、および/またはユーザー ID のみを配布できます(以下に説明する場合を除きます)。
X から書面による許可を得ていない限り、30 日間で単一の事業体(単一の事業体に関連する複数の個人を含む)に配布できる投稿 ID の合計数は 1,500,000 を超えてはなりません。加えて、開発者は、非自動化された手段(スプレッドシートや PDF のダウンロードなど)による場合、サービスを利用する各人に対して 1 日あたり最大 500 件の公開 Post オブジェクトおよび/または User オブジェクトを提供できます。
学術研究者は、学術機関を代表する非商用の研究のみを目的とし、X から書面で承認されたもの、またはそのような研究のピアレビューや検証のためにのみ、投稿 ID および/またはユーザー ID を配布することが許可されます。研究に必要で、X によって承認された数の投稿 ID またはユーザー ID のみを使用できます。
第三者に提供される X コンテンツは引き続き本ポリシーの対象となり、それらの第三者は、当該ダウンロードを受け取る前に、X の [利用規約](https://x.com/tos)、[プライバシーポリシー](https://x.com/privacy)、[開発者契約](/developer-terms/agreement)、および [開発者ポリシー](/developer-terms/policy) に同意する必要があります。本 [ポリシー](/developer-terms/policy)、[開発者契約](/developer-terms/agreement)、または X との他の契約に含まれる X コンテンツの配布に関するその他の制限または限定を、いずれの事業体においても回避することを可能にしてはなりません。
**注:** 本セクションは、EU デジタルサービス法 (2022)(以下「**DSA**」)の第 40 条に基づいて X API アクセスを取得した研究者には適用されません。当該研究者は、代わりに DSA および開発者契約に定められた手続きおよび制限の対象となります。
## エンゲージメントへの対価支払い
**サービスは、X 上でアクションを取ることに対して人々に報酬を提供してはなりません。それは、プラットフォームの健全性を損なう非本物的なエンゲージメントを生み出すためです。** X API を使用する際、X 上のいかなるアクションに対しても、金銭的または仮想的な対価を販売または受領してはなりません。これには、投稿、フォロー、フォロー解除、リポスト、いいね、コメント、およびリプライが含まれますが、これらに限定されません。
## サービスの真正性
**人々がその出所と目的を理解できるように、サービスを明確に識別しなければなりません。** サービスのアイデンティティや機能を隠したり、X または第三者との関連を誤って示唆する名称、ロゴ、または URL を使用してはなりません。名前を売買する目的、または他者が名前を使用することを妨げる目的でアプリケーションを作成することは禁止されていることに注意してください。
**以下に人々を誘導する目的で、サービスのために URL(短縮 URL を含む)を使用してはなりません:**
* サービスとは無関係のサイト
* スパムまたはマルウェアのサイト
* 人々に X ポリシーの違反を促すサイト
## X の名称、ロゴ、および類似性
**X の名称およびロゴは、X コンテンツの出所として X を識別するためにのみ使用および表示できます。** 誤った推奨、支援、または X との関連を意図的に示唆する形で、X の名称およびロゴ、X 公式パートナープログラムバッジ、またはその他の類似のマークや名称を使用してはなりません。X の [ブランドリソース](https://about.x.com/who-we-are/brand-toolkit) には、X ブランドを正しく使用するための詳細情報が記載されています。
**X 認証済みアカウントバッジおよびその他の強化されたアカウント分類は、API を通じて X から報告されたとおりにのみ使用できます。** これにより、サービスが表示するコンテンツが X 上で表示されるものと同等であることを人々に伝えることができます。
## X 上での広告
**X コンテンツの周囲に広告を表示する方法と場所には、制限があります。** まず、あなたの広告は投稿と似ていたり、人々が投稿と混同するようなものであってはなりません。広告に関するその他のルールには以下が含まれます:
* **X コンテンツと広告の間には明確な区別が必要です。** X 広告以外の広告を X タイムライン内に配置してはなりません。
* **X は、X API を介して広告を配信する権利を留保します。** API 経由で配信を開始した後に X 広告を配信することを決定した場合、関連する条件に従って広告収益の一部を共有します。
* **X プラットフォーム外で人々を広告のターゲットにするために、X コンテンツまたは X API から取得した情報を使用してはなりません。**
以下に記載する X サービスまたは機能の使用については、以下の追加ルールが適用されます:
## X ログイン
**OAuth プロトコルなどを介して、X へのログインとログアウトを容易に見つけられるオプションを人々に提示しなければなりません。** *Sign in with X* オプションは、サービス上の他のサインアップまたはサインイン機能と同等以上の目立ちやすさで表示される必要があります。X アカウントを持たない人々に対しても、X 経由でアカウントを作成する機会を提供する必要があります。
***Sign in with X 経由でサービス上の誰かが認証された後、その X アイデンティティを明確に表示する必要があります。*** X アイデンティティには、その人物の現在の X @ハンドル、アバター、および X ロゴが含まれます。サービス上の X フォロワーの表示は、その関係が X に関連付けられていることを明確に示す必要があります。
X は、Sign In with X(または他の X 認証方法)を介してあなたのプロダクトおよびサービスへ、またはあなたやあなたの関連会社によって、もしくはこれらのために提供されているものへ認証またはログインした固有のユーザーの総数を随時監視する権利を留保します。その総数が、同様のティアのサービスを購読する他の開発者の通常のレベルを大幅に超える場合、X からの書面による通知を受けた時点で Enterprise プランに申請(または既に加入)する必要があります。
X は、随時 *Sign in with X* オプションをレビューし、その独自の裁量で、この X 機能をサービスから削除できることに同意するものとします。
## X カード
**質の高い体験を確保するため、カードが表示されるすべてのプラットフォームでレンダリングされるようにカードを開発する必要があります。** カードを使用する際に従うべき追加ルールには以下が含まれます:
* カード内に機微なメディアを表示する予定がある場合は、投稿を機微メディアとして「true」にマークする必要があります
* カード内のすべてのアセットのホスティングには HTTPS を使用する必要があります。カードは、アクティブな混合コンテンツのブラウザ警告を生成してはなりません
* 音声および動画コンテンツには停止または一時停止のコントロールを含め、自動再生する動画のデフォルトは「サウンドオフ」にする必要があります
**カードの意図された使用を含む、カードに設定された X の制限を超えたり回避したりしてはなりません。** カードの使用に関するその他の制限には以下が含まれます:
* X の承認なしに、第三者のスポンサードコンテンツをカード内に配置してはなりません
* カード内、またはカードから X 上で、金銭的インセンティブ(仮想通貨を含む)を添付してはなりません
* URL やメディアなど、誤解を招く、または文脈的に関連性のないコンテンツやアクションをカード内に含めてはなりません
* 誰かが投稿内でアプリを明示的に宣伝または言及している場合にのみ、投稿にアプリカードを添付できます
## 成功へ準備を整える
X API を使用する際の多くの潜在的な落とし穴は、サービスを初日から正しい方法で構築することで回避できます。開発者ポリシーのこのセクションには、X API または X コンテンツを利用する前にすべての開発者が従うべきルールが含まれています。
Free、Basic、および Pro プラン([developer.x.com](http://developer.x.com) で説明)は、趣味の開発者、商用プロトタイピング、初期段階の X プロダクト統合、および限られたエンドユーザーをサポートするアプリケーション向けに設計されています。この範囲を超えて X API および X コンテンツを利用する場合は、Enterprise プラン([developer.x.com](http://developer.x.com) で説明)に申請(または既に加入)する必要があります。
**当社は、ポリシー準拠を検証するために、X 開発者プラットフォームの提案されたすべての利用をレビューします。したがって、アクセスを付与および維持するために、計画された X API および X コンテンツの利用について開示(および該当する場合は更新)することが必要です。** すべての新規開発者は、X API にアクセスするために [開発者アカウントを申請](https://developer.x.com/portal/petition/essential/basic-info) する必要があります。承認された開発者アカウントを持たない現行の開発者は、X の指示に従って申請する必要があります。このプロセスの一環として、X API および X コンテンツの意図された利用について、書面による説明を提供する必要があります。
利用ケースの説明はあなたを拘束し、そこからの実質的な逸脱はルールへの違反とみなされ、エンフォースメントアクションが取られる可能性があります。利用ケースへの実質的な変更については当社に通知し、その新しい目的のために X コンテンツの利用を開始する前に承認を得る必要があります。これを怠ると、API およびデータへのアクセスの停止および終了につながる可能性があります。
**X API に基づいて構築するか、X コンテンツにアクセスすることにより、あなたはすべての X ポリシーに準拠する必要があります。** これらには、本 [開発者ポリシー](/developer-terms/policy)、[Automation Rules](https://help.x.com/rules-and-policies/x-automation)、[表示要件](https://developer.x.com/developer-terms/display-requirements.html)、[API 制限された利用ルール](/developer-terms/restricted-use-cases)、[X ルール](https://help.x.com/rules-and-policies/x-rules)、[X ブランドリソース](https://about.x.com/who-we-are/brand-toolkit)、ならびに X API または X コンテンツの利用に関して X と締結するその他の契約([開発者契約](/developer-terms/agreement) またはマスターライセンス契約もしくは注文(該当する場合)を含みますが、これらに限定されません)が含まれます。これらのポリシーへの変更や、X によって新たに立ち上げられるポリシーにも従う必要があります。サービスの利用状況を監視し、それを利用する人々による X ポリシー違反を防止するようにサービスを設計することはあなたの責任です。これを怠ると、API および X コンテンツへのアクセスの停止または終了につながる可能性があります。
**単一の利用ケース、または実質的に類似する、もしくは重複する利用ケースのために複数のアプリケーションを登録してはなりません。** この文脈における「利用ケース」とは、アプリケーションを介して実行される一貫した一連の分析、表示、またはアクションのことです。ツールやサービスの「ホワイトラベル」バージョンは許可されません。アプリケーションを「ホワイトラベル」化する予定がある場合は、当社に通知し、別途承認を得る必要があります。
*このルールへの唯一の例外として、* 同じサービスの開発、ステージング、および本番インスタンス用に最大 3 つのアプリケーションを作成して使用できます。これらのアプリは単一のアカウントに登録され、単一のサービスの dev、staging、prod インスタンスであることを(名前と説明で)明確に識別する必要があります。**開発またはステージング用のアプリケーションを本番目的で使用してはなりません。**
**すべての API キーやその他のアクセス認証情報は非公開に保つ必要があります。** 他者が所有する API キーやその他のアクセス認証情報を利用したり、他者の利用を奨励または助長したりしてはなりません。
**X とのライセンス契約は、X API と X コンテンツの利用を制限します。とりわけ、X API には、公正なデータ利用を確保し、プラットフォーム上のスパムに対抗するのに役立つレート制限があります。** レート制限や、本ポリシーもしくは X との契約で説明されている、[開発者サイト](https://developer.x.com/) に記載されている、もしくは X から伝達されたその他の制限や制約を、超えたり回避したりしてはなりません。
**X API 経由で受け取った X コンテンツから、専有的な注記やマークを削除または変更してはなりません。** これにより、人々が X コンテンツの出所と帰属を把握できるようにするのに役立ちます。
**データ完全性とプラットフォームの健全性の理由により、X API または X サービスのいかなる機能にも干渉、傍受、混乱、無効化を行ってはなりません。** つまり、[developer.x.com](https://developer.x.com/) に文書化されている通り、意図された方法で API を使用してください。許容される利用の詳細については、[HackerOne ガイドライン](https://hackerone.com/x) をご参照ください。
## プライバシーとコントロールは不可欠
X はプライバシーを真剣に受け止めており、X コンテンツと X API を利用するすべての人にも同様のことを期待しています。X 開発者プラットフォーム、X API、または X コンテンツを、人々の合理的なプライバシー期待と矛盾する形で利用した場合、エンフォースメントアクションの対象となる可能性があり、API および X コンテンツへのアクセスの停止および終了が含まれる可能性があります。
プライバシーとコントロールへのコミットメントは、X コンテンツのすべての利用と、当社の API を使用して構築するサービスのあらゆる側面に及ぶ必要があります。そのために、サービスを利用する人々は、あなたが自分たちのデータをどのように使用し、彼らに代わって X にどのようにアクセスするかを理解し、同意している必要があります。これは、明確で包括的かつ透明性のあるプライバシーポリシーを人々に提供し、サービスを利用する各人に代わってアクションを取る前に、明示的かつ十分な情報に基づいた同意を得ることで達成できます。**サービスへの認証だけでは、それ自体で同意を構成するものではないことに注意してください。**
## 同意と権限
**特に、以下のいずれかを行う前に、人々から明示的かつ十分な情報に基づいた同意を得なければなりません:**
* 彼らに代わって *何らかの* アクションを取ること。これには以下が含まれます(ただしこれらに限定されません):
* X へのコンテンツの投稿
* アカウントのフォロー/フォロー解除
* プロフィールまたはアカウント情報の変更
* 投稿へのハッシュタグやその他のコンテンツの追加
* X API または他の X ツール以外の手段でアクセスしたコンテンツの再公開
* 誰かの X コンテンツを商品やサービスの宣伝に使用すること
* ダイレクトメッセージ (DM) やその他のプライベートまたは機密情報などの非公開コンテンツの保存
* 保護されたコンテンツやその他のプライベートまたは機密情報の共有または公開
**サービスが人々に X へのコンテンツ投稿を可能にする場合、公開前に以下を行う必要があります:**
* 何が公開されるかを正確に表示する
* コンテンツにどのような位置情報が(あれば)追加されるかを、サービスを利用する人々に明確にする
**サービスが人々に、サービスと X の両方へのコンテンツ投稿を可能にする場合、公開前に以下を行う必要があります:**
* コンテンツを投稿する許可を得る
* どこにコンテンツを投稿するかを説明する
**すべての X コンテンツの保護およびブロックステータスを尊重する必要があります。ある人物の認証トークンを使用して取得したコンテンツを、そのコンテンツを閲覧する権限のない別の人物に提供してはなりません。**
* **保護されたアカウント:** [保護されたアカウント](https://help.x.com/safety-and-security/public-and-protected-posts) のコンテンツは、そのアカウントをフォローすることを所有者から承認された人のみが利用できます。したがって、保護されたアカウントにアクセスするサービスを運用する場合、そのコンテンツを閲覧する許可を持つ特定の人々に提供するためにのみ、これを行うことができます。
* **ブロックされたアカウント:** X 上の人々は、選択した理由でアカウントへのアクセスを [ブロック](https://help.x.com/using-x/blocking-and-unblocking-accounts) することができます。この選択を回避するために、トークンから取得した情報(またはその他の API ベースのアクション)を混合することは許可されません。
**ダイレクトメッセージ (DM) は本質的に非公開であるため、DM 機能を提供するサービスは個人プライバシーを守るために追加のステップを取る必要があります。DM コンテンツを閲覧する権限のない人々に対して DM コンテンツを提供してはなりません。サービスが DM 機能を提供する場合、以下も行う必要があります:**
* DM の既読受信イベントを送信する場合は、人々に通知する必要があります。これは、サービスに直接通知を提供するか、会話の他の参加者からの既読受信を表示することで行うことができます。
* DM で送信されるメディアが「共有」(すなわち、複数の DM で再利用可能)として設定される前に同意を得てください。DM 内のメディアを「共有」できるようにする場合、そのコンテンツがメディアの URL を持つ誰にでもアクセス可能であることを明確に通知する必要があります。
## コンテンツのコンプライアンス
**X コンテンツをオフラインで保存する場合、X 上のコンテンツの現在の状態と最新に保つ必要があります。** 具体的には、X 上でコンテンツが削除または変更された場合、保有しているコンテンツを削除または変更する必要があります。これは、合理的に可能な限り速やかに、または X もしくは該当する X アカウント所有者からの要求を受領してから 24 時間以内、あるいは X との契約もしくは適用される法律で求められる期間内に行う必要があります。これは、法律で別途禁止されている場合、および X の明示的な書面による許可がある場合を除いて行われる必要があります。
変更されたコンテンツはさまざまな形を取ることがあります。これには以下が含まれます(ただしこれらに限定されません):
* 非公開または保護ステータスを取得したコンテンツ
* プラットフォームから停止されたコンテンツ
* ジオタグが削除されたコンテンツ
* X から差し止められたか、削除されたコンテンツ
## X 外でのマッチング
**X 上の人物を、X 外で取得または保存された情報にマッチさせる状況は制限しています。** X 外でのマッチングとは、X @ハンドルやユーザー ID を含む X コンテンツを、人物、世帯、デバイス、ブラウザ、またはその他の X 外の識別子と関連付けることを指します。これを行うには、その関連付けを行う前に、その人物から明示的なオプトイン同意を得ている場合、または以下に説明する場合に限ります。
X アイデンティティを X 外の識別子とリンクさせるためのその人物の明示的なオプトイン同意がない状況では、その人物がその目的で使用されると合理的に予期する情報のみに基づいて、いかなる接続も行わなければなりません。加えて、その人物の明示的なオプトイン同意がない場合、以下に基づいてのみ、あなたの誰かに関する記録を X アイデンティティにマッチさせようとすることができます:
* **その人物から直接あなたに提供された情報。** あなたと事前の関係がない個人に関する記録(第三者から取得した個人に関するデータを含む)は、この基準を満たさないことに注意してください。および/または
* **公開データ。** ここでいう「公開データ」とは、以下を指します:
* 公開されている、一般的に利用可能なリソース(たとえば、専門家団体の会員名簿など)から取得した人物に関する情報
* 一般に公開されている X 上の人物に関する情報。以下を含みます:
* 投稿
* アカウントのバイオや公開設定された位置情報を含むプロフィール情報
* 表示名および @ハンドル
## プライバシーポリシー
**サービスをダウンロード、インストール、またはサインアップすることを許可される前に、サービスのプライバシーポリシーを人々に表示する必要があります。** これには、少なくとも以下の情報を開示する必要があります:
* サービスを利用する人々から収集する情報
* その情報の利用および共有方法(X との共有を含む)
* 情報に関する問い合わせや要求について、人々があなたに連絡する方法
プライバシーポリシーは、適用されるすべての法律と整合しており、[X のプライバシーポリシー](https://x.com/privacy) および [他のサービスおよび関連会社のプライバシーポリシー](https://help.x.com/rules-and-policies/x-services-and-corporate-affiliates) と同等以上に人々を保護するものでなければなりません。あなたおよび/または X のプライバシーポリシーに準拠できない場合、X API へのアクセスおよびすべての X コンテンツの利用を中止する必要があります。
## ジオデータの使用
**ジオデータの使用は、この情報の機微性により追加の制限が伴います。** サービスが投稿に位置情報を追加する場合、人々に以下を開示する必要があります:
* 位置情報を追加するタイミング
* 位置情報をジオタグとして追加するか、アノテーションデータとして追加するか
* 位置情報が場所として記載されるか、地理座標として記載されるか
アプリケーションが人々の位置情報を含めて投稿することを可能にする場合、X の [Geo ガイドライン](/developer-terms/geo-guidelines) に完全に準拠する必要があります。
**位置情報データや地理情報を単体で使用することは禁止されています。** X コンテンツに含まれる位置情報データやその他の地理情報を、投稿の一部として以外は保存、集約、キャッシュしてはなりません(また、他者にさせてはなりません)。たとえば、投稿から位置情報データや地理情報を切り離して、個人がどこにいたのかを時間経過にわたって示すことは行ってはなりません。集約された地理活動(たとえば、あるハッシュタグを使用している都市内の人数)を示すヒートマップおよび関連ツールは許可されています。
## X パスワード
**X パスワードを保存したり、X パスワード、アカウント認証情報、または開発者アプリケーション情報(コンシューマーキーを含む)を人々に直接提供するよう求めたりしてはなりません。** サービスと X 上の人々をリンクさせる認証ツールとして、[Sign-in with X](/fundamentals/authentication/guides/log-in-with-x) の使用を推奨します。
# X 開発者 PPU 契約
Source: https://docs.x.com/ja/developer-terms/ppu-agreement
X 開発者 Pay-Per-Use 契約は、有料の X API サービスにおけるクレジットの購入および利用条件を、請求および利用ルールを含めて規定します。
「Pay」をクリックし、Paid Services で利用するクレジットを購入すること、または Licensed Material にアクセスもしくは利用することにより、あなたは本契約の条件に同意するものとします。クレジットは、別途明記されない限り有効期限がなく、法律で要求される場合を除き、譲渡不可かつ返金不可です。クレジットの購入には確認済みの電話番号が必要です。
本 X 開発者 PPU 契約(以下「**本契約**」)は、あなた(本契約において「**あなた**」と呼びます)と X との間の拘束力のある法的合意であり、Paid Services(以下に定義)を含む Licensed Material(以下に定義)へのアクセスおよび利用を規定します。
Licensed Material(以下に定義)にアクセスまたは利用すること、本契約の条件を承諾するボタンをクリックすること、または Paid Services のクレジットを購入することにより、あなたは本契約の条件に拘束されることに同意します。本契約の条件を理解していない、またはその一部を承諾しない場合、Licensed Material を利用またはアクセスすることはできません。X との拘束力ある契約を締結できる法定年齢に達していない場合、または適用される法律により Licensed Material の利用もしくは受領を禁じられている場合、Licensed Material を利用すること、または本契約を承諾することはできません。Paid Service を購入して利用するには、次のいずれかに該当する必要があります: (i) 18 歳以上であるか、居住する法域の法律で定められた成年年齢以上であること、(ii) その Paid Service を購入して利用することについて親または保護者の明示的な同意があること。あなたが親または法定後見人であり、自分の子供(または後見の対象である子供)が Paid Service を購入または利用することを許可する場合、あなたは本契約の条件があなたに適用されることに同意し、本契約を遵守し、Paid Services における子供の活動および子供が本契約の条件を遵守することについて責任を負います。いずれの場合も、[**X 利用規約**](https://x.com/tos) の Who May Use the Services セクションに記載されているとおり、X 利用規約で定義される「Services」を利用するには少なくとも 13 歳以上である必要があります。企業、組織、政府、その他の法人を代表して本契約を承諾する場合、または Licensed Material を利用する場合、あなたはその企業、組織、政府、その他の法人を本契約に拘束する権限を有することを表明・保証するものとし、この場合、本契約で使用される「あなた」および「あなたの」という文言はそのような法人を意味します。本契約の条件に同意しない場合、あなた(およびあなたの人員)は Licensed Material にアクセスしたり利用したりすることはできません。
I. **定義**。
本契約において、以下の定義が適用されます:
1. **「クレジット」** とは、Paid Services の利用を可能にするためにあなたが購入する仮想単位を意味し、各 API 呼び出しまたはアクションごとに Pricing Schedule に基づく特定の数のクレジットが差し引かれます。クレジットは、法律で要求される場合を除き返金不可であり、譲渡不可であり、別途明記されない限り有効期限はありません。
2\. **「Developer Site」** とは、[**https://developer.x.com**](https://developer.x.com/) にある X の開発者サイトを意味します。
3\. **「ダイレクトメッセージ」** とは、X アプリケーション上で、あるユーザーが X のダイレクトメッセージ機能を使用して他の特定のユーザーに送信するプライベートメッセージを意味します。
4\. **「知的財産権」** とは、著作権、著作者人格権、特許権、商標権、およびその他の知的財産権または類似の権利(登録の有無を問わず)を、世界中で意味します。
5\. **「Licensed Material」** とは、単独または集合的に、X API および X コンテンツを意味します。
6\. **「Paid Service(s)」** とは、X から購入し、料金ページに詳述されている呼び出しや機能の利用に応じてアカウントから差し引かれるクレジットの控除と引き換えにアクセスする Licensed Material の機能や機能性を意味します。本契約で別途定めがない限り、「Licensed Material」への言及はすべて Paid Service(s) を含むものと解釈されます。
7\. **「Payment Portal」** とは、あなたが Licensed Material の利用にオプトインし、Paid Services のクレジット購入を管理し、Paid Services の支払い方法を管理し、「Auto-Recharge」(第 VII.F 節を参照)を有効化し、アカウント情報を更新するために提供されるオンラインポータルを意味します。
8\. 「**Services**」とは、X コンテンツを表示するか、Licensed Material をその他の方法で利用するあなたのサービス、ウェブサイト、アプリケーション、その他の提供物(調査を含む)を意味します。
9\. **「投稿」** とは、X アプリケーションを介して配信される短形式のテキストおよびマルチメディアベースのメッセージを意味します。
10\. **「Pricing Schedule」** とは、API 呼び出しまたはアクションごとの現在の料金リストを意味し、[https://developer.x.com/#pricing](https://developer.x.com/#pricing) で入手できます。
11\. **「X」** とは、(a) あなたの主要な事業所在地が欧州連合、EFTA 加盟国、および英国以外にある場合は、X Corp.(865 FM 1209, Building 2, Bastrop, TX 78602, USA)、または (b) あなたの主要な事業所在地が欧州連合、EFTA 加盟国、または英国内にある場合は、X Internet Unlimited Company(One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland)を意味します。
12\. **「X API」** とは、X のアプリケーションプログラミングインターフェース(それぞれを「API」)、ソフトウェア開発キット(それぞれを「SDK」)、および Developer Site を通じて X が提供する関連ツール、ドキュメンテーション、データ、テクノロジー、コード、その他の資料を意味します。
13\. **「X アプリケーション」** とは、一般に「X」として知られている X のリアルタイム情報サービスを意味し、X が現在ウェブサイトおよび X が所有・運営・管理するモバイルアプリケーション、ソーシャルプラグイン、およびアプリケーションプログラミングインターフェースにおいて提供するサービスを含みます。
14\. **「X コンテンツ」** とは、投稿、各投稿に対して生成される一意の識別番号、X エンドユーザーのプロフィール情報、および X API またはその他の X によって承認された手段を通じてあなたに提供される他のデータおよび情報、ならびにそれらのコピーおよび派生物を意味します。
15\. **「X マーク」** とは、Developer Site を含め、本契約に従って利用するためだけに X があなたに提供する X の名称、商標、およびロゴを意味します。
16\. **「ユーザー」** とは、あなたの Services の訪問者、ユーザー、または顧客を意味します。
**II. X API および X コンテンツ。**
**A. X からのライセンス。** 本契約および該当する Incorporated Developer Terms(以下に定義)の条件を遵守することを条件として、X はここに、以下の目的にのみ限定した、非独占的、ロイヤリティフリー、譲渡不可、サブライセンス不可、かつ取消可能なライセンスをあなたに付与します:
1\. X から明示的に承認された範囲で、X API を使用して X コンテンツを Services に統合するか、X コンテンツの分析を実施すること;
2\. 本契約で許可される範囲で、Services を通じてユーザーに X コンテンツを合理的な量だけコピー・表示すること;
3\. Services 上での表示のために書式を整える目的でのみ X コンテンツを変更すること;および
4\. 本契約に定めるところに従い、X アプリケーションを X コンテンツの出典として帰属表示するために X マークを利用し表示すること。
**B. X へのライセンス。** あなたはここに、[**埋め込み投稿**または**埋め込みタイムライン**](https://publish.x.com)を使用して X コンテンツを表示するあらゆるウェブページまたはアプリケーションに、ウェブスパイダーおよび/またはクローラーを含む任意の手段でアクセスし、インデックス化し、キャッシュするための、非独占的、ロイヤリティフリー、譲渡不可、かつサブライセンス不可の取消可能なライセンスを X に付与します。
**C. 組み込まれた条件。** Licensed Material へのアクセスおよび利用は、以下の追加の条件およびポリシー(総称して「**Incorporated Developer Terms**」)にも従い、これに準拠する必要があります:
1\. [**X 開発者ポリシー**](https://docs.x.com/developer-terms/policy);
2\. [**API 制限された利用ルール**](https://docs.x.com/developer-terms/restricted-use-cases);
3\. [**X ルール**](https://help.x.com/rules-and-policies/x-rules);
4\. X コンテンツの表示に関しては、[**表示要件**](https://docs.x.com/developer-terms/display-requirements);
5\. X マークの利用および表示に関しては、[**X ブランドガイドライン**](https://about.x.com/who-we-are/brand-toolkit);および
6\. あなたのアカウントで自動化されたアクションを行うことに関しては、[**Automation Rules**](https://help.x.com/rules-and-policies/x-automation)。
**III. 利用に関する制限。**
**A. リバースエンジニアリングおよびその他の制限。** あなたは、以下を行わず、また試みず(他者による行為も許可しません): (a) X API をリバースエンジニアリング、逆コンパイル、逆アセンブル、または翻訳することや、X API またはその一部に含まれるかまたはその基礎となるソースコード、営業秘密、ノウハウを導き出そうとすること;(b) X API の機能または機能性、あるいは X API の監視メカニズムに干渉、変更、混乱、無効化を行うこと;(c) Licensed Material を利用またはアクセスして、X アプリケーションの代替または類似のサービスや商品を作成しようとすること、または作成すること;(d) 本契約で明示的に許可される場合を除き、Licensed Material の全部または一部を第三者に販売、賃貸、リース、サブライセンス、配布、再配布、シンジケート、派生物の作成、譲渡、その他の移転、またはアクセス提供すること;(e) X API をサービスビューロー、レンタル、またはマネージドサービスとして提供すること、または他の個人もしくは事業体に、X API へのリンクを作成させたり、他のサーバー、ワイヤレスもしくはインターネットベースのデバイス上で X API を「フレーム」または「ミラー」させたり、その他の方法で X API へのトークン、キー、パスワード、その他のログイン認証情報を第三者に利用可能にすること;(f) Licensed Material を違法、非承認、その他不適切な目的で利用すること;(g) Licensed Material を利用して個々の X ユーザーの非公開情報を導き出したり取得したりすること;(h) X アプリケーション、X API、またはその中に含まれる X コンテンツの完全性やパフォーマンスに干渉または妨害すること;(i) X コンテンツから専有的な注記やマークを削除または改変すること;(j) X アプリケーション、X API、X コンテンツ、または関連するシステムやネットワークへの不正アクセスを試みること;(k) 基盤モデルまたはフロンティアモデルをファインチューニングまたはトレーニングするために X API または X コンテンツを利用すること;または (l) X アプリケーションの外部でユーザーを広告のターゲットにする、または広告を配信する目的で、X コンテンツを単独または第三者のデータと組み合わせて利用したり、そこから派生する分析を利用したりすること。
**B. 商用利用の制限。** Services が「非商用」に指定されている場合、Licensed Material を Commercial Use(以下に定義)してはなりません。Commercial Use の制限は、公式に登録された非営利団体または NGO には適用されない場合があります。「Commercial Use」とは、Licensed Material の任意の利用または X API へのアクセスであって、(a) 事業(すなわち、商品またはサービスを通じて収益を得ることを主目的とする事業体)によって、または事業のために行われるもの、あるいは (b) 収益化される商品またはサービスの一部として(たとえば、ウェブサイト広告、ライセンス料、アプリ内プロモーション、スポンサーシップなど)行われるものを意味します。
**C. 監視または計測なし。** これに反する定めにかかわらず、以下の情報は、非商用の内部目的(たとえば、Services の機能性を改善するため)にのみ使用できます: (a) X アプリケーションの集計ユーザーメトリクス(X アプリケーションのアクティブユーザーまたはアカウント数など);(b) X アプリケーションのレスポンス性;および (c) X API のパフォーマンスに関して分析、利用、または関連することから導き出された結果、利用統計、データ、その他の情報(集計または個別)。そのようなすべての情報は、Confidential Information(以下に定義)です。
**D. レート制限。** あなたは、X API のアクセス、コール、または利用に関する制限(「Rate Limits」)を超えたり回避したりしようとはせず、または合理的なリクエスト量を超え、過剰または濫用的な利用を構成する方法、あるいは本契約に準拠しない方法で X API を利用してはなりません。API 呼び出しおよびリクエストは、[https://developer.x.com/#pricing](https://developer.x.com/#pricing) で入手可能な Pricing Schedule に指定されているとおり、あなたの残高からクレジットを差し引きます。クレジット残高が呼び出しに不足している場合、クレジット残高が当該リクエストの控除を可能にするに十分になるまで、リクエストは拒否されます。あなたが Rate Limits、X API の利用を制限するための管理策を超えたり回避しようとしたり、あるいはその他の方法で本契約に違反して Licensed Material を利用していると X が合理的に判断した場合、Licensed Material を利用する能力が一時的に停止されるか、恒久的にブロックされる可能性があります。X は、Licensed Material および X アプリケーションを改善するため、また本契約および Incorporated Developer Terms へのあなたの準拠を確保するために、X API の利用状況を監視することがあります。あなたは、利用に関連する追加情報についての X の要求に応じることに同意します。X はいつでも Licensed Material の利用をレビューできます。X が X API へのアクセスを付与すること、または Licensed Material の利用を許可することは、あなたの利用の承認、あるいは本契約および X のポリシーに準拠する利用を要求する権利の放棄または制限とはみなされません。行われた支払いは返金不可ですが、X は、独自の裁量で、未使用のクレジットを本契約に準拠する利用に使用することを許可することができます。
**E. 位置情報データ。** あなたは、また他者にも、X コンテンツに含まれる位置情報データおよびその他の地理情報を、それが付随する X コンテンツと連動する場合を除き、集約、キャッシュ、または保存させてはなりません。位置情報データおよび地理情報は、X コンテンツによってタグ付けされた場所を識別するためにのみ利用できます。
**F. X マークの利用。** X マークをあなたの登録企業名、ロゴ、またはサービス名や商品名に含めてはなりません。X マークの派生物を作成したり、X との推奨、支援、または関連を作り出し、または合理的に示唆する形で X マークを利用したりしてはなりません。X マークのすべての利用およびその利用から生じるすべての信用は、X の利益に帰属します。Licensed Material から専有的な注記や X マークを削除または改変してはなりません。
**G. セキュリティ。** あなたは X API のセキュリティを維持し、X API へのトークン、キー、パスワード、その他のログイン認証情報を第三者に利用可能にしてはなりません。ウイルス、ワーム、その他の有害なコードや資料によるアクセスを含め、X API の機能や機能性への不正アクセスや利用を防ぐために業界標準のセキュリティ対策を利用します。X コンテンツについては、業界標準の組織的および技術的な保護策を用いて機密性を保ち、不正アクセスから安全に守るとともに、同種のデータを保管する際に用いる注意と少なくとも同等以上の注意をもって扱うものとします。Licensed Material に関するセキュリティの侵害または潜在的な脆弱性を知った場合または疑った場合、直ちに X に通知し、調査に協力し、必要な通知の支援を行い、X から合理的に要求される情報を提供します。Licensed Material へのあなたのアクセスから生じるそのような侵害または潜在的な脆弱性を速やかに是正します。
**H. デジタルサービス法。** 本契約における反対の定めにかかわらず、デジタルサービス法(規則 (EU) 2022/2065)(以下「DSA」)第 40 条に記載された手続きに従って Licensed Material へのアクセスを提供される場合、Licensed Material のアクセスおよび利用は、欧州連合内の体系的なリスクの検出、識別、および理解に貢献する研究を行うことのみに、および DSA に基づく X の義務を遵守するために必要な範囲内でのみ制限されます。Licensed Material のそのような利用は、本契約第 III(B) 節に記載されているとおり非商用です。X API を通じて取得した Licensed Material(その派生物を含む)を、承認された申請内で指定された者以外の個人または団体に開示、複製、ライセンス供与、またはその他の方法で配布してはなりません。ただし、(i) 情報が第 40 条に記載された「認定研究者」の地位および手続きに従って Digital Services Coordinator または DSA によって具体的に許可された他の当事者に開示される場合、または (ii) 法律により開示が要求される場合は除きます。
**I. トークン。** X は、X アプリケーション上の機能または機能性へのアクセスや利用を可能にするトークンを含め、あなたに提供するトークンの数を制限することがあります。
**J. 本契約に基づく利用レベル。** X は、いつでも本契約に基づく Licensed Materials の利用をレビューし、その利用を停止または終了することがあり、X が Licensed Materials の継続利用の提案を検討するために、Enterprise アクセス([**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction) に記載)の申請を提出するよう要求することができます。
**K. I-Framing の禁止:** いかなる状況においても、Licensed Material、X コンテンツ、X API、X アプリケーションの要素を、あなたの Services または他のプラットフォーム上で、iframe、インラインフレーム、または類似の埋め込みメカニズム内に埋め込んだり、表示したり、その他の方法で組み込んだりしてはなりません。この禁止は絶対的であり、表示、統合、または再配布のために X コンテンツをフレームで囲む試みを含みますが、これに限定されません。この条項への違反は、第 VII.I 節に記載されているとおり、開発者契約および Licensed Material(X API、X Data License、Developer Console など)へのアクセスの即時終了につながる可能性があります。
**L. セルフサーブでの利用。** Pay-Per-Use、Basic、および Pro プラン([developer.x.com](https://developer.x.com) に記載)は、趣味の開発者、商用プロトタイピング、初期開発、初期段階の X プロダクト統合、および限られた数のエンドユーザーをサポートするアプリケーションを対象として設計されています。この範囲を超えて X API を利用する場合、Enterprise プラン([developer.x.com](https://developer.x.com) に記載)に申請(または既に加入)する必要があります。
**M. 商用利用:** 趣味のプロジェクト、商用プロトタイピング、初期開発、初期段階の X プロダクト統合、または限られた数のエンドユーザーを対象としたアプリケーションの範囲を超えて X API を利用する場合、Enterprise プラン(developer.x.com に記載)に申請(または既に加入)する必要があります。
**IV. 更新および削除。**
**A. 更新。** X は、Licensed Material のいかなる機能や機能性も、全部または一部を随時更新、変更、または中止することがあります(それぞれを「Update」といいます)。あなたは Licensed Material の最新バージョンを実装・利用し、Update の結果として必要となる Services への変更を、自己の負担で行うものとします。Update は、Services が X API にアクセスまたは通信する方法、あるいは X コンテンツを表示する方法に悪影響を与えることがあります。X は、Update の結果として生じるいかなる損害についても責任を負いません。
**B. 削除。** X コンテンツが削除、保護されたステータスの取得、またはその他の方法で X アプリケーションから停止、差し止め、変更、または削除された場合(位置情報の削除を含む)、あなたは、X または該当する X ユーザーの書面による要求から可能な限り速やかに、いかなる場合でも 24 時間以内に、その X コンテンツを削除または変更(該当する場合)するあらゆる合理的な努力を行うものとします。ただし、法律または規制によって禁止されておらず、かつ X の明示的な書面による許可がある場合を除きます。
**V. 所有権、ベータ、およびフィードバック。**
**A. 所有権。** 本契約で明示的に別途規定されている範囲を除き、いずれの当事者も、他方当事者が所有またはライセンスを受ける知的財産権について、いかなる権利、権原、または利益も取得しないものとします。Licensed Material はライセンスされるものであり、販売されるものではなく、X(または該当する場合はそのライセンサーまたは X アプリケーションのユーザー)は、本契約で明示的に付与されていないすべての知的財産権を含むすべての権利を保持し留保します。あなたは、X の所有権と矛盾するいかなる行為も行いません。これには、X の X マークの所有権への異議申立、本契約で付与されたライセンスの有効性への異議申立、または本契約で具体的に承認された場合を除いて X マークをコピーまたは利用することが含まれますが、これに限定されません。あなたが法律の運用またはその他の方法により X マークまたは混同を招くほど類似したマークに関する何らかの権利を取得した場合、X に費用をかけず直ちにそれらの権利を X に譲渡します。
**B. ベータ。** X は、随時、一般に利用可能となっていないアルファ、ベータ、リサーチスタディ、パイロット、マーケティングサービス、その他のプログラム(それぞれ「Beta」)への早期アクセスを提供することがあります。Beta は Confidential Information とみなされます。Beta への参加は自己責任で行われ、追加の要件の対象となる場合があり、既存または将来のプログラム、商品、および/またはツールの調査、分析、検証において X を支援する場合があります。
**C. フィードバック。** X は、X、Licensed Material、Beta、または X の他の商品もしくはサービスに関してあなたが X に提供するフィードバック、コメント、または提案(以下「Feedback」)を、あなたまたは第三者に対する報酬または義務なしに、いかなる方法でも自由に利用できます。Feedback は Confidential Information とみなされます。あなたはここに、Feedback に関するすべての権利、権原、および利益を X に不可逆的に譲渡します。
**VI. 秘密保持。**
あなたは、Licensed Material に関連する非公開情報、ソフトウェア、および仕様(以下「Confidential Information」)にアクセスを付与される場合があります。あなたは、本契約に基づく権利の行使のために必要な範囲でのみ Confidential Information を利用できます。X の事前の書面による同意なしに、Confidential Information を第三者に開示してはなりません。Confidential Information を不正な利用、アクセス、または開示から、同種の自己の秘密情報を保護するために利用するのと同じ方法で、いかなる場合でも合理的な注意より低くない注意をもって保護します。
**VII. 期間、クレジット購入条件、クレジット控除、停止、および終了。**
**A. 期間。** 本契約の期間は、(i) 本契約の条件を承諾した日、または (ii) Licensed Material のいずれかへのアクセスもしくは利用を開始した日のいずれか早い方から開始し、以下に記載されているとおり早期に終了しない限り、Licensed Material のアクセスおよび利用を停止するまで継続します。
**B. クレジット購入条件。** Licensed Material の一部として提供される Paid Services は、[https://developer.x.com/#pricing](https://developer.x.com/#pricing)、Developer Site および Payment Portal に記載されているとおり、X API 利用を含む機能、便益、またはサービスの利用に応じて差し引かれるクレジットの購入を通じて利用可能となります。Paid Service を購入する場合、Payment Portal を介して適用される料金を前払いで支払うことにより、まずクレジットを事前に購入します。あなたのクレジット残高は購入後に更新され、Paid Services を利用するにつれて差し引かれます。Paid Services へのアクセスを可能にするため、必要に応じて追加のクレジットを購入する必要があります。第 VII.D 節に詳述されるオプションの「Auto-Recharge」機能を有効化しない限り、クレジット購入は繰り返し行われません。Payment Portal 経由でクレジットを購入すると、本契約の条件に明示的に同意し、請求を承認したことになります。X は、残高が低くなった場合の通知を提供することがあります。クレジットの価格および控除率は、Pricing Schedule に定めるとおり随時変更されることがあります。X は、価格の重大な変更について合理的な事前通知を提供します。この通知は Developer Site または Payment Portal を介して提供される場合があります。価格変更は、将来の購入および控除に適用されます。価格変更に同意しない場合、クレジットの購入と Paid Services の利用を停止できます。クレジットは、別途明記されない限り有効期限がなく、法律で要求される場合を除き、譲渡不可かつ返金不可です。
**C. クレジットの控除:** Paid Services へのアクセスには、アカウント内に十分なクレジットが必要です。各 API 呼び出しもしくはリクエスト、または Pricing Schedule に指定されているその他の機能もしくはサービスの利用は、Pricing Schedule に指定された率に基づいて残高からクレジットを差し引きます。控除率は変動する場合があり、Pricing Schedule は変更されることがあります。X は、各呼び出しもしくはリクエスト、または Pricing Schedule に指定されているその他の機能もしくはサービスの利用の時点でクレジットを差し引くこと、および残高が不足している Paid Services を拒否することを目指します。この場合、Paid Service を利用可能にするために、追加のクレジットを購入する必要があります。マイナスのクレジット残高を維持することはできません。Paid Services へのアクセスを維持するために、クレジット残高を監視することはあなたの責任です。
**D. 利用に関する紛争**: クレジット控除に誤りがあると思われる場合、[請求サポート](https://docs.x.com/forms/billing-support) を通じて、争いのある控除から 30 日以内に X に通知する必要があります。X は調査を行い、誤りが確認された場合、クレジット残高をそれに応じて調整します。調整は X の独自の裁量で行われ、本契約の対象となります。
**E. 支払い条件。** X は、Paid Service、デバイス、オペレーティングシステム、地理的な場所、その他の要因によって異なる支払いオプションを提供することがあり、これらは随時更新される場合があります。これらの支払いオプションには、第三者の支払処理業者(以下「Payment Processor」)を利用したウェブ支払いが含まれることがあります。Paid Service にアクセスする際、あなたは以下に同意します: (i) クレジットに対する記載された価格を、税金、追加料金、クレジットカード手数料、銀行手数料、外貨取引手数料、外国為替手数料、通貨変動に関連する追加金額とともに支払うこと;および (ii) 特定の支払い方法の利用に関して Payment Processor によって課される該当する利用規約、プライバシーポリシー、その他の法的合意または制限(追加の年齢制限を含む)を遵守すること。料金はクレジット購入時に請求されます。クレジット残高を監視し、銀行、クレジットカード、デビットカード、および/または他の支払い情報が常に最新、完全、正確であることを確認することは、あなたの責任です。Payment Processor を介して Paid Service の支払いを行う場合、X は、いつ支払いが行われたか、購入したプラットフォーム、その他の情報など、あなたの取引に関する情報を受け取ることがあります。X は、Payment Processor、あなたの銀行、あなたのクレジットカード会社、または任意の支払いネットワークによる誤りまたは遅延について責任を負いません。X への支払いはすべて、本契約で別途明示的に規定されている場合、または法律で要求されている場合を除き、返金不可能です。
**F. オプションの Auto-Recharge 機能。** Developer Console を介して「auto-recharge」機能にオプトインすることができ、これによりクレジット残高が auto-recharge ツールで設定したしきい値を下回った際に、X が保存された支払い方法に対してユーザー選択の金額を自動的に請求することを承認できます。請求には、第 VII.E 節に従ってその金額に対する該当する税金と料金が含まれます。この機能は Payment Portal を通じていつでも変更または無効化することができ、有効化することにより、しきい値に達するたびに X がその第三者 Payment Processor を介して選択した金額を請求することに同意します。ただし、失敗した請求(たとえば、無効な支払い方法による)はクレジットの追加を妨げます。auto-recharge を有効化しても、Paid Services への中断のないアクセスは保証されません。X が残高不足や auto-recharge イベントに対して提供する通知にかかわらず、あなたはクレジット残高を監視する責任を引き続き負い、auto-recharge の請求は法律で要求される場合を除き返金不可です。
**D. 税金および料金。** すべての料金は、現在有効な、または将来施行または課される、取引、Licensed Material の提供、または X コンテンツの提供に対する税金および類似の料金を除外しています。これには、売上税、使用税、または付加価値税、商品サービス税、消費税、関税、料金、または類似の料金が含まれます。これらの税金には、VAT、GST、売上税、源泉徴収税、その他該当する税金が含まれる場合がありますが、X の純利益のみに基づく税金は除外されます。あなたは、そのような税金、関税、および料金のすべての支払い、および当該金額の支払いから生じる関連する罰金や利息に責任を負います。加えて、特定の法域で X が負担するデジタルサービス税(「DST」)または類似の法域固有の税金や規制料金に関連するコストを回収するために、追加料金が請求される場合があります。この追加料金は、該当する場合、請求書に別項目として表示され、X の独自の裁量で決定される該当する料金の割合として計算されます。X は、税率もしくは料率の増加、または関連する管理コストに対応して、事前の通知なしにいつでもこの追加料金を調整することがあります。あなたの所在地によっては、X は Paid Services の購入から生じる取引税に関連する情報の収集および報告に責任を負う場合があります。あなたは、X が税金の徴収および報告義務を果たすために、あなたのアカウントおよび個人情報を関連する税務当局に提供することを許可します。
**E. 返金および Paid Services の停止。** さらに API 呼び出しを行わないことによって、いつでも Paid Services の利用を停止することができます。未使用のクレジットは、法律で要求される場合を除き、購入または使用されたクレジットに対する返金なしに、返金不可かつ譲渡不可です。クレジット購入は前払いで、返金不可です(法律で要求される場合を除く)。適用される法律(たとえば、以下の撤回権)に従ってのみ、未使用のクレジットに対する返金を要求できます。以下に記載されているとおり、法律により撤回する権利がある場合を除き、すべての取引は最終的です。
**1. EU または UK に居住するユーザーの撤回権および返金。** クレジット購入から 14 日以内(以下「Withdrawal Period」)であれば、いかなる理由も示さずにクレジット購入から撤回する法的権利があります。この権利を行使するには、Withdrawal Period が満了する前に、[請求サポート](https://docs.x.com/forms/billing-support) に撤回の明確な声明を送信することにより、撤回する決定を X に通知する必要があります。Withdrawal Period 内に撤回し、クレジットを一切使用していない場合、X は撤回通知を受領してから 14 日以内に、購入に使用した同じ支払い方法を使用して、購入したクレジットに対して支払われた全額(該当する税金や料金を含む)を返金します。ただし、明示的に別途合意しない限りです。
ただし、あなたは、Withdrawal Period 中にクレジットを使用した場合(たとえば、API 呼び出しやリクエストを行うことによって)、Paid Services が事前の明示的な同意とその使用時に撤回権が失われるという承認とともに開始されたため、撤回する権利を放棄することを明示的に承諾し同意します。Withdrawal Period 中に購入したクレジットの一部のみを使用し、その後撤回権を行使する場合、X は、[https://developer.x.com/#pricing](https://developer.x.com/#pricing) で入手可能な Pricing Schedule に基づいて計算された、未使用のクレジットに相当する金額を返金します。
**2. 台湾に居住するユーザーには撤回権がありません。** 台湾に居住する消費者である場合、消費者保護法に基づき、クレジット購入から 7 日間の撤回期間の権利がある場合がありますが、クレジットを使用した場合はこの限りではなく、撤回する権利は失われます。この権利を行使するには、購入日から 7 日以内に [請求サポート](https://docs.x.com/forms/billing-support) で X に通知する必要があります。未使用のクレジットに対する返金は、適用される法律に従って処理されます。
**F. クレジットは X アカウント間で譲渡不可。** クレジットの各購入は単一の X アカウントに適用されます。つまり、購入はクレジットを購入した際に使用していたアカウントのみに適用され、アクセスまたは管理する他のアカウントには適用されません。複数のアカウントを保有または管理し、各アカウントで Paid Services へのアクセスを望む場合、各アカウントで個別に必要なクレジットを購入する必要があります。他者があなたの X アカウントを使用して、その人が注文していない Licensed Material にアクセスすることを許可してはなりません。米国財務省の外国資産管理局が管理する制裁を含む経済制裁、または他の該当する制裁当局によって、米国人が取引することを許可されない者(「Prohibited Person」)である場合、クレジットを購入したり、Licensed Material を利用したりしてはなりません。これには、次の国および地域に居住する、国民である、または通常居住する者が含まれますが、これに限定されません: キューバ、イラン、ウクライナのクリミア地域、北朝鮮、シリア。あなたは、Prohibited Person ではないことを表明・保証します。
**G. 制限および義務。** Licensed Material を自国で合法的に利用でき、該当するクレジット購入、Paid Service、または Licensed Material について X がサポートする国に居住している場合にのみ、クレジットを購入・利用し、Licensed Material を利用することができます。X は、独自の裁量で、特定の国での Licensed Material へのアクセスまたはクレジット購入能力を制限することがあります。X は、サポートする国のリストを随時変更する権利を留保します。X は、クレジットの販売または Paid Services へのアクセスを拒否したり、Paid Service または Licensed Material の販売もしくは利用をキャンセルまたは中止したりする権利を、独自の裁量で留保します。
**H. 停止。** X は、通知なしに直ちに Licensed Material へのアクセスおよび利用を停止することがあります。 (a) X が合理的に以下を判断する場合:(i) あなたによる Licensed Material の利用が Licensed Material に損害を与えるか、過度の負担を与える;(ii) 本契約に違反した;(iii) X に対してリスクまたは可能性のある法的責任を生じさせる;(iv) X によるあなたへの Licensed Material の提供が、商業的にもはや実行可能でない;(b) 長期間の非活動;(c) 管轄権のある裁判所、規制当局、または法執行機関から要求または指示された場合;または (d) Paid Services の支払いを怠った場合。X は、そのような停止の結果として生じるいかなる損害についても責任を負いません。
**I. 終了。** X は、独自の裁量でいかなる理由でも本契約を終了することがあります。X によるそのような早期終了は、直ちに有効となります。あなたが本契約の条件に違反した場合、X は理由あってあなたへの通知後直ちに本契約を終了することができ、あなたはいかなるクレジットに対する返金も受け取りません。Developer Site で Paid Services へのアクセスまたは Licensed Material の利用をキャンセルできます。あなたはいかなるクレジットの返金も受ける権利がなく、また未使用のクレジットの利用の権利もありません。本契約の終了時: (a) 本契約で付与されたすべてのライセンスは直ちに失効し、あなたはあらゆる Licensed Material の利用を停止する必要があります;および (b) あなたが所持するあらゆる形式および種類のメディア上のすべての Licensed Material およびそのコピーを恒久的に削除する必要があります。X の要求に応じて、いかなる理由でも、速やかに(いかなる場合もそのような要求から 10 営業日以内に)、本節の前述の (b) の規定への準拠の証拠(例: 削除確認のスクリーンショット)を提供します。本契約の当事者は、本契約で許可される本契約の終了のみから生じるいかなる損害についても、相互に責任を負いません。
**VIII. コンプライアンス監査。**
X または相互に合意した第三者の代理人(秘密保持義務を負う)は、本契約の履行に関連するあなたの管理下または所持下にある記録を、合理的な事前通知に基づき、通常営業時間内の合理的な時間に、監査に先行する 2 年間の本契約の遵守および X に支払われる料金の検証を目的として、検査および監査する権利を有します。X は、不遵守の合理的な理由がない限り、12 か月ごとに 1 回を超えて監査権を行使しないものとし、その監査はあなたの事業活動を不合理に妨げないものとします。あなたはそのような監査に十分な協力と支援を提供し、所持するすべての Licensed Material、該当する契約、および記録へのアクセスを提供します。前述の一般性を制限することなく、監査の一部として、X は、あなたの現在の Licensed Material の展開状況をリストした、権限のある代表者によって署名された書面による報告書を要求し、あなたはこれを提供することに同意します。監査の完了後 30 営業日以内に、そのような監査によって明らかになった不足額を X に支払います。加えて、そのような監査があなたによる 5% 以上の不足支払いを明らかにした場合、そのような監査の合理的な費用も X に払い戻します。本節の要件は、本契約の終了後 1 年間存続します。
**IX. 免責。**
適用される法律で許容される最大限の範囲において、Licensed Material は「現状のまま」「所在のまま」、すべての欠陥とともにあなたに提供され、X は、明示、黙示、法定、その他を問わず、商品性、非侵害、特定目的への適合性、および本契約、取引の過程、または商慣行から生じる保証または条件を含む、あらゆる保証を否認します。X は、Licensed Material、または本契約に基づき提供される他の X 商品もしくはサービスがあなたのいかなる要件も満たすこと、あるいはそのような Licensed Material または他の商品もしくはサービスの利用がエラーフリー、中断なし、ウイルスなし、または安全であることを保証しません。あなたは、Licensed Material の利用および提供するコンテンツについて責任を負います。この保証否認は、一部の法域では有効でない場合があり、法律に基づき放棄または否認できない保証権をあなたが有する場合があります。
**さらに、あなたは、Paid Services が「現状のまま」および「利用可能な範囲」で提供されることを理解し同意します。**
**X. 補償。**
あなたは、(a) 本契約と矛盾する方法での Licensed Material の利用、または (b) あなたの Services のパフォーマンス、プロモーション、販売、配布から生じる範囲で、第三者による X に対するあらゆる手続、要求、請求、訴訟(製造物責任請求を含みますが、これに限定されません)に対して、自己の費用で X を防御し、あらゆる責任、損害、費用(合理的な弁護士費用を含みますが、これに限定されません)から X を補償します。X が本節に基づく補償または防御をあなたに求める場合、X は、補償または防御を求める X に対して提起された請求について、速やかにあなたに書面で通知します。X は、自らが選定する弁護士による請求の防御の完全な支配を引き受けることができます。X の権利に影響を及ぼす、X による過失の認定を構成する、またはいかなる方法でも X を拘束する第三者との契約を、X の事前の書面による同意なしに締結してはなりません。X がそのような請求の防御の支配を引き受けた場合、X はあなたの事前の書面による承認なしに、あなたからの支払いを必要とするそのような請求を和解させません。
**XI. 責任の制限。**
いかなる場合でも、X は、あなたまたはユーザーに対して、間接、特別、付随的、模範的、懲罰的、または結果的損害、あるいは本契約に起因または関連する使用、データ、事業、営業権、または利益の損失または損害について責任を負いません。いかなる場合も、本契約に基づくあらゆる請求に対する X の総合的な責任は 50 米ドル (\$50.00) を超えないものとします。前述の制限、除外、および免責は、そのような責任が契約、保証、不法行為、厳格責任その他に基づく請求に起因するかどうか、および X がそのような損失または損害の可能性について通知されたかどうかにかかわらず適用されます。適用される法律が本規定の責任のいかなる制限も禁止している場合、当事者は、その制限が適用される法律に適合するように修正されたとみなされることに同意します。当事者は、本規定に定める責任の制限が合意されたリスクの配分であり、いかなる限定的救済策の本質的目的の失敗にもかかわらず適用されることに同意します。
**XII. 契約の更新。**
X は、本契約または Incorporated Developer Terms を随時更新または修正することがあります。あなたは、定期的に Developer Site で更新を確認します。X は、これらのサイトで更新された条件を掲示すること、サービス通知を介して、または他の適切な手段(たとえば、アカウントに関連付けられたメールアドレスへのメール)により、これらの条件への重大な修正について通知します。変更は遡及的ではなく、Developer Site で利用可能な本契約の最新バージョンが、Licensed Material へのあなたのアクセスおよび利用、および対応する取引を規定します。Licensed Material への継続的なアクセスまたは利用は、そのような更新および修正への拘束力ある承諾を構成します。
**XIII. 紛争解決および集団訴訟の放棄。**
**A. 本節は、あなたが欧州連合、EFTA 加盟国、または英国以外に居住している場合(米国に居住している場合を含む)にのみ適用されます。この節を注意深くお読みください。あなたの法的権利、特に裁判所に訴訟を提起する権利に重大な影響を与える可能性があります。**
**1. 準拠法および裁判管轄地の選択。** テキサス州法(その抵触法規定を除く)は、当事者間の反対の合意にかかわらず、本契約およびあなたと X との間で生じるいかなる紛争にも適用されます。本契約に関連するすべての紛争、本契約に起因もしくは関連する紛争、請求、または論争、Licensed Material のマーケティング、および/または Licensed Material への参加は、テキサス州北部地区の米国地方裁判所または米国テキサス州タラント郡に所在する州裁判所においてのみ提起されるものとし、あなたはこれらの法廷における対人管轄に同意し、不便な法廷に関する異議を放棄します。前述にかかわらず、X が、独自の裁量で、あなたに対して有する請求、訴因、または紛争を、請求について管轄権と裁判地を有するあなたが居住する国の管轄裁判所に提起することができることに同意します。
米国において公務上 Licensed Material を利用する連邦、州、または地方政府機関であり、法的に上記の準拠法、裁判管轄、または裁判地条項を受け入れることができない場合、それらの条項はあなたに適用されません。そのような米国連邦政府機関については、本契約およびそれに関連するいかなる訴訟も、米国法(抵触法への参照なし)により、連邦法がない場合および連邦法で許容される範囲内で、テキサス州法(法選択を除く)により規定されます。
**2. X に対する請求提起は 1 年以内です。** 適用される法律が、その請求に対する通常の時効を合意で短縮することを許可しないと規定していない限り、本契約に起因または関連するいかなる請求も、紛争を生じさせる事象または事実の発生日から 1 年以内に X に対して提起する必要があります。この期間内に請求を提起しない場合、当該事象または事実に基づく、あらゆる種類または性質の請求または訴因を追及する権利を永久に放棄し、そのような請求または訴因は永久に禁じられ、X はそのような請求について責任を負いません。
**3. 集団訴訟の放棄。** 法律で許容される範囲において、いかなる主張された集団訴訟、集合訴訟、または代表訴訟手続きにおいても、原告または集団構成員として参加する権利も放棄します。
**4. 本節の変更。** この紛争解決節は、X によって提供されるサービスまたは通信のキャンセルまたは購読解除を含む、あなたと X との関係の終了後も存続します。
**5. 差止による救済。** 前述にかかわらず、あなたは、X の知的財産または Confidential Information を保護する本契約の違反または違反のおそれが生じた場合には、金銭的損害賠償が X にとって不十分な救済策となることに同意します。そのような違反または脅威が生じた場合、X は、既得のその他の救済策に加えて、担保金を提供する必要なく、予備的または差止による救済(そのような規定への違反となる措置をあなたが取ることを禁止する命令を含む)、および該当する場合は特定履行を受ける権利を有します。当事者は、当事者が事業を行うか設立された州にかかわらず、国際物品売買契約に関する国際連合条約も統一コンピュータ情報取引法も本契約に適用されないことに同意します。X による本契約に基づく約束または権利の放棄は、X によって承認された書面に記載されない限り、有効ではありません。
**B. 本節は、あなたが欧州連合、EFTA 加盟国、または英国に居住している場合にのみ適用されます。この節を注意深くお読みください。あなたの法的権利、特に裁判所に訴訟を提起する権利に重大な影響を与える可能性があります。**
**1. 準拠法および裁判管轄地の選択。** 法律で許容される範囲において、本契約に関連するすべての紛争、本契約に起因もしくは関連する紛争、請求、または論争、Licensed Material のマーケティング、および/または Licensed Material への参加は、当事者間の反対の合意にかかわらず、アイルランドの管轄裁判所においてのみ提起され、抵触法規定を考慮せずアイルランド法により規定されます。前述にかかわらず、X が、独自の裁量で、あなたに対して有する請求、訴因、または紛争を、請求について管轄権と裁判地を有するあなたが居住する国の管轄裁判所に提起することができることに同意します。
**2. X に対する請求提起は 1 年以内です。** 適用される法律が、その請求に対する通常の時効を合意で短縮することを許可しないと規定していない限り、本契約に起因または関連するいかなる請求も、紛争を生じさせる事象または事実の発生日から 1 年以内に X に対して提起する必要があります。この期間内に請求を提起しない場合、当該事象または事実に基づく、あらゆる種類または性質の請求または訴因を追及する権利を永久に放棄し、そのような請求または訴因は永久に禁じられ、X はそのような請求について責任を負いません。
**3. 集団訴訟の放棄。** 法律で許容される範囲において、いかなる主張された集団訴訟、集合訴訟、または代表訴訟手続きにおいても、原告または集団構成員として参加する権利も放棄します。
**4. 本節の変更。** この紛争解決節は、X によって提供されるサービスまたは通信のキャンセルまたは購読解除を含む、あなたと X との関係の終了後も存続します。
**5. 差止による救済。** 前述にかかわらず、あなたは、X の知的財産または Confidential Information を保護する本契約の違反または違反のおそれが生じた場合には、金銭的損害賠償が X にとって不十分な救済策となることに同意します。そのような違反または脅威が生じた場合、X は、既得のその他の救済策(金銭的損害賠償を含む)に加えて、担保金を提供する必要なく、予備的または差止による救済(そのような規定への違反となる措置をあなたが取ることを禁止する命令を含む)、および該当する場合は特定履行を受ける権利を有します。当事者は、当事者が事業を行うか設立された州にかかわらず、国際物品売買契約に関する国際連合条約も統一コンピュータ情報取引法も本契約に適用されないことに同意します。X による本契約に基づく約束または権利の放棄は、X によって承認された書面に記載されない限り、有効ではありません。
**XIV. その他。**
**A. 譲渡。** X の事前の書面による同意なしに、本規定に基づき付与された権利または義務の全部または一部を、自発的に、法律の運用、契約、合併(あなたが存続または消滅する法人であるかにかかわらず)、株式または資産の売却、統合、解散、政府による措置その他により譲渡してはなりません。X は、米国外に居住する X ユーザーの情報について責任を負うアイルランドの会社である X Internet Unlimited Company のために、修正および同意に署名する権限を有します。本節に違反する譲渡は、無効となり、X は本契約を終了することができます。
**B. ユーザーの保護。** X によって書面で明示的に承認されていない限り、以下の目的で X コンテンツまたは X コンテンツから派生した情報を利用したり、故意に表示、配布、その他の方法で利用可能にしたりしてはなりません: (a) X ユーザーまたは X コンテンツの調査または追跡を含みますが、これに限定されない、監視の実施もしくは提供、または情報収集;(b) X ユーザーの合理的なプライバシー期待と矛盾する方法で、違法もしくは差別的な目的または方法での分析または調査の実施もしくは提供;(c) 抗議、集会、コミュニティ組織的な会合を含みますが、これに限定されない、機微なイベントの監視;または (d) 健康(例: 妊娠)、財務状況の悪さ、政治的所属もしくは信条、人種もしくは民族的出自、宗教的もしくは哲学的所属もしくは信条、性生活もしくは性的指向、労働組合への加入、犯罪の疑いのある行為もしくは実際の犯罪行為に関する X コンテンツ、または法律で禁止されている他の機微な個人情報カテゴリーを含む、機微な個人情報に基づく個人のターゲティング、セグメント化、またはプロファイリング。
**C. 政府による利用**。 政府関連の団体(それぞれ「**Government End User**」)であるユーザー、またはそれらの団体を代表して行動するユーザーに X コンテンツを表示、配布、またはその他の方法で利用可能にする場合: (a) Enterprise プラン([**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction) に記載)に申請(または既に加入)する必要があります;(b) X にレビューのために利用ケースを提出する際に、そのようなすべての Government End User を識別する必要があります;および (c) その後、Services が Government End User に、または新しい利用ケースのために X コンテンツを表示、配布、またはその他の方法で利用可能にする前に、新しい Government End User または既存の Government End User との新しい利用ケースについて、X に書面で通知する必要があります。X は、Government End User に X コンテンツを利用可能にすることを禁じることがあります。監視の実施または情報収集を主要な機能または任務とする Government End User に対して、X コンテンツまたは X コンテンツから派生した情報を利用したり、故意に表示、配布、その他の方法で利用可能にしたりしてはなりません。法執行機関が現在進行中の調査の目的で X またはそのユーザーに関する情報を要求する場合、[**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support) にある X の Guidelines for Law Enforcement をご参照いただくことができます。X API および X コンテンツは、48 C.F.R. 2.101 で定義される「商用アイテム」であり、48 C.F.R. 12.212 で使用される「商用コンピュータソフトウェア」および「商用コンピュータソフトウェアドキュメンテーション」で構成されています。政府機関による X API または X コンテンツの利用、修正、派生物、複製、リリース、実行、表示、開示、または配布は、本契約の条件で明示的に許可されている場合を除き、禁止されています。加えて、米国政府機関による利用はすべて、48 C.F.R. 12.212 および 48 C.F.R. 227.7202-1 から 227.7202-4 に従って行われる必要があります。米国州または地方政府機関の従業員または代表者として公務上 X API または X コンテンツを利用しており、法的に本規定の補償、裁判管轄、裁判地、その他の条項を受け入れることができない場合、それらの条項は法律で求められる範囲でその団体に適用されません。契約者/製造者は、X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA です。
**D. 法令遵守、輸出および輸入。** 各当事者は、贈収賄および/または汚職に関するすべての法律を含む、適用される外国、連邦、州、地方の法律、規則、および規制を遵守します。Licensed Material は米国輸出法の対象となり、配達または利用される国の輸入および利用法の対象となる場合があります。あなたはこれらの法律を遵守します。これらの法律の下で、Licensed Material は、ライセンス、または関連する政府当局の承認なしに、これらの法律によって制限された国、または外国国民(米国政府が禁輸措置を講じている国(現在キューバ、イラン、北朝鮮、北スーダン、シリア)を含む)、または制限もしくは拒否されたエンドユーザー(米国財務省外国資産管理局によって禁止されている個人または団体を含みますが、これに限定されません)に、あるいはいかなる制限された最終利用のためにも、販売、賃貸、ダウンロード、移動、輸出、再輸出、または国境を越えて移転してはなりません。あなたは、Services に必要なすべての権利およびライセンスを維持します。
**E. データ保護附属書。** 各当事者は、[**https://gdpr.x.com/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html) にある X Controller-to-Controller Data Protection Addendum を遵守します。これは、X によって随時更新される場合があります。
**F. 存続。** 本契約の第 III 節(利用に関する制限)、第 V 節(所有権およびフィードバック)、第 VI 節(秘密保持)、第 VII(I) 節(終了)、第 VIII 節(コンプライアンス監査)、第 IX 節(保証否認)、第 X 節(補償)、第 XI 節(責任の制限)、第 XIII 節(紛争解決および集団訴訟の放棄);および第 XIV 節(その他)は、本契約の終了後も存続します。
**G. 完全合意。** 本契約は、本契約の対象事項に関する当事者間の完全な理解を構成し、対象事項に関する当事者間の書面または口頭の他のすべての合意に優先し、置き換えます。本契約のいずれかの条項が裁判所によって強制不能とされた場合、本契約の残りの条項は引き続き有効です。本契約に基づく放棄は、書面で放棄を許可する当事者によって署名されない限り、有効ではありません。ある機会に付与された放棄は、他の機会における放棄として作用しません。本契約は、パートナーシップ、代理、または合弁事業を作り出したり、暗示したりするものではありません。
[**開発者ポリシーと契約**](https://docs.x.com/developer-terms)
[**@XDEVELOPERS**](https://x.com/XDevelopers) をフォロー
[**開発者ニュースを購読**](https://developer.x.com/twitterdev-news-subscription)
# 表示要件: リプライ
Source: https://docs.x.com/ja/developer-terms/reply-requirements
X API を使用するアプリで投稿へのリプライを表示する際の表示要件。スレッド構造、帰属表示、リプライコンテキストのルールを含みます。
## リプライ
リプライを表示する際は、以下のガイドラインに従ってください。
### デフォルトのリプライの場合:
### ソーシャルコンテキスト付きのリプライの場合:
### 引用の場合:
# X API の制限された利用ケース
Source: https://docs.x.com/ja/developer-terms/restricted-use-cases
X API の制限された利用ケースの詳細。プラットフォーム外の追跡、政府による監視、機微情報の取り扱い、禁止されているツールを含みます。
当社の開発者プラットフォームを利用するには、[開発者契約およびポリシー](/developer-terms/agreement)、ならびに [表示要件](https://docs.x.com/developer-terms/display-requirements) や [Automation Rules](https://help.x.com/en/rules-and-policies/twitter-automation) を含む関連ポリシーをレビューし、これらに同意する必要があります。当社の契約およびポリシーは、いくつかの制限された利用ケースに関するガイダンスを提供しています。以下では、これらの制限のいくつかについて追加情報を提供します。
## 自動化、スパム、自動応答
X の API および開発者向けプロダクトを使用してスパムを作成したり、スパム的な行為を行ったりすることは禁止されています。スパムに関する [X ルール](https://t.co/rules) をレビューし、アプリケーションが当社のポリシーに違反せず、またユーザーが違反することを可能にしないようにしてください。
アプリケーションが X サービス上で書き込みアクション(投稿の投稿、アカウントのフォロー、ダイレクトメッセージの送信を含む)を実行する場合、サービスがガイドラインに準拠していることを確認するために、[Automation Rules](https://support.x.com/articles/76915) を注意深くレビューしてください。特に以下を守ってください:
* [自動リプライやメッセージ](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444) を送信する前に、必ずユーザーの明示的な同意を得る
* あなたからの連絡を受けたくないというユーザーの要求を直ちに尊重する
* [大量フォロー](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769) を含む、一括、攻撃的、またはスパム的な行為を絶対に行わない
* [複数のアカウント](https://blog.x.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html) で同一または実質的に類似したコンテンツを投稿しない
## 機微情報
X のデータを使用して X ユーザーの潜在的に機微な特性を導出または推定することについては、慎重であるべきです。X ユーザーに関する以下の情報を導出または推定したり、そのような導出または推定された情報を保存したりしてはなりません:
* 健康(妊娠を含む)
* 財務状況の悪さ
* 政治的所属または信条
* 人種または民族的出自
* 宗教的または哲学的所属または信条
* 性生活または性的指向
* 労働組合への加入
* 犯罪の疑いのある行為または実際の犯罪行為
個人データ(たとえば、ユーザー ID、ユーザー名、その他の識別子など)を一切保存しない X コンテンツの集計分析は、その分析が適用される法律ならびに開発者契約およびポリシーのすべての部分に準拠している場合に限り、許可されます。
## X 外でのマッチング
X 外でのマッチングとは、X のユーザー名やユーザー ID などの X コンテンツを、人物、世帯、デバイス、ブラウザ、またはその他の X 外の識別子と関連付けることを指します。一例として、X のユーザー名を企業の顧客記録に関連付けること(すなわち、あなたの顧客記録内の「John Doe」を X の @johndoe と一致させること)が挙げられます。
私たちは、人々が X 上で別個の、そして望むならペンネーム的なアイデンティティを作ることに安心感を持てるようにしたいと考えています。X ユーザーに関する何らかの情報を X 外の識別子と関連付けようとする場合、その関連付けを行う前に、ユーザーから明示的なオプトイン同意を取得することを義務付けています。たとえば、ユーザーがあなたのサービスへのサインアッププロセスの一環として自身の X ハンドルを直接あなたと共有した場合に、この同意を得られる可能性があります。
X アイデンティティを X 外の識別子とリンクさせるためのユーザーの明示的なオプトイン同意がない状況では、ユーザーがその目的で使用されると合理的に予期する情報のみに基づいて、あらゆる接続を行うことを義務付けています。ユーザーが提供した情報を、X アカウントを X 外のアイデンティティにリンクするために使用していることを知ったら驚くようなことであれば、それを行わないでください。加えて、ユーザーの明示的なオプトイン同意がない場合、次のいずれかに基づいてのみ、あなたの記録を X アイデンティティにマッチさせようとすることができます:
* **ユーザーから直接あなたに提供された情報。** あなたと事前の関係がない個人に関する記録(第三者から取得した個人に関するデータを含む)は、この基準を満たしません。および/または
* **公開データ。** ここでいう「公開データ」とは、以下を指します:
* 公開されている、一般的に利用可能なリソース(たとえば、専門家団体の会員名簿など)から取得したユーザーに関する情報
* 一般に公開されている X 上のユーザーに関する情報。以下を含みます:
* 投稿
* アカウントのバイオや公開設定された位置情報を含むプロフィール情報
* 表示名およびユーザー名
## X コンテンツの再配布
X API 経由で取得した X コンテンツを別の当事者と共有する必要がある場合、投稿 ID、ダイレクトメッセージ ID、および/またはユーザー ID を共有する方法が最善です。コンテンツのエンドユーザーは、X API を使用してこれを再ハイドレート(すなわち、完全な投稿、ユーザー、またはダイレクトメッセージのコンテンツをリクエスト)することができます。これにより、X コンテンツのエンドユーザーは常に最新の情報を当社から直接取得できるようになります。
非自動化された手段によるハイドレート済み X コンテンツの限定的な再配布は許可されています。この方法でハイドレート済みの X コンテンツを他の当事者と共有する場合、1 日あたり受信者ごとに最大 50,000 個のハイドレート済みの公開 Post オブジェクトおよび/または User オブジェクトのみを共有でき、このデータを一般に公開してはなりません(たとえば、ブログ投稿の添付ファイルや公開の Github リポジトリなど)。
X コンテンツの再配布に関しては、他にもいくつか留意すべき点があります:
* X から事前の明示的な書面による許可を得ていない限り、30 日間で単一の事業体に配布できる投稿 ID は合計 1,500,000 件までです。
* 非商用研究のみを目的として、学術機関を代表して投稿 ID および/またはユーザー ID を再配布する個人は、無制限の投稿 ID および/またはユーザー ID を再配布することが許可されます。
* 上記のとおり X コンテンツを共有する許可をリクエストするには、API Policy サポートフォームをご利用ください。
第三者に X コンテンツを配布することが許可されている範囲では、そのコンテンツは引き続き開発者契約およびポリシーの対象であり、それらの第三者は X コンテンツを受け取る前に X の [利用規約](https://x.com/en/tos)、[プライバシーポリシー](https://x.com/en/privacy)、[開発者契約](/developer-terms/agreement)、[開発者ポリシー](/developer-terms/policy) に同意する必要があることに注意してください。
## 複数のアプリケーション
単一の利用ケース、または実質的に類似する、もしくは重複する利用ケースのために複数のアプリケーションを登録することは認められません。これらのポリシーの詳細は [こちら](https://twittercommunity.com/t/policy-clarification-multiple-applications-for-the-same-use-case/92080) をご覧ください。
ここでいう「利用ケース」とは、アプリケーションを介して実行される一貫した一連の分析、表示、またはアクションを指します。同じサービスやアプリケーションを異なるエンドユーザーに提供することは、単一の利用ケースとしてカウントされます。ただし、ツールやサービスの「ホワイトラベル」バージョンは含まれません。アプリケーションを「ホワイトラベル」化する予定がある場合は、当社に通知し、別途承認を得る必要があります。これらのルールは、あなたが登録するアプリケーションと、あなたのツールやサービスのエンドユーザーが登録するアプリケーションの両方に適用されます。ツールやサービスを使用する目的でエンドユーザーにアプリケーションを登録するよう要求すると、あなた、あなたのアプリケーション、あなたの顧客、および/またはあなたのツールやサービスのエンドユーザーに対して、エンフォースメントアクションが取られる可能性があります。
このルールの唯一の例外は、同じサービスの開発(「dev」)、ステージング、および本番(「prod」)インスタンスを作成することです。これらのアプリケーションが明確にラベル付けされていること(たとえば、アプリケーション名や説明で)、および開発またはステージング用のアプリケーションを本番目的で使用しないことを確認してください。
## X サービスの計測
ベンチマークや競合目的で X の可用性、パフォーマンス、機能、または利用状況を計測するために X API を使用しないでください。たとえば、以下のような目的で X API を使用してはなりません:
* 総アクティブユーザー数やアカウント数など、X ユーザーの集計メトリクスの算出
* 1 日あたりの投稿総数、ユーザーエンゲージメント数、アカウントエンゲージメント数など、X 投稿の集計メトリクスの算出
* [X ルール](https://help.x.com/en/rules-and-policies/twitter-rules) で許可されている場合を除き、X 上のスパムやセキュリティの計測または分析
## 監視、プライバシー、ユーザー保護
X では、ユーザーのプライバシーを保護し擁護することが、当社のコア DNA に組み込まれており、開発者向けおよびデータ向けプロダクトはそのコミットメントを反映しています。X のデータは、ジャカルタの洪水時における救命活動から、USGS による地震追跡の支援、持続可能な開発目標を達成するための国連との協力まで、世界にとって大きな善の力になり得ると私たちは考えています。しかしながら、いかなる事業体による、監視目的、またはユーザーの合理的なプライバシー期待と矛盾するその他の方法での X のデータおよび X API の使用も禁止します。これに例外はありません。
[開発者契約](/developer-terms/agreement) では、X ユーザーやそのコンテンツの調査または追跡の禁止、機微なイベント(抗議、集会、コミュニティの組織的会合など)の追跡、警告、または監視の禁止など、当社のデータおよび開発者向けプロダクトの禁止された利用について記述しています。
これらの条件のもとで禁止される活動のカテゴリーには、以下のようなものが含まれます(ただしこれらに限定されません):
* 労働組合や活動家グループなどの機微なグループや組織の調査または追跡
* バックグラウンドチェックやあらゆる形式の厳格な審査
* 信用または保険のリスク分析
* 個人プロファイリングやサイコグラフィックセグメンテーション
* 顔認識
これらのポリシーは、当社の API のすべてのユーザーに適用されます。これらの目的で X API を悪用した場合は、エンフォースメントアクションの対象となり、アクセスの停止および終了が含まれる可能性があります。
X アカウントに関する情報を求める法執行機関向けの追加情報については、[https://t.co/le](https://t.co/le) をご覧ください。
さらに、現時点では、[Grok](https://help.x.com/en/using-x/about-grok) を除き、基盤モデルやフロンティアモデルのファインチューニングまたはトレーニングのために X API および/または X コンテンツを使用することを禁止します。
# Enterprise API について — firehose、ストリーム、Webhook
Source: https://docs.x.com/ja/enterprise-api/getting-started/about-x-api
X Enterprise API の概要。完全な firehose アクセス、ボリュームストリーム、Account Activity Webhook、カスタムレート制限、専任サポートを含みます。PowerTrack ルール、Historical PowerTrack、Engagement API もあわせて解説します。
Enterprise API は、X データへの最高ティアのアクセスを提供します。標準の X API で利用可能なすべての機能に加えて、独占的な大容量エンドポイント、Filtered Stream 向けのセマンティック埋め込み演算子、カスタムレート制限、X データを大規模に必要とする組織向けの専任アカウント管理を提供します。
***
## できること
標準の X API のすべてに加えて:
| 機能 | 説明 |
| :------------------------- | :-------------------------------------------------------------------------------------- |
| **完全な firehose のストリーミング** | ボリュームストリームで公開投稿の 100% にリアルタイムでアクセス |
| **すべてのいいねのストリーミング** | 完全およびサンプル化されたいいねストリームをリアルタイムで |
| **高度な Filtered streaming** | Powerstream (低レイテンシのキーワードフィルタリング) |
| **セマンティック埋め込み演算子** | Filtered Stream で `embedding:` を使用して意味で投稿をマッチ (キーワードだけでなく) (Enterprise + Embedding ティア) |
| **深いエンゲージメント分析** | 大規模での投稿およびメディアエンゲージメントメトリクス |
| **Account Activity イベント** | ユーザーイベント (投稿、DM、いいね、フォロー) のリアルタイム購読 |
| **Webhook 配信** | Webhook を介して Filtered stream データを受信 |
| **カスタムレート制限** | スループットニーズに合わせた引き上げ制限 |
| **専任サポート** | 指定されたアカウントマネージャーと優先的な問題解決 |
***
## エンタープライズ専用エンドポイント
これらのエンドポイントは Enterprise アクセスでのみ利用可能です:
完全なリアルタイムカバレッジのための完全な firehose および言語固有のストリーム。
プラットフォーム全体のすべてのいいね、またはサンプル化されたいいねをストリーミング。
高度な演算子を備えた高性能フィルタリングストリーミング。
深いエンゲージメントインサイトのための投稿およびメディアアナリティクス。
ユーザーアクティビティのリアルタイムイベント購読。
Webhook を介した Filtered stream の配信。
***
## 利用可能なすべてのリソース
Enterprise アクセスには、X API リソースの完全なセットが含まれます:
投稿の検索、取得、作成、削除。タイムライン、スレッド、引用投稿へのアクセス。
プロフィールの参照、関係の管理、フォロワーデータへのアクセス。
ライブ音声会話と参加者を発見します。
ユーザー間でプライベートメッセージを送受信。
アカウントのキュレーションリストを作成・管理。
地域別のトレンドトピックにアクセス。
***
## API のハイライト
必要なデータのみをリクエストします。`fields` パラメータで特定の属性を選択し、`expansions` で関連オブジェクトを含めます。
```bash theme={null}
curl "https://api.x.com/2/tweets/123?tweet.fields=created_at,public_metrics&expansions=author_id&user.fields=username" \
-H "Authorization: Bearer $TOKEN"
```
[fields の詳細はこちら →](/x-api/fundamentals/fields)
投稿には、人物、場所、製品、トピックを識別するセマンティックアノテーションが含まれます。トピック別にストリームと検索をフィルタリングします。
[アノテーションの詳細はこちら →](/x-api/fundamentals/post-annotations)
Enterprise の顧客は、投稿とメディアの両方に対する専用のエンゲージメントメトリクスエンドポイントへのアクセスを得て、標準の公開メトリクスを超える大規模な深い分析を実現できます。
[メトリクスの詳細はこちら →](/x-api/fundamentals/metrics)
`conversation_id` を使用して会話スレッド全体を再構築します。スレッド全体の返信を追跡します。
[会話追跡の詳細はこちら →](/x-api/fundamentals/conversation-id)
投稿の編集履歴 (過去のすべてのバージョンと編集メタデータを含む) にアクセスできます。
[投稿の編集の詳細はこちら →](/x-api/fundamentals/edit-posts)
***
## 料金
Enterprise プランは、組織のニーズに合わせてカスタマイズされます。料金はデータ量、エンドポイントの使用、サポート要件に基づきます。
| 機能 | 詳細 |
| :------------- | :----------------------- |
| **カスタムパッケージ** | 特定のデータとスループットのニーズに合わせて調整 |
| **長期契約** | コミットされた利用契約による予測可能な料金設定 |
| **投稿読み取り上限なし** | カスタムまたは無制限の投稿読み取り量 |
| **専任サポート** | すべての Enterprise プランに含まれる |
[料金についてセールスに問い合わせる](/forms/enterprise-api-interest)
***
## 次のステップ
セールスチームに連絡し、ニーズについて話し合いましょう。
Enterprise 専用エンドポイントを含む、利用可能なすべてのエンドポイントを閲覧します。
# Enterprise アクセスを取得する
Source: https://docs.x.com/ja/enterprise-api/getting-started/getting-access
X Enterprise API のアクセス申請から利用開始までの流れを解説します。専任担当チームによるオンボーディング、API キーとアクセストークンの発行、エンドポイント設定、組織のデータボリュームと支援ニーズに合わせたカスタムプラン構成までを順を追って説明します。
Enterprise アクセスには、申請とオンボーディングのプロセスが必要です。専任のアカウントチームが、認証情報の設定とアクセス構成をサポートします。
***
## ステップ 1: Enterprise アクセスを申請する
[Enterprise 関心フォームに記入](/forms/enterprise-api-interest)し、組織とユースケースに関する詳細を提供します。
当社の営業チームから、データ量、エンドポイント要件、サポートニーズを把握するためにご連絡します。
ユースケースに合わせた料金、レート制限、アクセスレベルを含むプランを受け取ります。
***
## ステップ 2: オンボーディングを受ける
Enterprise プランが整ったら、専任のアカウントマネージャーが以下のセットアップを支援します:
[Developer Console](https://console.x.com) で Enterprise レベルのアクセスを持つ App をセットアップします。
アカウントマネージャーが、レート制限、エンドポイントアクセス、その他カスタム設定の構成をサポートします。
認証用の API キーとトークンを生成します。
***
## ステップ 3: 認証情報を保存する
認証ニーズに応じて、いくつかの認証情報を受け取ります:
| 認証情報 | 用途 |
| :------------------------ | :--------------------------------------------- |
| **API Key & Secret** | App を識別します。トークンの生成と OAuth 1.0a リクエストの署名に使用します。 |
| **Bearer Token** | 公開データの読み取り用 App 専用認証。 |
| **Access Token & Secret** | 自身のアカウントに代わってリクエストを行います (OAuth 1.0a)。 |
| **Client ID & Secret** | ユーザーコンテキストリクエスト用の OAuth 2.0 認証。 |
**すぐに保存してください。** 認証情報は一度しか表示されません。パスワードマネージャーや安全なボールトに保管してください。紛失した場合は再生成が必要となり (古いものは無効になります)。
***
## どの認証情報が必要ですか?
公開データへのシンプルな読み取り専用アクセスには **Bearer Token** を使用します。
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
最適な用途: 投稿の検索、ユーザーの参照、トレンドの読み取り。
ユーザーに代わって動作するには **OAuth 2.0** (推奨) または **OAuth 1.0a** を使用します。
OAuth 2.0 はきめ細かいスコープを提供します—必要な権限のみをリクエストできます。
最適な用途: 投稿、いいね、フォロー、DM へのアクセス。
[OAuth 2.0 ガイド →](/resources/fundamentals/authentication/oauth-2-0/overview)
自身のアカウントとしてリクエストを行うには **Access Token & Secret** を使用します。
これらのトークンは、App を所有するアカウントを表します。
最適な用途: テスト、個人用ボット、自身の自動化。
***
## 認証情報のセキュリティに関するベストプラクティス
認証情報をソースコードにハードコードしないでください。
認証情報ファイルを `.gitignore` に追加してください。
セキュリティ対策として、認証情報を定期的に再生成してください。
App に必要な OAuth 権限のみをリクエストしてください。
***
## 次のステップ
新しい認証情報で API を呼び出します。
OAuth 1.0a と OAuth 2.0 を理解します。
# 重要なリソース
Source: https://docs.x.com/ja/enterprise-api/getting-started/important-resources
X Enterprise API のお客様向けの必須リソース。オンボーディングガイド、アカウントマネージャー、サポート連絡先、ステータスページ、SDK を含みます。データディクショナリ、認証手順、変更履歴、契約およびコンプライアンス関連の資料へのリンクもまとめて案内します。
X API 開発のためのこれらの必須リソースをブックマークしておきましょう。
***
## ドキュメント
パラメータと例を含む完全なエンドポイントドキュメント。
投稿、ユーザー、メディアなどのオブジェクトスキーマ。
OAuth 1.0a および OAuth 2.0 の実装ガイド。
エンドポイントごとの制限とベストプラクティス。
***
## ツール
| ツール | 説明 |
| :------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |
| [Developer Console](https://console.x.com) | アプリ、認証情報、請求を管理 |
| [Postman Collection](https://www.postman.com/xapidevelopers/x-api-public-workspace/collection/34902927-2efc5689-99c6-4ab6-8091-996f35c2fd80) | インタラクティブな API テスト |
| [Python SDK](/xdks/python/overview) | 公式 Python ライブラリ |
| [TypeScript SDK](/xdks/typescript/overview) | 公式 TypeScript ライブラリ |
| [OpenAPI Spec](https://api.x.com/2/openapi.json) | 機械可読の API 仕様 |
***
## 学習
よくあるユースケースのためのステップバイステップガイド。
アプリ例とコードサンプル。
プロジェクトのアイデアとインスピレーション。
v1.1 から v2 へのアップグレード。
***
## コミュニティとサポート
質問し、コミュニティと解決策を共有しましょう。
FAQ、トラブルシューティング、連絡オプション。
公式の更新とお知らせ。
API 固有のニュースとヒント。
***
## 最新情報を入手する
| リソース | 入手できるもの |
| :------------------------------------------------------------------- | :---------------- |
| [Changelog](/changelog) | すべてのプラットフォーム変更と更新 |
| [Newsletter](/newsletter) | ニュースと機能の月次まとめ |
| [Forum Announcements](https://devcommunity.x.com/c/announcements/22) | 重要なプラットフォーム通知 |
| [API Status](/status) | リアルタイムのサービス可用性 |
破壊的変更と新機能をキャッチするために、[@XDevelopers](https://x.com/XDevelopers) をフォローし、通知をオンにしてください。
***
## クイックリファレンス
### レスポンスの構造
すべての v2 レスポンスはこの構造に従います:
```json theme={null}
{
"data": { ... }, // Primary object(s)
"includes": { ... }, // Expanded objects (if requested)
"meta": { ... }, // Pagination info
"errors": [ ... ] // Partial errors (if any)
}
```
### 共通のパラメータ
| パラメータ | 用途 |
| :----------------- | :----------------- |
| `tweet.fields` | 特定の投稿フィールドをリクエスト |
| `user.fields` | 特定のユーザーフィールドをリクエスト |
| `expansions` | 関連オブジェクトを含める |
| `max_results` | ページあたりの結果を制限 |
| `pagination_token` | 次/前のページを取得 |
### 認証方法
| 方法 | ユースケース |
| :----------- | :---------------------- |
| Bearer Token | 読み取り専用の公開データ |
| OAuth 2.0 | きめ細かなスコープを使用したユーザーアクション |
| OAuth 1.0a | ユーザーアクション (レガシー、フル権限) |
[認証ガイド全文 →](/resources/fundamentals/authentication/overview)
# 最初のリクエストを送信する
Source: https://docs.x.com/ja/enterprise-api/getting-started/make-your-first-request
最初の X Enterprise API リクエストを送信します。認証セットアップ、エンドポイントの選択、cURL コマンド例、レスポンス処理のヒントを含みます。ベーシック認証、ホワイトリスト設定、PowerTrack のルール登録、Search API の呼び出し方も具体的に解説します。
このガイドでは、最初の X API リクエストを送信する手順を説明します。開始する前に、[アプリ認証情報を含むデベロッパーアカウント](/x-api/getting-started/getting-access) が必要です。
***
## cURL でクイックスタート
API をテストする最も簡単な方法は cURL です。ユーザーを検索してみましょう:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
`$BEARER_TOKEN` を実際の Bearer Token に置き換えてください。次のようなレスポンスが返されます:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## ステップバイステップガイド
[Developer Console](https://console.x.com) でアプリに移動し、Bearer Token をコピーします。
まずは初心者向けの次のエンドポイントから始めましょう:
| エンドポイント | 機能 |
| :------------------------------------------------ | :------------------------- |
| [User lookup](/x-api/users/lookup/introduction) | ユーザー名または ID でユーザープロフィールを取得 |
| [Post lookup](/x-api/posts/lookup/introduction) | ID で投稿を取得 |
| [Recent search](/x-api/posts/search/introduction) | 過去 7 日間の投稿を検索 |
cURL、Postman、またはお好みの HTTP クライアントを使用します:
```bash theme={null}
# ユーザー名でユーザーを検索
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
レスポンスは JSON 形式です。主要なデータは `data` フィールドに含まれます:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## fields でより多くのデータをリクエストする
デフォルトでは、エンドポイントは最小限のフィールドのみを返します。`fields` パラメータを使用して追加データをリクエストできます:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers?user.fields=created_at,description,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
レスポンス:
```json 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 Platform",
"public_metrics": {
"followers_count": 570842,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
[fields の詳細はこちら →](/x-api/fundamentals/fields)
***
## その他の例
```bash theme={null}
curl "https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=from:xdevelopers&tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/tweets?max_results=5" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## cURL の代わりにコードを使う
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/users/by/username/xdevelopers"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers)
print(response.json())
```
```javascript theme={null}
const bearerToken = "YOUR_BEARER_TOKEN";
const url = "https://api.x.com/2/users/by/username/xdevelopers";
fetch(url, {
headers: { Authorization: `Bearer ${bearerToken}` }
})
.then(res => res.json())
.then(data => console.log(data));
```
本番利用には、公式 SDK の使用をおすすめします:
* [Python SDK](/xdks/python/overview)
* [TypeScript SDK](/xdks/typescript/overview)
これらは認証、ページネーション、レート制限を自動的に処理します。
***
## テスト用ツール
コレクションを使ったビジュアル API テスト。
複数の言語での例。
エンドポイントの完全なドキュメント。
***
## トラブルシューティング
* Bearer Token が正しいか確認してください
* トークンが再生成されていないことを確認してください
* `Authorization` ヘッダーの形式を確認: `Bearer YOUR_TOKEN`
* アプリがこのエンドポイントへのアクセス権を持っていない可能性があります
* 一部のエンドポイントはユーザーコンテキスト認証 (OAuth 1.0a または 2.0) が必要です
* Developer Console でアプリの権限を確認してください
* レート制限に達しました
* 再試行のタイミングについては `x-rate-limit-reset` ヘッダーを確認してください
* コードに指数バックオフを実装してください
[完全なエラーリファレンス →](/x-api/fundamentals/response-codes-and-errors)
***
## 次のステップ
ユーザーコンテキストリクエストのための OAuth を理解しましょう。
何が構築できるか発見しましょう。
公式ライブラリで開発を加速。
作るもののアイデア。
# Enterprise API の料金とカスタムプラン
Source: https://docs.x.com/ja/enterprise-api/getting-started/pricing
X Enterprise API の料金プランは、組織のデータ量、利用するエンドポイント、SLA、運用サポート要件に応じて個別に設計されます。大量データ、専用アクセス、カスタム契約に対応した価格や見積もりについては、X の営業担当チームまでお問い合わせください。
Enterprise プランは、お客様の組織のニーズに合わせてカスタマイズされます。専任のアカウントチームと連携し、データ量、エンドポイントの利用状況、サポート要件に合ったパッケージを構築します。
***
## Enterprise の料金体系
お客様固有のデータ量、エンドポイントのニーズ、スループット要件に合わせて料金を設定します。
長期契約と利用量のコミットにより、予測可能なコストを実現します。
従量課金プランの月間 200 万件の上限をはるかに超える、カスタムまたは無制限の投稿読み取り量に対応します。
すべての Enterprise プランには、専任のアカウントマネージャーと優先テクニカルサポートが含まれます。
***
## 含まれる内容
すべての Enterprise プランには、X API のフル機能に加え、Enterprise 専用エンドポイントへのアクセスが含まれます:
| 機能 | 詳細 |
| :------------------------ | :------------------------------------------------------------------------ |
| **すべての標準エンドポイント** | 従量課金型 X API で利用できるすべての機能 |
| **Volume streams** | フル firehose および言語別ストリーム |
| **Likes streams** | リアルタイムのフル/サンプリング likes |
| **Powerstream** | 高度なフィルタリングストリーミング |
| **セマンティック embedding 演算子** | Filtered Stream 専用のセマンティックマッチング向け `embedding:` 演算子(Embedding ティアのアクセスが必要) |
| **Engagement metrics** | 投稿およびメディア分析エンドポイント |
| **Account Activity** | ユーザーイベントのリアルタイム購読 |
| **Stream webhooks** | Webhook 経由のフィルタリングストリーム配信 |
| **カスタムレート制限** | お客様のニーズに合わせて引き上げられた制限 |
| **専任サポート** | 専任のアカウントマネージャーと優先対応 |
***
## Enterprise と従量課金の比較
| | 従量課金(Pay-per-use) | Enterprise |
| :------------------------ | :---------------- | :---------------------------------------------------------- |
| **料金モデル** | クレジット制の従量課金 | カスタム契約 |
| **月間 Post 上限** | 200 万件の読み取り | カスタム / 無制限 |
| **Volume streams** | 利用不可 | フル firehose および言語別ストリーム |
| **Likes streams** | 利用不可 | フルおよびサンプリング likes |
| **セマンティック embedding 演算子** | 利用不可 | Filtered Stream 専用の `embedding:` 演算子(Embedding ティアのアクセスが必要) |
| **Engagement metrics** | 利用不可 | 投稿およびメディア分析 |
| **レート制限** | 標準 | カスタム / 引き上げ |
| **サポート** | コミュニティフォーラム | 専任アカウントマネージャー |
| **コミットメント** | なし | 契約ベース |
***
## 利用状況のモニタリング
[Usage エンドポイント](/x-api/usage/introduction) を使うと、API の利用状況をプログラムで追跡できます:
```bash theme={null}
curl "https://api.x.com/2/usage/tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
これにより日次の Post 消費数が返され、次のような用途に活用できます:
* 契約上限に対する消費量を追跡する
* 関係者向けの利用状況レポートを作成する
* 消費量の多いエンドポイントを特定する
* アカウントチームとともにキャパシティを計画する
***
## はじめに
[Enterprise アクセスを申請](/forms/enterprise-api-interest)し、ユースケースとデータニーズをお知らせください。
セールスチームがお客様と連携し、要件と予算に合ったパッケージを構築します。
専任のアカウントマネージャーが、認証情報のセットアップ、アクセス設定、開発開始までをサポートします。
***
## 次のステップ
セールスチームに連絡してはじめましょう。
利用状況をプログラムでモニタリングします。
# Enterprise API
Source: https://docs.x.com/ja/enterprise-api/introduction
X firehose、ボリュームストリーム、full-archive search、PowerTrack へのエンタープライズグレードのアクセス。専任の技術サポートとカスタム料金を提供します。高スループット、SLA 保証、Account Activity Webhook、コンプライアンスストリームにも対応します。
X API Enterprise プランは、X データへの最高レベルのアクセスを提供します。完全な firehose カバレッジ、ボリュームストリーム、Filtered Stream 用のセマンティック埋め込み演算子、専任のアカウント管理、X データを大規模に活用する組織向けに設計されたカスタムレート制限を取得できます。
専任のアカウントチームを伴うエンタープライズアクセスを申し込めます。
エンタープライズ専用エンドポイントを含む、利用可能なすべてのエンドポイントを探索します。
公式 Python・TypeScript ライブラリ。
***
## なぜ Enterprise なのか?
Enterprise アクセスには、従量課金制の X API のすべてに加えて、独占的な大容量エンドポイント、専任サポート、ニーズに合わせたカスタムパッケージが含まれます。
公開投稿の 100% をリアルタイムにストリーミング。サンプリングや制限なし。すべての投稿を発生と同時に取得できます。
英語、日本語、韓国語、ポルトガル語の firehose を含む、フルボリュームおよび言語固有のストリームにアクセスできます。
専任のアカウントマネージャー、パーソナライズされた技術サポート、優先的な問題解決を提供します。
スループット要件に合わせた、より高いレート制限とカスタマイズされたパッケージ。
投稿とメディアのアナリティクスエンドポイントにアクセスし、大規模なデータセット全体での深いエンゲージメントインサイトを得られます。
投稿、ユーザー、いいねに関するリアルタイムのコンプライアンスイベントストリームでコンプライアンスを維持できます。
Filtered Stream で `embedding:` 演算子を使用して、キーワードだけでなく概念的な意味で投稿をマッチさせます (Embedding ティアが必要)。
***
## エンタープライズ専用エンドポイント
これらのエンドポイントは Enterprise プランでのみ利用可能です:
完全な firehose、言語固有のストリーム、サンプルストリーム。
すべてのいいね、またはサンプル化されたいいねをリアルタイムでストリーミング。
低レイテンシの高性能フィルタリングストリーミング (キーワード演算子)。
投稿とメディアエンゲージメントの深い分析。
投稿、DM、いいね、フォローを含むリアルタイムのユーザーアクティビティイベントを購読します。
永続的な接続の代わりに、Webhook を介して Filtered stream データを受信します。
***
## 構築できるもの
Enterprise アクセスは、X 上で最も要求の厳しいユースケースを支援します。
投稿の検索、取得、公開。タイムライン、スレッド、引用投稿へのアクセス。
ユーザーの検索、フォロー、ブロック、ミュートの管理。
ライブ音声会話とその参加者を見つけます。
プライベートメッセージの送受信。
アカウントのキュレーションリストを作成・管理。
地域別のトレンドトピックにアクセス。
***
## 主な機能
### 完全なリアルタイムカバレッジ
公開投稿の 100% を発生と同時にストリーミング。サンプリングやギャップなし。Enterprise firehose アクセスは、X 上の公開会話の完全な姿を提供します。
利用可能なストリーム:
* **すべての投稿** - すべての公開投稿をリアルタイムで
* **英語の投稿** - すべての英語投稿
* **日本語の投稿** - すべての日本語投稿
* **韓国語の投稿** - すべての韓国語投稿
* **ポルトガル語の投稿** - すべてのポルトガル語投稿
* **サンプルストリーム** - 1% および 10% のランダムサンプル
[ボリュームストリームの詳細](/x-api/posts/volume-streams/introduction)
### 豊富なデータオブジェクト
投稿、ユーザー、メディアなどの詳細で構造化されたデータにアクセス:
* **投稿**: フルテキスト、メトリクス、エンティティ、アノテーション、会話スレッド
* **ユーザー**: プロフィール、フォロワー数、認証ステータス
* **メディア**: メタデータ付き画像、動画、GIF
* **投票**: 選択肢と投票数
必要なデータだけを取得するために、[fields](/x-api/fundamentals/fields) と [expansions](/x-api/fundamentals/expansions) でレスポンスをカスタマイズします。
### Filtered stream
投稿が公開されると、リアルタイムで配信されます。Enterprise はより高いルール制限と、意味でマッチさせる (キーワードだけでない) セマンティックな `embedding:` 演算子 (Filtered Stream でのみ) を追加します。
```bash theme={null}
# ルールを追加
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $TOKEN" \
-d '{"add": [{"value": "from:xdevelopers"}]}'
# ストリームに接続
curl "https://api.x.com/2/tweets/search/stream" \
-H "Authorization: Bearer $TOKEN"
```
[Filtered stream の詳細](/x-api/posts/filtered-stream/introduction)
### Full-archive search
2006 年までさかのぼる公開投稿の完全な履歴を検索できます。ユーザー、キーワード、日付などの演算子でクエリを構築します。
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?query=AI%20lang:en" \
-H "Authorization: Bearer $TOKEN"
```
### エンゲージメントメトリクス
インプレッション、いいね、リポスト、返信、動画再生数、メディアレベルのメトリクスを含む、深いエンゲージメント分析にアクセスできます。
[検索の詳細](/x-api/posts/search/introduction)
***
## Enterprise vs 従量課金
| 機能 | 従量課金 | Enterprise |
| :------------------- | :---------------------- | :----------------------------------------------------------- |
| **投稿検索** | Recent および full-archive | Recent および full-archive |
| **Filtered stream** | 最大 1,000 ルール | 5,000 以上のルール + セマンティック `embedding:` 演算子 (Filtered Stream のみ) |
| **ボリュームストリーム** | - | 完全な firehose および言語ストリーム |
| **Likes ストリーム** | - | 完全およびサンプル化されたいいね |
| **Powerstream** | - | 高度なフィルタリングストリーミング |
| **エンゲージメントメトリクス** | - | 投稿およびメディアアナリティクス |
| **Account Activity** | - | リアルタイムのユーザーイベント購読 |
| **月間投稿上限** | 200 万読み取り | カスタム / 無制限 |
| **レート制限** | 標準 | カスタム / 引き上げ |
| **サポート** | コミュニティフォーラム | 専任アカウントマネージャー |
***
## はじめる
[セールスチームにお問い合わせ](/forms/enterprise-api-interest) いただき、ニーズについて話し合い、カスタムパッケージを取得します。
専任のアカウントマネージャーが、認証情報のセットアップとアクセスの設定をサポートします。
連携には、同じモダンな v2 API エンドポイントに加えて、Enterprise 専用エンドポイントを使用します。
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## ツール & ライブラリ
非同期サポート付きの公式 Python ライブラリ。
公式 TypeScript/JavaScript ライブラリ。
インタラクティブな API エクスプローラ。
[すべてのライブラリを参照する](/tools-and-libraries)
***
## サポート
Enterprise の顧客には、技術およびアカウントサポートの専任窓口があります。
コミュニティと X チームから助けを得られます。
# Ads API アクセスフォーム
Source: https://docs.x.com/ja/forms/ads-api-access
X Ads API のアクセス申請フォームです。利用するユースケース、開発者アプリ情報、会社情報、コンバージョン API の利用予定などの必要事項を入力して送信し、X 担当チームの審査と承認を経て広告データへのアクセスと Ads API の利用を開始できます。
# 請求サポートフォーム
Source: https://docs.x.com/ja/forms/billing-support
請求書、支払い方法、サブスクリプションの変更、返金、プランのアップグレード、アカウント関連の請求に関する問題について、X API の請求サポートにお問い合わせください。
セルフサーブおよび Enterprise API のサブスクリプションに関する請求サポートを受けられます。
# Enterprise アクセスフォーム
Source: https://docs.x.com/ja/forms/enterprise-api-interest
会社情報、想定するユースケース、想定されるデータ量、レビュー用の連絡先情報を送信して、X Enterprise API へのアクセスをリクエストします。
# 政府エンドユーザー申請フォーム
Source: https://docs.x.com/ja/forms/government-end-user-request
政府・公的機関向けフォーム。機関情報、想定するユースケース、レビュー用のコンプライアンス情報を提供して、X API アクセスをリクエストします。
# OAuth API リファレンス索引
Source: https://docs.x.com/ja/fundamentals/authentication/api-reference
OAuth 1.0a および OAuth 2.0 における X 認証エンドポイントのリファレンス索引。request tokens、authorize、access tokens、トークン取り消しを含みます。
### OAuth 1.0a
| | |
| :---------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------- |
| **目的** | メソッド |
| 3-legged OAuth フローおよび Sign in with X のステップ 1 consumer アプリケーションが OAuth Request Token を取得してユーザー認可を要求できるようにします。 | [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) |
| 3-legged OAuth フローおよび Sign in with X のステップ 2 consumer アプリケーションが OAuth Request Token を使ってユーザー認可を要求できるようにします。 | [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) |
| 3-legged OAuth フローおよび Sign in with X のステップ 2 consumer アプリケーションが OAuth Request Token を使ってユーザー認可を要求できるようにします。 | [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) |
| 3-legged OAuth フローおよび Sign in with X のステップ 3 consumer アプリケーションが OAuth Request Token を OAuth Access Token に交換できるようにします。 | [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) |
| 登録済みアプリケーションが発行済みの OAuth Access Token を取り消せるようにします。 | [POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth-invalidate-token) |
### OAuth 2.0 Bearer Token
| | |
| :---------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
| **目的** | メソッド |
| 登録済みアプリが、ユーザーコンテキストなしでアプリに代わって API リクエストを行うために使用できる OAuth 2 app-only Bearer Token を生成できるようにします。 | [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) |
| 登録済みアプリが、発行済みの OAuth 2 app-only Bearer Token を取り消せるようにします。 | [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) |
### POST oauth/request\_token
consumer アプリケーションが OAuth Request Token を取得してユーザー認可を要求できるようにします。このメソッドは [OAuth 1.0 認証フロー](http://oauth.net/core/1.0/#anchor9) の [Section 6.1](https://oauth.net/core/1.0/#auth_step1) を満たします。
**すべての OAuth 認可ステップで HTTPS の使用が必須です。**
**使用上の注意:** `oauth_nonce` には ASCII 値のみが受け付けられます。
**リソース URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/request_token`
**リソース情報[](#resource-information "Permalink to this headline")**
| | |
| :---------- | :--- |
| レスポンスフォーマット | JSON |
| 認証が必要? | No |
| レート制限? | Yes |
**パラメーター[](#parameters "Permalink to this headline")**
| 名前 | 必須 | 説明 | 例 |
| :-------------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------- |
| oauth\_callback | required | OAuth 1.0a 準拠のため、このパラメーターは **必須** です。ここで指定する値は、ユーザーがアプリケーションのアカウントへのアクセスを承認した際にリダイレクトされる URL として使用されます。out-of-band pin モードには `oob` を設定します。これはデスクトップ/モバイルアプリケーションで使用するカスタムコールバックを指定する方法でもあります。事前登録されたコールバックの有無に関わらず、このステップでは常に `oauth_callback` を送信してください。
このエンドポイントで使用するコールバック URL は、developer.x.com のアプリ設定で構成しておく必要があります\* | `http://themattharris.local/auth.php` `twitterclient://callback` |
| x\_auth\_access\_type | optional | アプリケーションがユーザーアカウントに要求するアクセスレベルを上書きします。サポートされる値は `read` または `write` です。このパラメーターは、read/write アプリケーションとして登録されていながら、必要に応じて read only アクセスをリクエストできるようにするためのものです。 | |
コールバック URL の承認方法については [こちらのページ](/resources/fundamentals/developer-apps#callback-urls) を参照してください。
**注意事項** - developer.x.com で X アカウントにログインしている場合、[X app dashboard](https://developer.x.com/en/apps) から既存の [X アプリ](/resources/fundamentals/developer-apps) を確認・編集できます。
**リクエスト例[](#example-request "Permalink to this headline")**
リクエスト URL: `POST https://api.x.com/oauth/request_token`
リクエスト POST 本文: *N/A*
Authorization ヘッダー: `OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw", oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1300228849", oauth_consumer_key="OqEqJeafRSF11jBMStrZz", oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", oauth_version="1.0"`
レスポンス: `oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik&oauth_token_secret=Kd75W4OQfb2oJTV0vzGzeXftVAwgMnEK9MumzYcM&oauth_callback_confirmed=true`
### GET oauth/authorize
consumer アプリケーションが OAuth Request Token を使ってユーザー認可を要求できるようにします。このメソッドは [OAuth 1.0 認証フロー](http://oauth.net/core/1.0/#anchor9) の [Section 6.2](http://oauth.net/core/1.0/#auth_step2) を満たします。デスクトップアプリケーションはこのメソッドを使用する必要があります ([GET oauth / authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) は使用できません)。
**使用上の注意:** `oauth_callback` はこのメソッドに送信しないでください。代わりに [POST oauth / request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) に渡してください。
**リソース URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authorize`
**リソース情報[](#resource-information "Permalink to this headline")**
| | |
| :---------- | :--- |
| レスポンスフォーマット | JSON |
| 認証が必要? | Yes |
| レート制限? | Yes |
**パラメーター[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :------- | :---------------------------------------- | :----- | :- |
| 名前 | 必須 | 説明 | デフォルト値 | 例 |
| force\_login | optional | 正しいユーザーアカウントが認可されるように、ユーザーに認証情報の入力を強制します。 | | |
| screen\_name | optional | OAuth ログイン画面のユーザー名入力欄を指定された値で事前入力します。 | | |
**リクエスト例[](#example-request "Permalink to this headline")**
oauth\_token パラメーターを含めて、Web ブラウザーでユーザーを `oauth/authorize` のステップに送ります:
`https://api.x.com/oauth/authorize?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### GET oauth/authenticate
consumer アプリケーションが OAuth `request_token` を使ってユーザー認可を要求できるようにします。
このメソッドは、コールバック認証フローを使用するアプリケーションのために、[OAuth 1.0 認証フロー](http://oauth.net/core/1.0/#anchor9) の [Section 6.2](http://oauth.net/core/1.0/#auth_step2) を置き換えるものです。`force_login` パラメーターが `true` に設定されていない限り、このメソッドは現在ログイン中のユーザーをアクセス認可の対象アカウントとして使用します。
このメソッドが [GET oauth / authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) と異なる点は、ユーザーがすでにアプリケーションに権限を付与している場合、ユーザーが再度アプリケーションを承認する必要なくリダイレクトが発生することです。この挙動を実現するには、[application record](https://developer.x.com/apps) で *Use Sign in with X* 設定を有効にする必要があります。
**リソース URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authenticate`
**リソース情報[](#resource-information "Permalink to this headline")**
| | |
| :---------- | :--- |
| レスポンスフォーマット | JSON |
| 認証が必要? | Yes |
| レート制限? | Yes |
**パラメーター[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :------- | :---------------------------------------- | :----- | :----- |
| 名前 | 必須 | 説明 | デフォルト値 | 例 |
| force\_login | optional | 正しいユーザーアカウントが認可されるように、ユーザーに認証情報の入力を強制します。 | | *true* |
| screen\_name | optional | OAuth ログイン画面のユーザー名入力欄を指定された値で事前入力します。 | | |
**リクエスト例[](#example-request "Permalink to this headline")**
oauth\_token パラメーターを含めて、Web ブラウザーでユーザーを `oauth/authenticate` のステップに送ります:
`https://api.x.com/oauth/authenticate?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### POST oauth/access\_token
consumer アプリケーションが OAuth Request Token を OAuth Access Token に交換できるようにします。このメソッドは [OAuth 1.0 認証フロー](http://oauth.net/core/1.0/#anchor9) の [Section 6.3](http://oauth.net/core/1.0/#auth_step3) を満たします。
**リソース URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/access_token`
**リソース情報[](#resource-information "Permalink to this headline")**
| | |
| :---------- | :--- |
| レスポンスフォーマット | JSON |
| 認証が必要? | Yes |
| レート制限? | Yes |
**パラメーター[](#parameters "Permalink to this headline")**
| | | | | |
| :-------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----- | :- |
| 名前 | 必須 | 説明 | デフォルト値 | 例 |
| oauth\_token | required | ここでの oauth\_token は、request\_token ステップで返された oauth\_token と同じである必要があります。 | | |
| oauth\_verifier | required | OAuth の Web フローを使用する場合は、コールバック URL に返された *oauth\_verifier* の値をこのパラメーターに設定してください。out-of-band OAuth を使用している場合は、この値を PIN コードに設定してください。OAuth 1.0a 準拠のため、このパラメーターは **必須** です。OAuth 1.0a は厳密に強制されており、*oauth\_verifier* を使用しないアプリケーションでは OAuth フローを完了できません。 | | |
**リクエスト例[](#example-request "Permalink to this headline")**
`POST https://api.x.com/oauth/access_token?oauth_token=qLBVyoAAAAAAx72QAAATZxQWU6P&oauth_verifier=ghLM8lYmAxDbaqL912RZSRjCCEXKDIzx`
PIN ベースから `POST https://api.x.com/oauth/access_token?oauth_token=9Npq8AAAAAAAx72QBRABZ4DAfY9&oauth_verifier=4868795`
**レスポンス例[](#example-response "Permalink to this headline")**
`oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG5ly3sR3XjE0IBSnlQu4ZrUzPiYTmrkVU&user_id=6253282&screen_name=xapi`
### POST oauth/invalidate\_token
登録済みアプリケーションが、クライアント認証情報を提示することで発行済みの OAuth access\_token を取り消せるようにします。access\_token が無効化されると、新たに作成しようとしても異なる Access Token が発行され、無効化されたトークンの使用は許可されなくなります。
**リソース URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/1.1/oauth/invalidate_token`
**リソース情報[](#resource-information "Permalink to this headline")**
| | |
| :---------- | :------------------------------------------ |
| レスポンスフォーマット | JSON |
| 認証が必要? | Yes - 無効化したい access token を用いた User context |
| レート制限? | Yes |
**リクエスト例[](#example-request "Permalink to this headline")**
```bash theme={null}
curl --request POST
--url 'https://api.x.com/1.1/oauth/invalidate_token.json'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**レスポンス例[](#example-response "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 127
...
{"access_token":"ACCESS_TOKEN"}
```
**トークン無効化後のエラーレスポンス例[](#example-error-response-after-token-has-been-invalidated "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 401 Authorization Required
...
{"errors": [{
"code": 89,
"message": "Invalid or expired token."}
]}
```
### POST oauth2/token
登録済みアプリケーションが、ユーザーコンテキストなしにアプリケーション自身に代わって API リクエストを行うために使用できる OAuth 2 Bearer Token を取得できるようにします。これは [Application-only 認証](/resources/fundamentals/authentication/oauth-2-0/application-only) と呼ばれます。
Bearer Token は oauth2/invalidate\_token を使用して無効化できます。Bearer Token が無効化されると、新たに作成しようとしても異なる Bearer Token が発行され、以前のトークンの使用は許可されなくなります。
アプリケーションに対して有効な bearer token は 1 つのみ存在でき、このメソッドを繰り返し呼び出しても、無効化されるまで同じ既存トークンが返されます。
成功時のレスポンスには、付与された Bearer Token を記述する JSON 構造が含まれます。
このメソッドで受け取ったトークンはキャッシュしておくべきです。あまりに頻繁に試行すると、リクエストは HTTP 403 (コード 99) で拒否されます。
**リソース URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/token`
**リソース情報[](#resource-information "Permalink to this headline")**
| | |
| :---------- | :------------------------------------------------------ |
| レスポンスフォーマット | JSON |
| 認証が必要? | Yes - Basic 認証 (ユーザー名に API キー、パスワードに API キー secret を使用) |
| レート制限? | Yes |
**パラメーター[](#parameters "Permalink to this headline")**
| | | | | |
| :---------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----- | :-------------------- |
| 名前 | 必須 | 説明 | デフォルト値 | 例 |
| grant\_type | required | アプリケーションが要求している grant のタイプを指定します。現時点では *client\_credentials* のみが許可されます。詳しくは [Application-Only Authentication](/resources/fundamentals/authentication/oauth-2-0/application-only) を参照してください。 | | *client\_credentials* |
**リクエスト例[](#example-request "Permalink to this headline")**
```bash theme={null}
POST /oauth2/token HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=client_credentials
```
**レスポンス例:**
```bash theme={null}
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
```
### POST oauth2/invalidate\_token
登録済みアプリケーションが、クライアント認証情報を提示することで発行済みの oAuth 2.0 Bearer Token を取り消せるようにします。Bearer Token が無効化されると、新たに作成しようとしても異なる Bearer Token が発行され、無効化されたトークンの使用は許可されなくなります。
成功時のレスポンスには、取り消された Bearer Token を記述する JSON 構造が含まれます。
**リソース URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/invalidate_token`
**リソース情報[](#resource-information "Permalink to this headline")**
| | |
| :---------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
| レスポンスフォーマット | JSON |
| 認証が必要? | Yes - アプリケーションの consumer API キーとアプリケーション所有者の access token および access token secret を用いた [oAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a) |
| レート制限? | Yes |
**パラメーター[](#parameters "Permalink to this headline")**
| 名前 | 必須 | 説明 |
| :------------ | :------- | :--------------------- |
| access\_token | required | 無効化したい bearer token の値 |
**リクエスト例[](#example-request "Permalink to this headline")**
```
curl --request POST
--url 'https://api.x.com/oauth2/invalidate_token?access_token=AAAA%2FAAA%3DAAAAAAAA'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**レスポンス例[](#example-response "Permalink to this headline")**
```
Status: 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 135
...
{
"access_token": "AAAA%2FAAA%3DAAAAAAAA"
}
```
# ベーシック認証
Source: https://docs.x.com/ja/fundamentals/authentication/basic-auth
HTTP ベーシック認証を使用して、メールとパスワードを HTTPS 経由で送信し、PowerTrack、Decahose、Search などの X エンタープライズ API にアクセスします。認証ヘッダーの生成、Base64 エンコード、資格情報の保護、失敗時のトラブルシューティングも解説します。
## ベーシック認証
X のエンタープライズ API の多くは HTTP ベーシック認証の使用を必要とします。ベーシック認証を必要とする API へのリクエストを成功させるには、各リクエストの認証ヘッダーとして有効なメールアドレスとパスワードの組み合わせを渡す必要があります。メールとパスワードの組み合わせは、[エンタープライズ API コンソール](https://console.gnip.com/) へのアクセスに使用するものと同じであり、このコンソール内から編集できます。
ベーシック認証を使用してリクエストを構築する際は、HTTPS 経由でエンコードされた認証情報を含む Authentication: Basic HTTP ヘッダーを追加してください。
次の cURL リクエスト例では、リクエストを送信する前に `` と `` を認証情報に置き換えます:
```bash theme={null}
curl -v --compressed -u:
"https://gnip-api.x.com/search/30day/accounts//prod/counts.json?query=from%3Axdevelopers"
```
**ベーシック認証を必要とする API:**
* [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) enterprise
* [Decahose stream API](http://localhost:3000/x-api/enterprise-gnip-2.0/fundamentals/decahose-api) enterprise
* [30-Day Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Full-Archive Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Usage API](/x-api/enterprise-gnip-2.0/fundamentals/usage) enterprise
# OAuth FAQ
Source: https://docs.x.com/ja/fundamentals/authentication/faq
X API を使用する際の OAuth 1.0a、OAuth 2.0、アクセストークン、スコープ、認証エラーに関するよくある質問への回答。Bearer トークンの取得、PKCE のフロー、リフレッシュトークン、コールバック URL のトラブルシューティングをカバーします。
## 全般
OAuth は、ユーザーがパスワードを共有せずにアプリケーションを承認し、自分に代わって動作させることができる認証プロトコルです。詳細は [oauth.net](http://oauth.net/) で確認できます。
アクセストークンを生成するには [X アプリ](/resources/fundamentals/developer-apps) が必要です。アクセストークンの詳細については [こちら](/resources/fundamentals/authentication#oauth-1-0a-2) を参照してください。
[X アプリ](/resources/fundamentals/developer-apps) を作成するには [デベロッパーアカウント](/resources/fundamentals/developer-portal) が必要です。[こちら](https://developer.x.com/en/portal/petition/essential/basic-info) から登録できます。
developer.x.com に X アカウントでログインしている場合は、[X アプリダッシュボード](https://developer.x.com/content/developer-twitter/en/apps) からアプリを表示および編集できます。
## 技術
アクセストークンには明示的な有効期限はありません。アクセストークンは、ユーザーが X アカウント設定でアプリケーションを明示的に取り消した場合や、X がアプリケーションを停止した場合に無効になります。アプリケーションが停止されている場合は、[X アプリ](/resources/fundamentals/developer-apps) ダッシュボードに停止された旨の注記が表示されます。
ユーザーのアクセストークンは *いつでも* 無効になる可能性があると想定してください。これが発生した場合は、ユーザーにアプリケーションの再認可を促してください。この状況を適切に処理することは、優れたユーザー体験のために重要です。
多くのユーザーは、アプリケーションに情報を読み取らせることは信頼しますが、必ずしもユーザープロフィール情報を変更したり、新しいステータスを投稿したりすることは信頼しません。X API を介して情報 (名前、場所、または新しいステータスの追加) を更新するには、HTTP POST が必要です。HTTP POST を必要とする API メソッドは書き込みメソッドと見なされ、読み取り & 書き込みアクセスが必要です。
# ベストプラクティス
Source: https://docs.x.com/ja/fundamentals/authentication/guides/authentication-best-practices
API キーとトークンは細心の注意を払って保護する必要があります。これらの認証情報は、あなたのデベロッパーアプリおよびそれを認可した X アカウントに直接紐づいています。
API キーとトークンは細心の注意を払って保護する必要があります。
これらの認証情報は、あなたの [デベロッパーアプリ](/resources/fundamentals/developer-apps) と、あなたに代わってリクエストを行うことを許可した X アカウントに直接紐づいています。キーが漏洩すると、悪意のある第三者がそれらを使ってあなたのデベロッパーアプリまたはその認可済みユーザーに代わって X エンドポイントにリクエストを送る可能性があります。その結果、想定外のレート制限に達したり、有料アクセスの割り当てを使い果たしたり、さらにはデベロッパーアプリが停止される可能性もあります。
以下のセクションでは、API キーとトークンを管理する際に検討すべきベストプラクティスを紹介します。
## API キーとトークンを再生成する
API キーが漏洩したと思われる場合は、以下の手順で API キーを再生成してください:
1. [Developer Console の「Apps」ページ](https://developer.x.com/en/portal/projects-and-apps.html) に移動します。
2. 該当するアプリの横にある「Keys and tokens」アイコン (🗝) をクリックします。
3. 再生成したいキーとトークンのセットの横にある「Regenerate」ボタンをクリックします。
Access Token または Bearer Token をプログラム的に再生成したい場合は、認証エンドポイントを使用できます。
* Access Token を再生成したい場合は、[POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) エンドポイントでトークンを無効化してから、[3-legged OAuth フロー](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) でトークンを再生成する必要があります。
* Bearer Token を再生成したい場合は、[POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) エンドポイントでトークンを無効化してから、[POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) エンドポイントでトークンを再生成する必要があります。
## シークレット用の集中ファイルを持つ
.ENV ファイルやその他の .yaml ファイルなど、シークレットを格納するファイルを利用することは有効な選択肢の 1 つですが、誤って git リポジトリにコミットしないよう、しっかりとした .gitignore ファイルを用意してください。
## 環境変数
環境変数を利用するコードを書くことも役立ちます。
以下は Python で書かれた例です:
```python theme={null}
import os
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")
```
ターミナルでは次のように書きます:
```bash theme={null}
export CONSUMER_KEY='xxxxxxxxxxxxxxxxxxx'
export CONSUMER_SECRET='xxxxxxxxxxxxxxxxxxxxxxx'
```
## ソースコードとバージョン管理
デベロッパーが犯す最も一般的なセキュリティミスは、GitHub や BitBucket などのアクセス可能なバージョン管理システムに API キーとトークンをコミットしてしまうことです。これらのコードリポジトリの多くは公開されています。この間違いは公開コードリポジトリで頻繁に発生しており、API キーをスクレイピングする収益性の高いボットが存在するほどです。
* サーバーの環境変数を使用してください。API キーを環境変数に格納することで、コードやバージョン管理から切り離せます。これによって環境ごとに異なるキーを簡単に使用することも可能になります。
* ソース管理から除外した設定ファイルを使用してください。ファイル名を [.gitignore](https://git-scm.com/docs/gitignore) ファイルに追加して、そのファイルがバージョン管理で追跡されないようにします。
* バージョン管理を使用した後にコードから API キーを削除しても、以前のコードベースにアクセスすれば依然として API キーにアクセスできる可能性があります。次のセクションで説明するとおり、API キーを再生成してください。
## データベース
access token をデータベースに保存する必要がある場合は、以下の点に留意してください:
* データベースへのアクセスを制限し、access token がそのトークンの所有者のみに読み取り可能となるようにします。
* access token を格納するデータベーステーブルへの編集/書き込み権限を制限してください — これはキー管理システムで自動化する必要があります。
* データストアに保存する前に access token を暗号化してください。
## パスワード管理ツール
1password や Last Pass などのパスワード管理ツールは、キーとトークンを安全な場所に保管するのに役立ちます。共有チームのパスワード管理ツール内でこれらを共有することは避けたほうがよいでしょう。
## Web ストレージとクッキー
Web ストレージには 2 種類あります: LocalStorage と SessionStorage。Web ストレージのストレージ容量は Cookie ストレージよりもはるかに大きいため、これらは Cookie を使用する場合の改善として作成されました。ただし、これらのストレージオプションにはそれぞれ異なる利点と欠点があります。
**Web ストレージ: LocalStorage**
ローカル Web ストレージに保存されたものは永続的です。つまり、明示的に削除されるまでデータは保持されます。プロジェクトのニーズによっては、これを利点と捉えることもあります。ただし、対象の Web ページへの以降のすべての訪問でデータへの変更/追加が利用可能になるため、LocalStorage の使用には注意が必要です。通常、いくつかの例外を除いて LocalStorage の使用は推奨しません。LocalStorage を使用する場合、同一オリジンポリシーをサポートしているため、ここに保存されるすべてのデータは同じオリジン経由でのみアクセスできる点を覚えておいてください。データを HTTP リクエストのたびにサーバーに送り返す必要がないため、クライアント-サーバー間のトラフィックが減るというパフォーマンス上のメリットもあります。
**Web ストレージ: SessionStorage**
SessionStorage は LocalStorage に似ていますが、大きな違いは SessionStorage が永続的ではないことです。SessionStorage への書き込みに使用したウィンドウ (使用しているブラウザーによってはタブ) が閉じられると、データは失われます。これは、ユーザーセッション内でトークンへの読み取りアクセスを制限するのに便利です。セキュリティの観点で考えると、通常は LocalStorage よりも SessionStorage を使うほうが好ましいです。LocalStorage と同様に、同一オリジンポリシーのサポートやクライアント-サーバー間のトラフィック減少のメリットは SessionStorage にも適用されます。
**Cookie**
Cookie はセッションデータを保存するより従来からの方法です。各 Cookie に有効期限を設定でき、これによってアクセスの取り消しや制限が容易になります。ただし、Cookie を使用するとデータは HTTP リクエストのたびにサーバーに送り返されるため、クライアント-サーバー間のトラフィックは確実に増加します。Cookie を使用する場合、セッションハイジャックから保護する必要があります。デフォルトでは、Cookie は HTTP でプレーンテキストで送信されるため、内容がパケットスニッフィングや、攻撃者がトラフィックを改ざんする中間者攻撃に対して脆弱になります。通信中のデータを保護するために HTTPS を必ず強制してください。これにより、機密性、(データの) 整合性、および認証が提供されます。ただし、Web アプリケーションやサイトが HTTP と HTTPS の両方で利用可能な場合は、Cookie に 'Secure' フラグも使用するとよいでしょう。これにより、攻撃者がサイトの HTTP バージョンへのリンクをユーザーに送り、それに伴って生成される HTTP リクエストを盗聴することを防げます。
Cookie を使用する際のセッションハイジャックに対する二次的な防御としては、影響の大きいアクションを実行する前に再度ユーザーの身元を検証する方法があります。Cookie のセキュリティを高めるために検討するもう 1 つのフラグは 'HttpOnly' フラグです。このフラグは、対象の Cookie が指定されたサーバーからのみアクセス可能であることをブラウザーに伝えます。クライアント側のスクリプトによる試行はこのフラグにより禁止されるため、ほとんどのクロスサイトスクリプティング (XSS) 攻撃から保護するのに役立ちます。
# Log in with X
Source: https://docs.x.com/ja/fundamentals/authentication/guides/log-in-with-x
OAuth 1.0a の request token フローを使って、Web サイトやモバイルアプリで Sign in with X を実装し、ユーザーを認証して access token を取得します。
Log in with X (Sign in with X とも呼ばれます) を使用すると、サイトやアプリケーション上にボタンを配置でき、X ユーザーがワンクリック程度で登録済みユーザーアカウントの利便性を享受できます。これは Web サイト、iOS、モバイル、およびデスクトップアプリケーションで動作します。
## 特徴
* 使いやすさ - サイトへの新規訪問者は、初回ログイン時にわずか 2 つのボタンをクリックするだけで済みます。
* X との連携 - Log in with X フローにより、ユーザーに代わって X API を使用する認可を付与できます。
* OAuth ベース - 豊富なクライアントライブラリとサンプルコードが Log in with X API と互換性があります。
## 利用可能な対象
* ブラウザー - ユーザーがブラウザーにアクセスできる場合、Log in with X を統合できます。ブラウザーサインインフローについて確認してください。
* モバイルデバイス - Web に接続できる任意のモバイルデバイスで Log in with X を利用できます。モバイルサインインフローについて確認してください。
## Log in with X の実装
Log in with X のブラウザーおよびモバイル Web の実装は OAuth に基づいています。このページでは、サインインフロー用の access token を取得するために必要なリクエストを示します。
「Log in with X」フローを使用するには、[X アプリ設定](/resources/fundamentals/developer-apps) に移動し、「*Allow this app to be used to Sign in with X?*」オプションが有効になっていることを確認してください。
このページでは、読者が OAuth 1.0a プロトコルを使ってリクエストに署名する方法を知っていることを前提としています。リクエストへの署名方法を知りたい場合は、[リクエストの認可](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request) ページをご覧ください。
このページのリクエストの署名を確認したい場合、使用されている consumer secret は次のとおりです: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg。この値はテスト目的で、実際のリクエストでは動作しません。
Log in with X を実装する 3 つのステップ (request token の取得、ユーザーのリダイレクト、request token から access token への変換) は以下のとおりです。
### ステップ 1: request token の取得
サインインフローを開始するには、[X アプリ](/resources/fundamentals/developer-apps) が [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) に署名済みメッセージを送って request token を取得する必要があります。このリクエストで唯一固有のパラメーターは oauth\_callback で、ステップ 2 が完了したときにユーザーをリダイレクトさせたい URL の URL エンコード版でなければなりません。残りのパラメーターは OAuth 署名プロセスによって追加されます。
**注:** [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) エンドポイントで使用する [callback URL](/resources/fundamentals/developer-apps#callback-urls) は、[Developer Console](/resources/fundamentals/developer-portal) の [X アプリ設定](/resources/fundamentals/developer-apps) 内に登録されている必要があります。
**リクエスト例 (Authorization ヘッダーは折り返されています):**
```
POST /oauth/request_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization:
OAuth oauth_callback="http%3A%2F%2Flocalhost%2Fsign-in-with-twitter%2F",
oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="ea9ec8429b68d6b77cd5600adbbb0456",
oauth_signature="F1Li3tvehgcraF8DMJ7OyxO4w9Y%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_version="1.0"
```
アプリはレスポンスの HTTP ステータスを確認する必要があります。200 以外の値は失敗を示します。レスポンスの本文には oauth\_token、oauth\_token\_secret、oauth\_callback\_confirmed パラメーターが含まれます。アプリは oauth\_callback\_confirmed が true であることを確認し、次のステップのために他の 2 つの値を保存する必要があります。
**レスポンス例 (レスポンス本文は折り返されています):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:06 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 146
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI&
oauth_callback_confirmed=true
```
### ステップ 2: ユーザーのリダイレクト
次のステップは、以下の「ブラウザーサインインフロー」で説明されているように、ユーザーを X にリダイレクトして適切なフローを完了してもらうことです。ユーザーを [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) にリダイレクトし、ステップ 1 で取得した request token を oauth\_token パラメーターとして渡します。
Web サイトでこれを実装する最もシームレスな方法は、元の「サインイン」リクエストへのレスポンスとして HTTP 302 リダイレクトを発行することです。モバイルおよびデスクトップアプリでは、新しいブラウザーウィンドウを開くか、埋め込みの Web ビューで URL に遷移する必要があります。
**リダイレクト先の URL 例:**
[https://api.x.com/oauth/authenticate?oauth\_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0](https://api.x.com/oauth/authenticate?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0)
サインインエンドポイントは、ユーザーのステータスに応じて 3 つのうちいずれかの挙動をとります:
1. **サインイン済みかつ承認済み**: ユーザーが x.com にサインインしており、既に呼び出し元アプリケーションを承認している場合、直ちに認証され、有効な OAuth request token とともにコールバック URL に戻されます。x.com へのリダイレクトはユーザーには明示的には見えません。
2. **サインイン済みだが未承認**: ユーザーが x.com にサインインしているが、呼び出し元アプリケーションを承認していない場合、呼び出し元アプリケーションとアクセスを共有するリクエストが表示されます。承認リクエストを受け入れた後、ユーザーは有効な OAuth request token とともにコールバック URL にリダイレクトされます。
3. **未サインイン**: ユーザーが x.com にサインインしていない場合、同じ画面上で認証情報を入力し、アプリケーションが自分の情報にアクセスするための許可を付与するよう促されます。サインイン後、ユーザーは有効な OAuth request token とともにコールバック URL に戻されます。
認証に成功すると、callback\_url は oauth\_token と oauth\_verifier のパラメーターを含むリクエストを受け取ります。アプリケーションは、トークンがステップ 1 で受け取った request token と一致することを確認する必要があります。
**クライアントのリダイレクトからのリクエスト (クエリ文字列パラメーターは折り返されています):**
```
GET /sign-in-with-twitter/?
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.5 (KHTML, like Gecko) Chrome/16.0.891.1 Safari/535.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://localhost/sign-in-with-twitter/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
```
### ステップ 3: request token を access token に変換する
request token を利用可能な access token にレンダリングするには、アプリケーションはステップ 2 で取得した oauth\_verifier の値を含めて [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) エンドポイントにリクエストを行う必要があります。request token はヘッダーの oauth\_token 部分でも渡されますが、これは署名プロセスで追加されているはずです。
**リクエスト例 (Authorization ヘッダーは折り返されています):**
```
POST /oauth/access_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
oauth_version="1.0"
Content-Length: 57
Content-Type: application/x-www-form-urlencoded
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
```
成功したレスポンスには oauth\_token、oauth\_token\_secret パラメーターが含まれます。この token と token secret は保存し、以降の X API への認証済みリクエストで使用します。ユーザーの身元を確認するには、[GET account/verify\_credentials](https://dev.x.com/rest/reference/get/account/verify_credentials) を使用してください。
**レスポンス例 (レスポンス本文は折り返されています):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:08 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 157
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4&
oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo
```
### Log in with X のリソース
#### クライアントライブラリ
[X libraries](/resources/tools-and-libraries) に掲載されているクライアントライブラリは、Log in with X の実装に役立ちます。前の手順で説明したとおり、/oauth/authenticate エンドポイントを使用してください。
#### Brand Toolkit
X では、一貫したブランディングのために公式の [X Brand Toolkit](https://about.x.com/en/who-we-are/brand-toolkit) をアプリケーションで使用することをお勧めします。これらの資産を保存し、「Login with X」ボタンを作成する際に使用してください。
ブラウザーログインフローは、Web ブラウザーを開くまたは埋め込むことができる Web サイトやアプリケーションに適しています。非常に高いレベルで見ると:
* アプリケーションが「Sign in with X」リンクまたはボタンをレンダリングします。
* ユーザーがサインインボタンをクリックします。
* 現在の Web ブラウザーが X にリダイレクトされます (または新しいブラウザーが開かれて X に遷移します)。
* 必要に応じて、ユーザーは X でログインおよび認可のステップを完了します。
* X はユーザーの認可情報を渡して、アプリケーションの管理下にある URL にリダイレクトします。
X は認可を記録するため、X.com にすでにサインインしていてアプリケーションを認可済みのユーザーには UI が表示されず、代わりに自動的にアプリケーションにリダイレクトされます。
### デスクトップフロー
このフローを示すため、上に描かれている Web サイト (「The greatest website ever created」) がランディングページの「Sign in with X」ボタンのように、この API を実装していると仮定してください。
ユーザーが Sign in ボタンをクリックすると、表示されるページはユーザーがサインインしているかどうか、および以前にアプリケーションのアカウントへのアクセスを許可しているかどうかによって異なります。
ユーザーが x.com にサインインしているがアクセスを付与していない場合、要求される権限のリストと Sign In および Cancel ボタンが表示されます。
ユーザーが x.com にサインインしていない場合、ユーザー名とパスワードの入力欄が表示されます。ユーザーが既にアプリケーションへのアクセスを付与している場合でも、権限のリストは表示されることに注意してください。
ユーザーが有効な認証情報を入力し (必要な場合)、「Sign In」をクリックすると、X はサインインフローを開始した Web サイトにユーザーをリダイレクトします。
ユーザーが既に x.com にサインインしており、Web サイトへのアクセスを付与している場合、このリダイレクトはすぐに行われます。
モバイル Web ブラウザー向けの UI フローは、ブラウザーサインインフローとまったく同じように動作しますが、モバイルブラウザー向けに最適化されています。
以下は、サインイン済み、未サインイン、リダイレクトの各画面のスクリーンショットです:
# TLS を使用した X API への接続
Source: https://docs.x.com/ja/fundamentals/authentication/guides/tls
TLS 1.2 で X API に安全に接続する方法。信頼できるルートストア、証明書失効チェック、HTTPS 検証の実践に関するガイダンスを提供します。
X API エンドポイントにアクセスするには TLS 接続が必要です。TLS 経由で通信することで、ユーザーと X API 間の情報がパブリックインターネットを移動する際に、ユーザーのプライバシーとセキュリティが保護されます。X API への接続には TLS バージョン 1.2 が必要です。
## 検証
### 最新のルートストアを使用する
アプリケーションまたはライブラリが X の証明書を検証する際、信頼できる最新のルートストアを使用することが重要です。可能であれば、オペレーティングシステムが提供するルートストアを使用するのが最もシンプルなアプローチかもしれません。代替として、[Mozilla (NSS) root store](https://www.mozilla.org/en-US/about/governance/policies/security-group/certs/) は公開かつ透明性のある形で適切にメンテナンスされています。Curl も [PEM 形式でのこのストアのバージョン](https://curl.haxx.se/docs/caextract.html) を提供しています。
現在、X の証明書の大部分は [DigiCert High Assurance EV Root CA](https://www.digicert.com/digicert-root-certificates.htm) から発行されていますが、X 関連のすべての証明書が該当するわけではなく、この状況が今後も続くとは限りません。そのため、現在使用されている DigiCert のルートだけを信頼する構成にすると、将来アプリで問題が発生する可能性があります。
### CRL および OCSP のステータスをチェックする[](#check-crls-and-the-ocsp-status "Permalink to this headline")
多くのアプリケーションは、返された証明書の証明書失効リスト (CRL) をチェックしなかったり、その処理をオペレーティングシステムに任せています。X の証明書を受け入れる前に、アプリケーションまたは TLS ライブラリが CRL および OCSP (Online Certificate Status Protocol) の検証を強制するよう設定されていることを確認してください。
### CDN[](#cdns "Permalink to this headline")
メディアを含む Tweet を表示する際、画像の表示に使用する HTTPS URL には `media_url_https` 属性を使用してください。将来的には、API エンドポイントから提供されるすべての URL が HTTPS パスを提供するようになります。
## セキュリティステータスの表示
可能であれば、アプリケーションと X の現在の接続ステータスの表示を行ってください。一部の Web ブラウザーは Lock Icon でこれを示し、他のブラウザーは説明的なメッセージで現在の接続状態を示します。
# X API v2 認証マッピング
Source: https://docs.x.com/ja/fundamentals/authentication/guides/v2-authentication-mapping
以下の表は、どの v2 エンドポイントがどの認証方式に対応するかを示しています。X Developer Platform の v2 認証に関するドキュメントです。
以下の表は、どの v2 エンドポイントがどの認証方式に対応するかを示しています。
| | | | |
| :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **エンドポイント** | **OAuth 1.0a User Context** | **OAuth 2.0** **App Only ** | **OAuth 2.0 Authorization Code with PKCE** |
| [Tweet lookup](/x-api/posts/lookup/introduction)
***
## 主な機能
### 豊富なデータオブジェクト
投稿、ユーザー、メディアなどの詳細で構造化されたデータにアクセス:
* **投稿**: フルテキスト、メトリクス、エンティティ、アノテーション、会話スレッド
* **ユーザー**: プロフィール、フォロワー数、認証ステータス
* **メディア**: メタデータ付き画像、動画、GIF
* **投票**: 選択肢と投票数
必要なデータだけを取得するために、[fields](/x-api/fundamentals/fields) と [expansions](/x-api/fundamentals/expansions) でレスポンスをカスタマイズします。
### Filtered stream
投稿が公開されると、ほぼリアルタイムで配信されます。最大 1,000 のフィルタリングルールを定義し、マッチする投稿のみを受信できます。
```bash theme={null}
# ルールを追加
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $TOKEN" \
-d '{"add": [{"value": "from:xdevelopers"}]}'
# ストリームに接続
curl "https://api.x.com/2/tweets/search/stream" \
-H "Authorization: Bearer $TOKEN"
```
[Filtered stream の詳細はこちら →](/x-api/posts/filtered-stream/introduction)
### Full-archive search
公開投稿の完全な履歴 — 2006 年までさかのぼって検索できます。ユーザー、キーワード、日付などの演算子でクエリを構築します。
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?query=AI%20lang:en" \
-H "Authorization: Bearer $TOKEN"
```
### メトリクス
インプレッション、いいね、リポスト、返信、動画再生数を含むエンゲージメントメトリクスにアクセス。
[検索の詳細はこちら →](/x-api/posts/search/introduction)
***
## クイックスタート
[console.x.com](https://console.x.com) でサインアップしてアプリを作成します。
アプリのみリクエスト用に Bearer Token を生成します。
ユーザーの検索を試してみてください:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## ツール & ライブラリ
非同期サポート付きの公式 Python ライブラリ。
公式 TypeScript/JavaScript ライブラリ。
インタラクティブな API エクスプローラ。
[すべてのライブラリを参照する →](/tools-and-libraries)
***
## サポート
コミュニティと X チームから助けを得られます。
FAQ とトラブルシューティングガイド。
# X API 概要
Source: https://docs.x.com/ja/x-api/overview
Posts、users、Spaces、Direct Messages、lists、trends、media、compliance、streaming、webhook エンドポイントを網羅した X API v2 の完全なリファレンス。
X API は X の公開会話へのプログラム的なアクセスを提供します。以下のすべてのエンドポイントは [従量課金制 (pay-per-use)](/x-api/introduction) プランで利用できます。Enterprise 専用と記載されているエンドポイントには [Enterprise](/enterprise-api/introduction) プランが必要です。
***
## エンドポイント
投稿の検索、取得、公開を行います。タイムライン、スレッド、引用投稿にアクセスできます。
プロフィールの参照、フォロー、ブロック、ミュートの管理を行います。
プライベートメッセージの送受信を行います。
ライブ音声会話と参加者を検索できます。
キュレーションされたアカウントのリストを作成・管理します。
投稿にいいねをつけたり取り消したりします。誰が投稿にいいねをつけたかを参照できます。
地域別のトレンドトピックとパーソナライズされたトレンド。
画像、動画、GIF をアップロードします。字幕とメタデータを管理します。
コミュニティを検索・参照できます。
Community Notes の作成、評価、検索を行います。
ニュース記事を検索・取得します。
バッチコンプライアンスジョブおよびコンプライアンスストリーム。
***
## ストリーミングとリアルタイム
フィルタールールに一致する投稿をリアルタイムで受け取ります。
フォロー、いいね、プロフィール更新などのリアルタイムアクティビティイベントを購読します。
HTTP コールバックでイベントデータを受け取ります。
***
## Enterprise 限定
これらのエンドポイントには [Enterprise プラン](/enterprise-api/introduction) が必要です。
フルファイアホースおよび言語別ストリーム。
すべての、またはサンプリングされたいいねをリアルタイムでストリーミングします。
高度な演算子に対応した高性能フィルタリングストリーミング。
大規模な投稿・メディアのエンゲージメント指標。
リアルタイムのユーザーイベントサブスクリプション。
webhook 経由での filtered stream 配信。
***
## クイックスタート
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
認証情報を取得して、数分で API を呼び出しましょう。
Python と TypeScript の公式ライブラリ。
# Filtered Stream のオペレーター
Source: https://docs.x.com/ja/x-api/posts/filtered-stream/integrate/operators
X API v2 Filtered Stream のオペレーター完全リファレンス。ストリームルール向けの keyword、has:、is:、および Enterprise 限定のセマンティック embedding: オペレーターを網羅します。ブール論理、否定、フレーズ一致、言語や地域フィルターの組み合わせも解説します。
このページでは、Filtered Stream の [ルール作成](/x-api/posts/filtered-stream/integrate/build-a-rule) で利用可能なオペレーターの完全な一覧を提供します。
## 概要
オペレーターは、投稿の特定の属性にマッチさせるために使用します。次の 2 種類があります:
* **スタンドアロンオペレーター** — 単独でも、他のオペレーターと組み合わせても使用可能
* **接続必須オペレーター** — 少なくとも 1 つのスタンドアロンオペレーターと組み合わせて使用する必要があります
ほとんどのオペレーターは Pay-per-use と Enterprise の両方で利用可能です。一部の高度なオペレーター (セマンティック embedding など) は、追加のティアアクセスを伴う Enterprise が必要です。
***
## キーワードおよびフレーズオペレーター
| Operator | Type | Summary | Example |
| :---------------------- | :--------- | :---------------------------------- | :------------------------------------ |
| `keyword` | Standalone | 投稿本文内のキーワードにマッチ (トークン化マッチ) | `pepsi OR cola OR "coca cola"` |
| `emoji` | Standalone | 投稿本文内の絵文字にマッチ | `(😃 OR 😡) 😬` |
| `"exact phrase"` | Standalone | 投稿本文内の完全一致フレーズにマッチ | `("X API" OR #v2) -"filtered stream"` |
| `"keyword1 keyword2"~N` | Standalone | 近接マッチ — 互いに N トークン以内のキーワード (最大 N=6) | `"social media"~5` |
***
## エンティティオペレーター
| Operator | Type | Summary | Example |
| :------- | :--------- | :--------------------- | :--------------------------- |
| `#` | Standalone | ハッシュタグを含む投稿にマッチ (完全一致) | `#thankunext #fanart` |
| `@` | Standalone | ユーザー名へのメンションを含む投稿にマッチ | `(@XDevelopers OR @api) -@x` |
| `$` | Standalone | キャッシュタグを含む投稿にマッチ | `$twtr OR @XDevelopers -$fb` |
***
## ユーザーオペレーター
| Operator | Type | Summary | Example |
| :------------------- | :--------- | :----------------------- | :------------------------------ |
| `from:` | Standalone | 特定のユーザーからの投稿にマッチ | `from:XDevelopers OR from:api` |
| `to:` | Standalone | 特定のユーザーへの返信にマッチ | `to:XDevelopers OR to:api` |
| `retweets_of:` | Standalone | 特定のユーザーのリポストにマッチ | `retweets_of:XDevelopers` |
| `from_affiliate_of:` | Standalone | 特定のユーザーのアフィリエイトからの投稿にマッチ | `from_affiliate_of:XDevelopers` |
| `to_affiliate_of:` | Standalone | 特定のユーザーのアフィリエイトへの返信にマッチ | `to_affiliate_of:XDevelopers` |
***
## URL オペレーター
| Operator | Type | Summary | Example |
| :----------------- | :--------- | :------------------------------------------------- | :------------------------------ |
| `url:` | Standalone | URL のトークン化マッチ (`url` または `expanded_url` フィールドにマッチ) | `url:"https://developer.x.com"` |
| `url_title:` | — | 展開された URL の HTML タイトルメタデータに対するキーワードマッチ | `url_title:snow` |
| `url_description:` | — | 展開されたページの説明メタデータに対するキーワードマッチ | `url_description:weather` |
| `url_contains:` | — | URL コンテンツに対するリテラルマッチ | `url_contains:photos` |
***
## コンテキストおよびエンティティオペレーター
| Operator | Type | Summary | Example |
| :----------------- | :--------- | :------------------------- | :------------------------------------------------- |
| `context:` | Standalone | 特定のドメイン/エンティティのペアを持つ投稿にマッチ | `context:10.799022225751871488` または `context:47.*` |
| `entity:` | Standalone | 特定のエンティティ文字列値を持つ投稿にマッチ | `entity:"Michael Jordan"` |
| `conversation_id:` | Standalone | 会話スレッド内の投稿にマッチ | `conversation_id:1334987486343299072` |
***
## ユーザープロフィールオペレーター
| Operator | Type | Summary | Example |
| :-------------- | :--------- | :------------------ | :--------------------------------------------- |
| `bio:` | Standalone | 投稿者の自己紹介内のキーワードにマッチ | `bio:developer OR bio:"data engineer"` |
| `bio_name:` | Standalone | 投稿者の名前内のキーワードにマッチ | `bio_name:phd OR bio_name:md` |
| `bio_location:` | Standalone | 投稿者の所在地内のキーワードにマッチ | `bio_location:"big apple" OR bio_location:nyc` |
***
## ロケーションオペレーター
| Operator | Type | Summary | Example |
| :--------------- | :--------- | :------------------ | :---------------------------------------------------------- |
| `place:` | Standalone | ロケーションタグ付きの投稿にマッチ | `place:"new york city" OR place:seattle` |
| `place_country:` | Standalone | 国コードを持つ投稿にマッチ | `place_country:US OR place_country:MX` |
| `point_radius:` | Standalone | ある地点の半径内の投稿にマッチ | `point_radius:[2.355128 48.861118 16km]` |
| `bounding_box:` | Standalone | バウンディングボックス内の投稿にマッチ | `bounding_box:[-105.301758 39.964069 -105.178505 40.09455]` |
***
## 投稿タイプオペレーター
| Operator | Type | Summary | Example |
| :------------- | :------------------- | :------------------------ | :------------------------------ |
| `is:retweet` | Conjunction required | リポストにマッチ | `data @XDevelopers -is:retweet` |
| `is:reply` | Conjunction required | 返信にマッチ | `from:XDevelopers is:reply` |
| `is:quote` | Conjunction required | 引用投稿にマッチ | `"sentiment analysis" is:quote` |
| `is:verified` | Conjunction required | 認証済みアカウントの投稿にマッチ | `#nowplaying is:verified` |
| `-is:nullcast` | Conjunction required | プロモーション投稿を除外 (否定形での使用が必須) | `"mobile games" -is:nullcast` |
***
## コンテンツタイプオペレーター
| Operator | Type | Summary | Example |
| :--------------- | :------------------- | :------------------------- | :----------------------------------- |
| `has:hashtags` | Conjunction required | ハッシュタグを含む投稿にマッチ | `from:XDevelopers -has:hashtags` |
| `has:cashtags` | Conjunction required | キャッシュタグを含む投稿にマッチ | `#stonks has:cashtags` |
| `has:links` | Conjunction required | リンクを含む投稿にマッチ | `from:XDevelopers has:links` |
| `has:mentions` | Conjunction required | メンションを含む投稿にマッチ | `#nowplaying has:mentions` |
| `has:media` | Conjunction required | メディア (写真、GIF、動画) を含む投稿にマッチ | `(kittens OR puppies) has:media` |
| `has:images` | Conjunction required | 画像を含む投稿にマッチ | `#meme has:images` |
| `has:video_link` | Conjunction required | ネイティブの X 動画を含む投稿にマッチ | `#icebucketchallenge has:video_link` |
| `has:geo` | Conjunction required | ジオロケーションデータを含む投稿にマッチ | `recommend #paris has:geo` |
***
## サンプリングおよび言語オペレーター
| Operator | Type | Summary | Example |
| :-------- | :------------------- | :----------------------- | :------------------------------- |
| `sample:` | Conjunction required | ランダムな割合のサンプル (1-100) を返す | `#nowplaying @spotify sample:15` |
| `lang:` | Conjunction required | 特定の言語に分類された投稿にマッチ | `recommend #paris lang:en` |
***
## ユーザーメトリクスオペレーター
| Operator | Type | Summary | Example |
| :----------------- | :--- | :--------------------------- | :---------------------------- |
| `min_followers:` | — | 指定した数以上のフォロワーを持つユーザーの投稿にマッチ | `min_followers:1000` |
| `followers_count:` | — | フォロワー数が範囲内のユーザーの投稿にマッチ | `followers_count:1000..10000` |
| `tweets_count:` | — | 投稿数が範囲内のユーザーの投稿にマッチ | `tweets_count:1000..10000` |
| `following_count:` | — | フォロー数が範囲内のユーザーの投稿にマッチ | `following_count:1000..10000` |
| `listed_count:` | — | 指定した数のリストに登録されているユーザーの投稿にマッチ | `listed_count:10..100` |
***
## 投稿参照オペレーター
| Operator | Type | Summary | Example |
| :---------------------- | :--- | :---------------------- | :----------------------------------------- |
| `in_reply_to_tweet_id:` | — | 特定の投稿への返信にマッチ | `in_reply_to_tweet_id:1539382664746020864` |
| `retweets_of_tweet_id:` | — | 特定の投稿のリポストにマッチ | `retweets_of_tweet_id:1539382664746020864` |
| `source:` | — | 特定のソースアプリケーションからの投稿にマッチ | `source:"X for iPhone"` |
***
## 論理オペレーター
| Operator | Summary | Example |
| :---------- | :------------ | :------------------------- |
| `OR` | 式間の論理 OR | `cat OR dog` |
| Space (AND) | 式間の論理 AND | `cat dog` (両方必須) |
| `()` | 複雑な式のためのグループ化 | `(cat OR dog) -is:retweet` |
| `-` | 否定/除外 | `cat -grumpy` |
***
## 埋め込みオペレーター
**Enterprise 限定 — Embedding ティアが必要**
`embedding:` および `embedding_threshold:` オペレーターは、Filtered Stream 向けに Embedding ティアアクセスがプロビジョニングされた Enterprise アカウントでのみ利用可能です。サポートされていないティアでは、ルール作成は "unavailable operator" エラーで拒否されます。有効化についてはアカウント担当者にお問い合わせください。
これらのオペレーターは、完全一致のキーワードを必要とせず、ニューラル埋め込みモデルを使用してクエリとの *意味的類似性* に基づいて投稿にマッチします。
| Operator | Type | Summary | Example |
| :------------------------- | :------------------- | :-------------------------------------------------------------- | :--------------------------------------------------------------- |
| `embedding:"query"` | Standalone | クエリと意味的に類似した投稿にマッチ。複数語のクエリは引用符で囲む必要があります。 | `embedding:"climate change policy"` |
| `embedding_threshold:X.XX` | Conjunction required | マッチに必要な最小コサイン類似度 (0.0–1.0)。デフォルトは `0.3`。0.3–0.6 の範囲の値を使用してください。 | `embedding:"cryptocurrency regulation" embedding_threshold:0.45` |
### 主な要件と注意点
* `embedding_threshold:` は、ルール内で **唯一のオペレーター** にはできません。`embedding:` (または他のスタンドアロンオペレーター) と組み合わせてください。
* `embedding:` を **否定しないでください** (例: `-embedding:"..."` はサポートされていません)。
* 短いキーワードよりも、長く説明的な自然言語のクエリの方が良い結果を生み出します。
* 埋め込みクエリの処理は非同期です — 新しく作成されたルールがマッチを開始するまでに数秒かかる場合があります。
* 投稿が埋め込みルールでマッチした場合、配信されるペイロードの `matching_rules` エントリには `embedding_similarity` と `embedding_threshold` が含まれます ([投稿とルールのマッチング](/x-api/posts/filtered-stream/integrate/matching-returned-tweets) を参照)。
**ルールの例:**
* `embedding:"electric vehicle announcements" lang:en -is:retweet has:links`
* `embedding:"natural disaster relief" embedding_threshold:0.45 has:media`
* `embedding:"renewable energy" embedding_threshold:0.4 OR embedding:"solar power investment"`
***
## 対応言語
`lang:` オペレーターは以下の BCP 47 言語コードに対応しています:
| Language | Code | Language | Code | Language | Code |
| :------- | :--- | :------- | :--- | :------- | :------ |
| アムハラ語 | `am` | ギリシャ語 | `el` | ポルトガル語 | `pt` |
| アラビア語 | `ar` | グジャラート語 | `gu` | ルーマニア語 | `ro` |
| アルメニア語 | `hy` | ヘブライ語 | `iw` | ロシア語 | `ru` |
| バスク語 | `eu` | ヒンディー語 | `hi` | セルビア語 | `sr` |
| ベンガル語 | `bn` | ハンガリー語 | `hu` | 簡体字中国語 | `zh-CN` |
| ブルガリア語 | `bg` | インドネシア語 | `in` | スロバキア語 | `sk` |
| カタルーニャ語 | `ca` | イタリア語 | `it` | スロベニア語 | `sl` |
| クロアチア語 | `hr` | 日本語 | `ja` | スペイン語 | `es` |
| チェコ語 | `cs` | カンナダ語 | `kn` | スウェーデン語 | `sv` |
| デンマーク語 | `da` | 韓国語 | `ko` | タミル語 | `ta` |
| オランダ語 | `nl` | ラトビア語 | `lv` | テルグ語 | `te` |
| 英語 | `en` | リトアニア語 | `lt` | タイ語 | `th` |
| エストニア語 | `et` | マラヤーラム語 | `ml` | 繁体字中国語 | `zh-TW` |
| フィンランド語 | `fi` | マラーティー語 | `mr` | トルコ語 | `tr` |
| フランス語 | `fr` | ノルウェー語 | `no` | ウクライナ語 | `uk` |
| ドイツ語 | `de` | ペルシャ語 | `fa` | ウルドゥー語 | `ur` |
| グルジア語 | `ka` | ポーランド語 | `pl` | ベトナム語 | `vi` |
***
## 次のステップ
ルールの構文とベストプラクティスを学ぶ
Filtered Stream を使い始める
ストリーミングの切断に対処する
# 暗号化入門
Source: https://docs.x.com/ja/xchat/cryptography-primer
X Chat のエンドツーエンド暗号化を支える ECDH、公開鍵暗号、デジタル署名の概念を、実装の詳細に立ち入らずに学びます。
このプライマーは、X Chat の背後にある暗号化のアイデアを概念レベルで説明します。構築するためにこの深さが必要というわけではありません — [Chat XDK](/xchat/xchat-xdk) が暗号化、復号、署名、鍵の保存を代行してくれます — が、このメンタルモデルはアプリを設計したり動作をデバッグしたりする際に役立ちます。
実装の準備ができたら、完全なウォークスルーとして [Getting Started](/xchat/getting-started) を、個別のルートについてはサイドバーの [API リファレンス](/x-api/chat/get-chat-conversations) を使用してください。
**この暗号化を自分で実装する必要はありません。** Chat XDK が処理します。このページは理解のためのものであり、API チェックリストではありません。
***
## 全体像
X Chat は次のような階層化された暗号化システムを使用します:
1. **メッセージ**は**会話鍵**で暗号化されます(高速な対称暗号化)
2. **会話鍵**は各参加者の **identity 公開鍵**を使って暗号化されます(非対称鍵交換)
3. **メッセージは**、**署名鍵**で**署名される**ので、受信者は誰が送信したのか、そして何も変更されていないことを検証できます
対称暗号化は大量のメッセージトラフィックに対して効率的です。非対称暗号化は、主に会話鍵を安全に**配布**するために使用されます。
```mermaid theme={null}
flowchart TB
subgraph "Message Encryption"
A[Your Message] --> B[Encrypt with Conversation Key]
B --> C[Encrypted Message]
end
subgraph "Key Distribution"
D[Conversation Key] --> E[Encrypt with Recipient's Public Key]
E --> F[Encrypted Key for Recipient]
end
subgraph "Authentication"
C --> G[Sign with Your Private Key]
G --> H[Signature]
end
```
製品フローにおいて、X は**暗号文と鍵エンベロープ**を転送します — 読み取り可能なメッセージ内容や生の会話鍵ではありません。あなたのアプリは暗号処理に Chat XDK を使い、鍵の登録や暗号化されたペイロードの送受信には [Chat API](/xchat/introduction)(Python/TypeScript の XDK 経由、または HTTPS)を使用します。これらのピースがどのように組み合わさるかは [Getting Started](/xchat/getting-started) を参照してください。
***
## 鍵の種類の説明
X Chat は 3 種類の鍵素材を使用しており、それぞれ特定の目的があります。
### 1. Identity キーペア
**目的:** ユーザー間で会話鍵を安全に交換すること
| 構成要素 | 説明 |
| :--------------- | :------------------------------- |
| **Identity 公開鍵** | 他のユーザーと共有;会話鍵を*あなた宛て*に暗号化するために使用 |
| **Identity 秘密鍵** | 秘密に保つ;*あなた宛て*に送られた会話鍵を復号するために使用 |
誰かが会話にあなたを追加するとき、彼らはあなたの identity 公開鍵を使って会話鍵を暗号化します。あなたの identity 秘密鍵だけがそれを復号できます。
公開鍵の半分はプラットフォームの**公開鍵**API を通じて登録および検出されます(API リファレンスの Encryption keys を参照)。秘密鍵の半分は Chat XDK 内に留まります(たとえば [安全な鍵バックアップ](#安全な鍵バックアップ-分散鍵ストレージ) や慎重に保護された鍵 blob 経由)。
### 2. 署名キーペア
**目的:** メッセージを作成したのがあなたであることを証明すること
| 構成要素 | 説明 |
| :-------- | :------------------------- |
| **署名公開鍵** | 他のユーザーと共有;あなたの署名を検証するために使用 |
| **署名秘密鍵** | 秘密に保つ;あなたのメッセージに署名するために使用 |
メッセージを送信するとき、あなたの署名秘密鍵で署名されます。受信者はあなたの署名公開鍵(同じく公開鍵 API を通じて公開されます)を使って検証します。Chat XDK はメッセージの暗号化の一部として署名を行い、送信者の公開鍵素材を渡した場合は復号時に検証することもできます。
### 3. 会話鍵
**目的:** 特定の会話内でメッセージ(およびメディア)を暗号化・復号すること
| プロパティ | 説明 |
| :---------- | :----------------------------------- |
| **対称** | 同じ鍵で暗号化と復号を行う |
| **会話ごと** | 各会話に独自の鍵がある |
| **参加者間で共有** | 会話を読むべき参加者全員がコピーを保持 |
| **バージョン付き** | 鍵はローテーション可能;アプリはバージョンを時間の経過とともに追跡すべき |
会話鍵は会話がセットアップされたときや、鍵がローテーションされたときに生成されます。各参加者は identity 公開鍵で暗号化された、鍵の**暗号化コピー**を受け取ります。自分のコピーを一度復号したら、**未加工の**会話鍵を保持し、高速なメッセージ(および[メディア](/xchat/media))暗号化に使用します。会話のためにこれらのコピーをセットアップすることは、Chat XDK と会話**鍵**エンドポイントを組み合わせて行われます — [Getting Started](/xchat/getting-started#4-set-up-conversation-keys) で解説されています。
***
## 暗号化の仕組み(概念的に)
### メッセージの送信
あなたが入力: "Hello, how are you?"
アプリは、正しい鍵バージョンについて、このチャットの未加工の会話鍵(セットアップまたは以前の鍵配布イベントから)を使用します。
Chat XDK は会話鍵でメッセージを暗号化します。結果はその鍵がなければ役に立たない暗号文です。
Chat XDK は暗号化されたペイロードにあなたの署名秘密鍵で署名し、あなたがまさにこの内容を作成したことを証明します。
アプリは、Chat API の**メッセージ送信**エンドポイントを介して暗号化されたペイロードと署名を X に送信します。X は平文として読み取れないバイトを保存し配信します。
### メッセージの受信
アプリは X から暗号文を受信します — [Webhook またはアクティビティストリーム](/xchat/real-time-events)経由、または履歴のために会話**イベント**を読み取ることで。
キャッシュされた未加工の鍵を使うか、これが新規または鍵ローテーション後の場合は鍵配布(鍵変更)イベントからあなたのコピーを復号して取得します。
Chat XDK は送信者の署名公開鍵(および関連する identity バインディング)を使って署名をチェックするので、誰が送ったか、そして変更されていないことを知ることができます。
Chat XDK は会話鍵で復号します。これで "Hello, how are you?" を読むことができます。
暗号化、送信、受信、復号の実装は [Getting Started](/xchat/getting-started) と [Chat XDK](/xchat/xchat-xdk) リファレンスにあります。
***
## 鍵配布の説明
エンドツーエンド暗号化における中心的な課題は**鍵配布**です: X(または観察者)が鍵を平文で見ることなく、参加者が会話鍵をどうやって受け取るか。
### 初期鍵セットアップ
会話がメッセージング用に準備される際:
1. ランダムな会話鍵が生成されます(Chat XDK 内)
2. **各参加者**について、その鍵は彼らの **identity 公開鍵**で暗号化されます
3. それらの暗号化コピーは X の Chat API 経由で保存および配信されます
4. 各参加者は**自分の**コピーを identity 秘密鍵で復号します(Chat XDK 内)
X が扱うのは**ラップされた**コピーだけで、生の会話鍵ではありません。
### 鍵変更イベント
会話鍵がローテーションされる(たとえばメンバーシップが変更された)とき、参加者は各メンバー用の新しい暗号化コピーを含む**鍵変更**イベントを受け取ります。
あなたのアプリは次のようにすべきです:
1. ライブイベントや会話履歴で鍵変更素材に気づく
2. 新しい会話鍵(およびバージョン)を復号して保存する
3. 以降の送信には最新バージョンを使用する
これらのイベントが実際にどこに現れるかは [Getting Started](/xchat/getting-started#6-receive-and-decrypt) と [リアルタイムイベント](/xchat/real-time-events) が説明しています。
***
## 安全な鍵バックアップ: 分散鍵ストレージ
あなたの **identity と署名の秘密鍵**は慎重に保存されなければなりません。X Chat には**安全な鍵バックアップ**システム(Juicebox で実装)が含まれており、単一のサーバーに完全な秘密を渡すことなく、パスコードを使ってデバイス間で鍵を復元できます。
### 従来の鍵ストレージの問題点
| アプローチ | 問題 |
| :--------------- | :-------------------------------- |
| デバイスにのみ保存 | デバイスを紛失 = 鍵を失う = メッセージ履歴へのアクセスを失う |
| 通常のクラウドバックアップに保存 | プロバイダーが鍵素材にアクセスする可能性がある |
| 長い鍵を覚える | 人間は高エントロピーの鍵を確実に暗記できない |
### 安全な鍵バックアップがどう解決するか
安全な鍵バックアップは**秘密分散**と**パスコード保護**を組み合わせます:
1. 秘密鍵は**シェアに分割**されます
2. シェアは**独立した realm**(別々のサーバー)が保持します
3. **単一の realm** だけでは鍵を再構築するのに十分な情報がありません
4. 復元には**パスコード**と**十分な数の realm** の協力が必要です
5. 間違ったパスコードは**レート制限**されて推測を遅らせます
```mermaid theme={null}
flowchart LR
A[Your Private Keys] --> B[Split into Shares]
B --> C[Realm 1 Share A]
B --> D[Realm 2 Share B]
B --> E[Realm 3 Share C]
subgraph Recovery
F[Your Passcode + Multiple Realms] --> G[Reconstruct Keys]
end
```
単一の当事者が秘密全体を保持することなく、復元可能性(新しいデバイス + パスコード)を得ることができます。
通常のパスでは鍵バックアップサーバーを手動で設定する必要はありません。Chat XDK にはバックアップクライアントが含まれており、realm 設定は X API から公開鍵レコード上の **`juicebox_config`** として提供されます(このフィールド名は、基盤となる実装である Juicebox に由来します)。初回のパスコード保存と後のアンロックは Chat XDK 呼び出しです — Getting Started の [既存の鍵で初期化する](/xchat/getting-started#2-initialize-the-chat-xdk-with-existing-keys) および [鍵を作成して登録する](/xchat/getting-started#3-create-and-register-keys-first-time-setup) を参照してください。一部のアプリ(特にサーバーとボット)は安全な鍵バックアップの代わりにエクスポートされた鍵 blob を使用します;その素材はパスワードのように保護してください。
***
## 署名の説明
すべての X Chat メッセージには、以下をサポートする**デジタル署名**が含まれます:
1. **真正性** — 送信者の署名秘密鍵で生成されたこと
2. **完全性** — 暗号化されたコンテンツが署名後に変更されていないこと
### 署名の仕組み(概念的に)
| アクション | 使用する鍵 | 結果 |
| :----- | :-------- | :---------------------- |
| **署名** | 送信者の署名秘密鍵 | この暗号化メッセージに正確にバインドされた署名 |
| **検証** | 送信者の署名公開鍵 | 署名がメッセージと鍵に一致することを確認 |
署名対象の何かが変更されると、検証は失敗します。その鍵の有効な署名を生成できるのは、署名秘密鍵を持つ人だけです。
### アプリでの利用
Chat XDK は送信メッセージを暗号化するときに署名し、受信メッセージを復号するときに(公開鍵 API からの)送信者の公開鍵素材に対して検証します。検証は**デフォルトで必須**です: SDK は明示的にチェックを無効にしない限り、検証されていない署名付きイベントを拒否します(推奨されません)。詳細は [Chat XDK](/xchat/xchat-xdk) リファレンスにあります。
### 署名付き状態変更(アクション署名)
メッセージだけが署名対象ではありません。会話の状態を変更するすべての呼び出し — 会話鍵の追加やローテーション、グループの作成、メンバーの追加 — は、1 つ以上の**アクション署名**を伴う必要があります: 送信者は変更が正確に何をするかを記述したペイロードに署名し(鍵変更の場合、そのペイロードには新しい会話鍵自体が含まれます)、署名が欠落または不正な形式の場合、API はリクエストを拒否します。
サーバーは平文の会話鍵を保持しないため、鍵変更の署名を暗号学的にチェックできません。受信したリクエストと、署名され、エンコードされた変更の説明が一致することを検証します。**暗号学的な**チェックはエッジで行われます: 各受信者の Chat XDK は、鍵変更イベントを復号する際に、送信者の署名公開鍵に対して署名を検証します。Chat XDK の `prepare` メソッドはこれらの署名を生成してくれます — グループの作成とメンバー追加は**2 つ**(鍵変更とグループアクション)を返し、両方を送信する必要があります。
署名はイベントの内容にバインドされ、不変です: 署名が検証できないイベントは、将来的に有効になることはありません。それらの扱い方については [トラブルシューティング](/xchat/troubleshooting) を参照してください。
***
## セキュリティプロパティ
### X Chat が保護する対象
| 脅威 | 保護 |
| :--------------------------- | :-------------------------------- |
| **X がメッセージ本文を読む** | コンテンツは X に送信される前に暗号化される |
| **ネットワーク盗聴者** | 転送セキュリティに加えてエンドツーエンド暗号化されたコンテンツ |
| **メッセージの改ざん** | 署名が変更を検出する |
| **単純な送信者なりすまし** | 有効な署名には送信者の署名秘密鍵が必要 |
| **単一サーバー鍵盗難(安全な鍵バックアップ使用時)** | シェアは realm 間で分散され、パスコードによってゲートされる |
### X Chat が**保護しない**対象
| 脅威 | なぜか |
| :------------ | :------------------------------------------ |
| **侵害されたデバイス** | 平文と鍵がアンロックされたクライアントで露出する可能性がある |
| **メタデータ** | X は誰がいつ誰にメッセージを送ったかを知ることができる — メッセージ本文は知らない |
| **前方秘匿性** | identity 鍵の侵害により、それらの鍵にラップされた会話鍵が露出する可能性がある |
| **侵害後セキュリティ** | 鍵をローテーションしても履歴は書き換えられない |
***
## 用語集
| 用語 | 定義 |
| :--------------- | :------------------------------------- |
| **対称暗号化** | 同じ鍵で暗号化と復号を行う(メッセージとメディアストリームで使用) |
| **非対称暗号化** | 暗号化と復号で異なる鍵(会話鍵をラップするために使用) |
| **公開鍵** | 共有しても安全;誰かに*向けて*暗号化するか、彼らの署名を検証するために使用 |
| **秘密鍵** | 秘密のままにしなければならない;復号または署名に使用 |
| **キーペア** | リンクされた公開鍵と秘密鍵 |
| **ECDH / ECIES** | 会話鍵を identity 鍵にラップするときに使用するアルゴリズム |
| **ECDSA** | メッセージ作成者に使用される署名アルゴリズム |
| **P-256** | X Chat で使用される楕円曲線(secp256r1) |
| **会話鍵** | 1 つの会話の参加者間で共有される対称鍵(時間経過でバージョン化される) |
| **秘密分散** | 秘密を分割して、再構築するために複数のピースが必要になるようにすること |
| **Realm** | 鍵素材の 1 シェアを保持する独立した安全な鍵バックアップサーバー |
***
## 次のステップ
鍵、送信、受信をステップバイステップで実装
暗号化 SDK のメソッドと型
製品概要とアーキテクチャ
暗号化イベントがどのように配信されるか
# Chat API を始める
Source: https://docs.x.com/ja/xchat/getting-started
Python、TypeScript、Go、Rust、C#、Java の Chat XDK を使って、エンドツーエンド暗号化された X Chat メッセージングを構築するチュートリアル。
X 上でエンドツーエンド暗号化されたダイレクトメッセージを送受信します: 鍵をセットアップし、会話を初期化し、メッセージを送信し、受信トラフィックを復号します。
X Chat アプリは、2 つの要素を組み合わせて使用します:
| コンポーネント | 役割 |
| :------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **[Chat XDK](/xchat/xchat-xdk)** | 暗号化、復号、署名、および秘密鍵の保存(安全な鍵バックアップまたは鍵 blob) |
| **X API** | 公開鍵、会話鍵、メッセージ、イベント — [Python](/xdks/python/overview) または [TypeScript](/xdks/typescript/overview) XDK 経由、または HTTPS とユーザーアクセストークン経由 |
**前提条件**
* [開発者アカウント](https://developer.x.com/en/portal/petition/essential/basic-info) と OAuth 2.0 用に構成されたアプリ
* `dm.read`、`dm.write`、`tweet.read`、`users.read` を持つユーザーアクセストークン
***
## 1. 依存関係をインストールする
```bash theme={null}
pip install chatxdk xdk
```
PyPI パッケージは `chatxdk` です。`chat_xdk` としてインポートします。Python 3.10+ が必要です。
```bash theme={null}
npm install @xdevplatform/chat-xdk @xdevplatform/xdk
npm install juicebox-sdk # optional peer dependency — required for setup()/unlock() secure key backup
```
コンパイル済みの WASM エンジンは `@xdevplatform/chat-xdk` に同梱されています。ビルド手順は不要です。Node.js 18+ が必要です。
```toml theme={null}
[dependencies]
# chat-xdk-core is not yet on crates.io — use the git dependency
chat-xdk-core = { git = "https://github.com/xdevplatform/chat-xdk", tag = "v0.2.1" }
reqwest = { version = "0.12", features = ["blocking", "json"] }
serde_json = "1"
base64 = "0.22"
uuid = { version = "1", features = ["v4"] }
# Required until thrift 0.24 is released on crates.io
[patch.crates-io]
thrift = { git = "https://github.com/apache/thrift.git", rev = "deb36fa409849de45973b04ffc3ce49d277ca90a" }
```
```bash theme={null}
go get github.com/xdevplatform/chat-xdk/go/chatxdk
```
プリコンパイル済みの静的ライブラリが含まれています(macOS arm64/amd64、Linux amd64 glibc/musl)。C コンパイラは必要ですが、Rust は不要です。Go 1.21+ が必要です。
```bash theme={null}
dotnet add package XDevPlatform.ChatXdk
```
パッケージは自己完結型です。macOS(arm64、x64)、Linux(x64)、Windows(x64)用のネイティブライブラリが同梱されています。.NET 8+ が必要です。
```xml theme={null}
com.xchatxdk0.2.1
```
Maven Central で入手できます。jar には macOS(arm64、x64)、Linux(x64)、Windows(x64)用のネイティブライブラリが同梱されており、`jna.library.path` の設定は不要です。`com.x.chatxdk` からインポートします。JDK 17+ が必要です。
**ユーザー** OAuth 2.0 アクセストークンで API クライアントを作成します:
```python theme={null}
from xdk import Client
client = Client(access_token="YOUR_OAUTH2_USER_TOKEN")
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ accessToken: 'YOUR_OAUTH2_USER_TOKEN' });
```
```rust theme={null}
let access_token = std::env::var("X_ACCESS_TOKEN")?;
let http = reqwest::blocking::Client::new();
let auth = format!("Bearer {access_token}");
```
```go theme={null}
accessToken := os.Getenv("X_ACCESS_TOKEN")
httpClient := &http.Client{Timeout: 30 * time.Second}
```
```csharp theme={null}
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", Environment.GetEnvironmentVariable("X_ACCESS_TOKEN"));
```
```java theme={null}
String accessToken = System.getenv("X_ACCESS_TOKEN");
HttpClient http = HttpClient.newHttpClient();
```
***
## 2. 既存の鍵で Chat XDK を初期化する
このステップでは、**すでに持っている鍵をロード**します — この identity が過去に初回セットアップを完了している場合に使用してください:
* **安全な鍵バックアップ:** 公開鍵レコードの `juicebox_config` で SDK を構築し、パスコードで `unlock` して秘密鍵を復元します(たとえば新しいデバイスで)。
* **鍵 blob:** 以前に `export_keys` でエクスポートした blob を `import_keys` に渡します。
次に、登録済みの公開鍵バージョン(レコード上の `public_key_version`)を設定します。
**初めてセットアップする場合は?** 同じ方法で SDK を構築しますが、`unlock` / `import_keys` はスキップし、[ステップ 3](#3-鍵を作成して登録する初回セットアップ) に進んで鍵の作成、バックアップ、登録を行ってください。
```python theme={null}
import json
from chat_xdk import Chat
resp = client.chat.get_user_public_keys(
"YOUR_USER_ID",
public_key_fields=[
"public_key_version", "public_key", "signing_public_key",
"identity_public_key_signature", "juicebox_config",
],
)
record = resp.data[0]
signing_key_version = str(record["public_key_version"])
chat = Chat(json.dumps(record["juicebox_config"]))
chat.unlock("YOUR_PASSCODE") # recovers keys stored by setup() during first-time setup (step 3)
chat.set_key_version(signing_key_version)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const resp = await client.chat.getUserPublicKeys('YOUR_USER_ID', {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key',
'identity_public_key_signature', 'juicebox_config',
],
});
const record = resp.data[0];
const signingKeyVersion = String(record.public_key_version);
const chat = await createChat({
juiceboxConfig: JSON.stringify(record.juicebox_config),
getAuthToken: async (realmId) => getRealmTokenFromYourBackend(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(signingKeyVersion);
```
```rust theme={null}
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use chat_xdk_core::ChatCore;
let mut chat = ChatCore::new();
let blob = B64.decode(std::env::var("PRIVATE_KEYS_B64")?)?;
let signing_key_version = std::env::var("SIGNING_KEY_VERSION").unwrap_or_else(|_| "1".into());
chat.import_keys(&blob)?;
chat.set_key_version(&signing_key_version);
```
```go theme={null}
import "github.com/xdevplatform/chat-xdk/go/chatxdk"
chat := chatxdk.New()
defer chat.Close()
blob, err := chatxdk.Base64ToBytes(os.Getenv("PRIVATE_KEYS_B64"))
if err != nil {
log.Fatal(err)
}
if err := chat.ImportKeys(blob); err != nil {
log.Fatal(err)
}
signingKeyVersion := os.Getenv("SIGNING_KEY_VERSION")
if signingKeyVersion == "" {
signingKeyVersion = "1"
}
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
using ChatXdk;
using var chat = new Chat();
var signingKeyVersion = Environment.GetEnvironmentVariable("SIGNING_KEY_VERSION") ?? "1";
chat.ImportKeys(Convert.FromBase64String(
Environment.GetEnvironmentVariable("PRIVATE_KEYS_B64")!));
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
import com.x.chatxdk.Chat;
String signingKeyVersion = Optional.ofNullable(System.getenv("SIGNING_KEY_VERSION")).orElse("1");
try (Chat chat = new Chat()) {
chat.importKeys(Base64.getDecoder().decode(System.getenv("PRIVATE_KEYS_B64")));
chat.setKeyVersion(signingKeyVersion);
}
```
サーバーおよびボットのサンプルでは、通常**鍵 blob**(`export_keys` / `import_keys`)を使用します。クライアントアプリでは通常**安全な鍵バックアップ**(パスコードを使った `setup` / `unlock`)を使用します。両方のパスについては [Chat XDK](/xchat/xchat-xdk) リファレンスを参照してください。
**独自の鍵を持ち込みますか?** `import_keys` は、Chat XDK の `export_keys` が生成する不透明な blob のみを受け付けます — これは鍵の完全な状態をバージョン付きで非公開にシリアライズしたものであり、未加工または PEM エンコードされた P-256 鍵ではありません。この blob を自分で構築することはできません: `generate_keypairs`([ステップ 3](#3-鍵を作成して登録する初回セットアップ))で鍵を生成し、blob を一度エクスポートして、base64 エンコードで保存してください。手作りまたは改変された blob はインポートに失敗します。
***
## 3. 鍵を作成して登録する(初回セットアップ)
[ステップ 2](#2-既存の鍵で-chat-xdk-を初期化する) で既存の鍵をロードした場合は、このステップをスキップしてください。それ以外の場合、新しい identity の 1 回限りのセットアップでは **3 つのこと**を行います:
1. **キーペアを作成する** — `generate_keypairs` が identity と署名のキーペアを生成します。
2. **公開鍵を登録する** — 他のユーザーがあなた宛てに暗号化し、あなたの署名を検証できるよう、登録ペイロードを add-public-key エンドポイントに POST します。
3. **秘密鍵を保存する** — パスコードで `setup` すると安全な鍵バックアップに書き込まれます(クライアント)。または `export_keys` が返す鍵 blob を安全に保存します(サーバーとボット)。
```python theme={null}
from xdk.chat.models import AddUserPublicKeyRequest
registration = chat.generate_keypairs()
pk = registration.public_key
client.chat.add_user_public_key(
"YOUR_USER_ID",
AddUserPublicKeyRequest(
public_key={
"identity_public_key_signature": pk.identity_public_key_signature,
"public_key": pk.public_key,
"public_key_fingerprint": pk.public_key_fingerprint,
"registration_method": pk.registration_method,
"signing_public_key": pk.signing_public_key,
"signing_public_key_signature": pk.signing_public_key_signature,
},
version=registration.version,
generate_version=registration.generate_version,
),
)
chat.setup("YOUR_PASSCODE")
chat.set_key_version(str(registration.version or signing_key_version))
```
```typescript theme={null}
const registration = chat.generateKeypairs();
const pk = registration.publicKey;
await client.chat.addUserPublicKey('YOUR_USER_ID', {
public_key: {
identity_public_key_signature: pk.identityPublicKeySignature,
public_key: pk.publicKey,
public_key_fingerprint: pk.publicKeyFingerprint,
registration_method: pk.registrationMethod,
signing_public_key: pk.signingPublicKey,
signing_public_key_signature: pk.signingPublicKeySignature,
},
version: registration.version,
generate_version: registration.generateVersion,
});
await chat.setup('YOUR_PASSCODE');
chat.setKeyVersion(String(registration.version ?? signingKeyVersion));
```
```rust theme={null}
let registration = chat.generate_keypairs()?;
let body = serde_json::to_value(®istration)?;
let resp = http
.post(format!("https://api.x.com/2/users/{user_id}/public_keys"))
.header("Authorization", &auth)
.json(&body)
.send()?;
if !resp.status().is_success() {
anyhow::bail!("register keys: {}", resp.text()?);
}
let _blob = chat.export_keys()?; // store securely
```
```go theme={null}
registration, err := chat.GenerateKeypairs()
if err != nil {
log.Fatal(err)
}
regJSON, _ := json.Marshal(registration)
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/users/"+userID+"/public_keys",
bytes.NewReader(regJSON))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
privateKeysB64, _ := chat.ExportKeys() // store securely
_ = privateKeysB64
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
var registration = chat.GenerateKeypairs();
var regJson = System.Text.Json.JsonSerializer.Serialize(registration);
using var content = new StringContent(regJson, Encoding.UTF8, "application/json");
using var regResp = await http.PostAsync(
$"https://api.x.com/2/users/{Uri.EscapeDataString(userId)}/public_keys", content);
regResp.EnsureSuccessStatusCode();
var blob = chat.ExportKeys(); // store securely
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
var registration = chat.generateKeypairs();
String regJson = new ObjectMapper().writeValueAsString(registration);
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/users/" + userId + "/public_keys"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(regJson))
.build();
HttpResponse regResp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (regResp.statusCode() >= 300) {
throw new RuntimeException("register keys: " + regResp.body());
}
byte[] blob = chat.exportKeys(); // store securely
chat.setKeyVersion(signingKeyVersion);
```
安全な鍵バックアップには強力なパスコードを使用してください。パスコードを紛失したり、保護されていない鍵 blob を失うと、過去のメッセージの復号ができなくなる可能性があります。
***
## 4. 会話鍵をセットアップする
**`prepare_conversation_key_change`** を、あなたのユーザー ID、署名鍵のバージョン、およびすべての参加者の identity 公開鍵とともに呼び出します。1 回の呼び出しで新しい会話鍵を生成し、各参加者向けに暗号化し、変更に署名します。結果を **add conversation keys** エンドポイント(`POST /2/chat/conversations/{id}/keys`)に POST します — ボディには `conversation_key_version`、`conversation_participant_keys`(SDK の `encrypted_key` → API の `encrypted_conversation_key`)、および **`action_signatures`** が必要です(必須;API は署名がないと呼び出しを拒否します)。送信用に**未加工の**会話鍵を保持します。
レスポンスは、正規の会話 ID(`data.conversation_id` — 1:1 の場合はハイフンで結合されたペア、グループの場合は g プレフィックス付き ID)と、鍵変更の `data.sequence_id` を返します。以降のリクエストでは、クライアント側で再構築するのではなく、返された ID を使用してください。同じ呼び出しは後で鍵を**ローテーション**するためにも使えます: 既存の会話 ID を `prepare_conversation_key_change` に渡し、新しい鍵バージョンで POST します。会話鍵が漏洩したと疑われる場合はローテーションしてください — ローテーションは**将来の**メッセージのみを保護します;以前の鍵バージョンで暗号化されたメッセージは、そのバージョンを保持している人にとっては引き続き読み取り可能です。
**ラップする前に取得した鍵を検証してください。** `prepare_conversation_key_change` は、渡された任意の公開鍵に対して新しい会話鍵を暗号化します。各取得済みレコードに対してまず `verify_key_binding(identity, signing, signature)` でチェックし(public-keys API のレコードの `public_key`、`signing_public_key`、`identity_public_key_signature` フィールドを渡します)、置き換えられた identity 鍵が会話鍵を受け取れないようにしてください。
```python theme={null}
def public_key_input(user_id: str) -> dict:
r = client.chat.get_user_public_keys(
user_id, public_key_fields=["public_key_version", "public_key"]
).data[0]
return {"user_id": user_id, "public_key": r["public_key"], "key_version": r["public_key_version"]}
prepared = chat.prepare_conversation_key_change(
"YOUR_USER_ID",
signing_key_version,
[public_key_input("YOUR_USER_ID"), public_key_input("RECIPIENT_USER_ID")],
# conversation_id=None for a new 1:1; pass the id to rotate later
)
resp = client.chat.add_conversation_keys(
"RECIPIENT_USER_ID",
{
"conversation_key_version": prepared["conversation_key_version"],
"conversation_participant_keys": [
{
"user_id": pk["user_id"],
"encrypted_conversation_key": pk["encrypted_key"],
"public_key_version": pk["public_key_version"],
}
for pk in prepared["participant_keys"]
],
"action_signatures": [
{
"message_id": sig["message_id"],
"encoded_message_event_detail": sig["encoded_message_event_detail"],
"message_event_signature": {
"signature": sig["signature"],
"public_key_version": sig["public_key_version"],
"signature_version": sig["signature_version"],
},
}
for sig in prepared["action_signatures"]
],
},
)
conversation_id = resp.data["conversation_id"] # canonical id for later requests
sequence_id = resp.data["sequence_id"]
conv_key = prepared["conversation_key"]
conv_key_version = prepared["conversation_key_version"]
```
```typescript theme={null}
async function publicKeyInput(userId: string) {
const r = (await client.chat.getUserPublicKeys(userId, {
publicKeyFields: ['public_key_version', 'public_key'],
})).data[0];
return { userId, publicKey: r.public_key, keyVersion: r.public_key_version };
}
// Omit conversationId for a new 1:1; pass the id to rotate later
const prepared = chat.prepareConversationKeyChange({
senderId: 'YOUR_USER_ID',
signingKeyVersion,
publicKeys: [
await publicKeyInput('YOUR_USER_ID'),
await publicKeyInput('RECIPIENT_USER_ID'),
],
});
const resp = await client.chat.addConversationKeys('RECIPIENT_USER_ID', {
conversation_key_version: prepared.conversationKeyVersion,
conversation_participant_keys: prepared.participantKeys.map((pk) => ({
user_id: pk.userId,
encrypted_conversation_key: pk.encryptedKey,
public_key_version: pk.publicKeyVersion,
})),
action_signatures: prepared.actionSignatures.map((sig) => ({
message_id: sig.messageId,
encoded_message_event_detail: sig.encodedMessageEventDetail,
message_event_signature: {
signature: sig.signature,
public_key_version: sig.publicKeyVersion,
signature_version: sig.signatureVersion,
},
})),
});
const conversationId = resp.data.conversation_id; // canonical id for later requests
const sequenceId = resp.data.sequence_id;
const convKey = prepared.conversationKey;
const convKeyVersion = prepared.conversationKeyVersion;
```
```rust theme={null}
// public_key_inputs: Vec from GET public keys
// (user_id, public_key, key_version ← public_key_version)
// new 1:1; set params.conversation_id = Some(id) to rotate later
let prepared = chat.prepare_conversation_key_change(
ConversationKeyChangeParams::new(&sender_id, &signing_key_version, public_key_inputs),
)?;
let participant_keys: Vec<_> = prepared
.participant_keys
.iter()
.map(|pk| {
serde_json::json!({
"user_id": pk.user_id,
"encrypted_conversation_key": pk.encrypted_key,
"public_key_version": pk.public_key_version,
})
})
.collect();
let action_signatures: Vec<_> = prepared
.action_signatures
.iter()
.map(|sig| {
serde_json::json!({
"message_id": sig.message_id,
"encoded_message_event_detail": sig.encoded_message_event_detail,
"message_event_signature": {
"signature": sig.signature,
"public_key_version": sig.public_key_version,
"signature_version": sig.signature_version,
},
})
})
.collect();
let body = serde_json::json!({
"conversation_key_version": prepared.conversation_key_version,
"conversation_participant_keys": participant_keys,
"action_signatures": action_signatures,
});
let resp: serde_json::Value = http
.post(format!("https://api.x.com/2/chat/conversations/{recipient_id}/keys"))
.header("Authorization", &auth)
.json(&body)
.send()?
.json()?;
// Canonical id for later requests
let conversation_id = resp["data"]["conversation_id"].as_str().unwrap().to_string();
// conversation_key is Option; encrypt_message wants owned bytes
let conv_key = prepared.conversation_key.expect("key present").to_bytes();
let conv_key_version = prepared.conversation_key_version;
```
```go theme={null}
// KeyVersion comes from the public_key_version field on each record
prepared, err := chat.PrepareConversationKeyChange(chatxdk.ConversationKeyChangeParams{
SenderID: myUserID,
SigningKeyVersion: signingKeyVersion,
PublicKeys: []chatxdk.PublicKeyInput{
{UserID: myUserID, PublicKey: myIdentityPubB64, KeyVersion: myKeyVersion},
{UserID: recipientID, PublicKey: theirIdentityPubB64, KeyVersion: theirKeyVersion},
},
// ConversationID empty for a new 1:1; pass the id to rotate later
})
var parts []map[string]string
for _, pk := range prepared.ParticipantKeys {
parts = append(parts, map[string]string{
"user_id": pk.UserID,
"encrypted_conversation_key": pk.EncryptedKey,
"public_key_version": pk.PublicKeyVersion,
})
}
var sigs []map[string]any
for _, sig := range prepared.ActionSignatures {
sigs = append(sigs, map[string]any{
"message_id": sig.MessageID,
"encoded_message_event_detail": sig.EncodedMessageEventDetail,
"message_event_signature": map[string]string{
"signature": sig.Signature,
"public_key_version": sig.PublicKeyVersion,
"signature_version": sig.SignatureVersion,
},
})
}
body, _ := json.Marshal(map[string]any{
"conversation_key_version": prepared.ConversationKeyVersion,
"conversation_participant_keys": parts,
"action_signatures": sigs,
})
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/chat/conversations/"+recipientID+"/keys",
bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
// Response data.conversation_id is the canonical id for later requests
// prepared.ConversationKey feeds EncryptMessage
_ = resp
```
```csharp theme={null}
// KeyVersion comes from the public_key_version field on each record
var prepared = chat.PrepareConversationKeyChange(new ConversationKeyChangeParams {
SenderId = myUserId,
SigningKeyVersion = signingKeyVersion,
PublicKeys = new[] {
new PublicKeyInput { UserId = myUserId, PublicKey = myPk, KeyVersion = myVer },
new PublicKeyInput { UserId = recipientId, PublicKey = theirPk, KeyVersion = theirVer },
},
}); // ConversationId null for a new 1:1; pass the id to rotate later
var keysBody = new {
conversation_key_version = prepared.ConversationKeyVersion,
conversation_participant_keys = prepared.ParticipantKeys.Select(pk => new {
user_id = pk.UserId,
encrypted_conversation_key = pk.EncryptedKey,
public_key_version = pk.PublicKeyVersion,
}),
action_signatures = prepared.ActionSignatures.Select(sig => new {
message_id = sig.MessageId,
encoded_message_event_detail = sig.EncodedMessageEventDetail,
message_event_signature = new {
signature = sig.Signature,
public_key_version = sig.PublicKeyVersion,
signature_version = sig.SignatureVersion,
},
}),
};
var json = System.Text.Json.JsonSerializer.Serialize(keysBody);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await http.PostAsync(
$"https://api.x.com/2/chat/conversations/{Uri.EscapeDataString(recipientId)}/keys",
content);
resp.EnsureSuccessStatusCode();
var data = System.Text.Json.JsonDocument.Parse(await resp.Content.ReadAsStringAsync())
.RootElement.GetProperty("data");
string conversationId = data.GetProperty("conversation_id").GetString()!; // canonical id
byte[] convKey = prepared.ConversationKey!;
string convKeyVersion = prepared.ConversationKeyVersion;
```
```java theme={null}
// keyVersion comes from the public_key_version field on each record
PublicKeyInput mine = new PublicKeyInput();
mine.userId = myUserId; mine.publicKey = myIdentityPubB64; mine.keyVersion = myKeyVersion;
PublicKeyInput theirs = new PublicKeyInput();
theirs.userId = recipientId; theirs.publicKey = theirIdentityPubB64; theirs.keyVersion = theirKeyVersion;
ConversationKeyChangeParams keyParams = new ConversationKeyChangeParams();
keyParams.senderId = myUserId;
keyParams.signingKeyVersion = signingKeyVersion;
keyParams.publicKeys = List.of(mine, theirs);
// keyParams.conversationId null for a new 1:1; set the id to rotate later
PreparedConversationChange prepared = chat.prepareConversationKeyChange(keyParams);
List> parts = new ArrayList<>();
for (var pk : prepared.participantKeys) {
parts.add(Map.of(
"user_id", pk.userId,
"encrypted_conversation_key", pk.encryptedKey,
"public_key_version", pk.publicKeyVersion));
}
List> sigs = new ArrayList<>();
for (var sig : prepared.actionSignatures) {
sigs.add(Map.of(
"message_id", sig.messageId,
"encoded_message_event_detail", sig.encodedMessageEventDetail,
"message_event_signature", Map.of(
"signature", sig.signature,
"public_key_version", sig.publicKeyVersion,
"signature_version", sig.signatureVersion)));
}
ObjectMapper mapper = new ObjectMapper();
String body = mapper.writeValueAsString(Map.of(
"conversation_key_version", prepared.conversationKeyVersion,
"conversation_participant_keys", parts,
"action_signatures", sigs));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/conversations/" + recipientId + "/keys"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString());
JsonNode data = mapper.readTree(resp.body()).path("data");
String conversationId = data.path("conversation_id").asText(); // canonical id
byte[] convKey = prepared.conversationKey;
String convKeyVersion = prepared.conversationKeyVersion;
```
***
## 5. メッセージを送信する
**未加工の**会話鍵バイトで暗号化します。送信リクエストでは、次のようにマップします:
| Chat XDK フィールド | リクエストボディフィールド |
| :---------------------------------------------------------------------------- | :-------------------------------- |
| `encrypted_content` / `encryptedContent` / `EncryptedContent` | `encoded_message_create_event` |
| `encoded_event_signature` / `encodedEventSignature` / `EncodedEventSignature` | `encoded_message_event_signature` |
| 生成した ID | `message_id` |
API で要求される場合、URL パスでは**ハイフン付きの**会話 ID を使用します(`:` → `-`)。SDK 自体は柔軟です: `encrypt_message` と `encrypt_reply` は、保持している任意の形式で ID を受け付けます — イベントからの `A:B`、リストや URL パスからの `A-B`(どちらの順序でも可)、あるいは受信者のユーザー ID だけでも構いません — そして署名する前に正規化します。グループ ID(`g` プレフィックス付き)はそのまま渡されます。
```python theme={null}
import uuid
from xdk.chat.models import SendMessageRequest
message_id = str(uuid.uuid4())
payload = chat.encrypt_message(
message_id,
"YOUR_USER_ID",
"CONVERSATION_ID",
conv_key,
"Hello!",
conv_key_version,
signing_key_version,
)
client.chat.send_message(
"RECIPIENT_USER_ID",
SendMessageRequest(
message_id=message_id,
encoded_message_create_event=payload.encrypted_content,
encoded_message_event_signature=payload.encoded_event_signature,
),
)
```
```typescript theme={null}
import { randomUUID } from 'crypto';
const messageId = randomUUID();
const payload = chat.encryptMessage({
messageId,
senderId: 'YOUR_USER_ID',
conversationId: 'CONVERSATION_ID',
conversationKey: convKey,
text: 'Hello!',
conversationKeyVersion: convKeyVersion,
signingKeyVersion,
});
await client.chat.sendMessage('RECIPIENT_USER_ID', {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
});
```
```rust theme={null}
use chat_xdk_core::EncryptMessageParams;
let message_id = uuid::Uuid::new_v4().to_string();
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id,
&sender_id,
&conversation_id,
conv_key,
"Hello!",
&conv_key_version,
&signing_key_version,
))?;
let body = serde_json::json!({
"message_id": message_id,
"encoded_message_create_event": payload.encrypted_content,
"encoded_message_event_signature": payload.encoded_event_signature,
});
let path_id = conversation_id.replace(':', "-");
http.post(format!("https://api.x.com/2/chat/conversations/{path_id}/messages"))
.header("Authorization", &auth)
.json(&body)
.send()?;
```
```go theme={null}
messageID := uuid.NewString()
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID,
SenderID: senderID,
ConversationID: conversationID,
ConversationKey: convKey,
Text: "Hello!",
ConversationKeyVersion: convKeyVersion,
SigningKeyVersion: signingKeyVersion,
})
body, _ := json.Marshal(map[string]string{
"message_id": messageID,
"encoded_message_create_event": payload.EncryptedContent,
"encoded_message_event_signature": payload.EncodedEventSignature,
})
pathID := strings.ReplaceAll(conversationID, ":", "-")
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/chat/conversations/"+pathID+"/messages",
bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
_ = resp
```
```csharp theme={null}
var messageId = Guid.NewGuid().ToString();
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId,
SenderId = senderId,
ConversationId = conversationId,
ConversationKey = convKey,
Text = "Hello!",
ConversationKeyVersion = convKeyVersion,
SigningKeyVersion = signingKeyVersion,
});
var sendJson = System.Text.Json.JsonSerializer.Serialize(new Dictionary {
["message_id"] = messageId,
["encoded_message_create_event"] = payload.EncryptedContent,
["encoded_message_event_signature"] = payload.EncodedEventSignature,
});
using var content = new StringContent(sendJson, Encoding.UTF8, "application/json");
var pathId = conversationId.Replace(':', '-');
using var resp = await http.PostAsync(
$"https://api.x.com/2/chat/conversations/{Uri.EscapeDataString(pathId)}/messages",
content);
resp.EnsureSuccessStatusCode();
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = UUID.randomUUID().toString();
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = convKey;
params.text = "Hello!";
params.conversationKeyVersion = convKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
String pathId = conversationId.replace(':', '-');
String sendJson = new ObjectMapper().writeValueAsString(Map.of(
"message_id", params.messageId,
"encoded_message_create_event", payload.encryptedContent,
"encoded_message_event_signature", payload.encodedEventSignature));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/conversations/" + pathId + "/messages"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(sendJson))
.build();
http.send(req, HttpResponse.BodyHandlers.ofString());
```
***
## 6. 受信して復号する
ライブトラフィックには [Webhook またはアクティビティストリーム](/xchat/real-time-events) を使用します。履歴には会話**イベント**をページングします。
* ライブペイロードのフィールド: `encoded_event`、オプションの `conversation_key_change_event`
* 履歴: `GET /2/chat/conversations/{id}/events` — 全イベントに対する **`decrypt_events`** に加えて `meta.conversation_key_events` を優先
* 署名検証のために送信者の公開鍵を decrypt に渡します(API フィールドを `SigningKeyEntry` にマップします;[Chat XDK](/xchat/xchat-xdk) を参照)
* JavaScript は camelCase のイベントタイプ(`message`)を使用します;他の言語は JSON で `"Message"` と snake\_case フィールドを使用します
```python theme={null}
conversation_keys = {} # conversation_id -> { version: key_bytes }
def signing_keys_for(user_id: str) -> list[dict]:
resp = client.chat.get_user_public_keys(
user_id,
public_key_fields=[
"public_key_version", "public_key", "signing_public_key", "identity_public_key_signature",
],
)
return [
{
"user_id": user_id,
"public_key_version": r["public_key_version"],
"public_key": r["signing_public_key"],
"identity_public_key": r["public_key"],
"identity_public_key_signature": r["identity_public_key_signature"],
}
for r in resp.data
]
def handle_payload(payload: dict):
cid = payload["conversation_id"]
if payload.get("conversation_key_change_event"):
conversation_keys[cid] = chat.extract_conversation_keys(
[payload["conversation_key_change_event"]]
)["keys"]
event = chat.decrypt_event(
payload["encoded_event"],
conversation_keys.get(cid, {}),
signing_keys_for(payload["sender_id"]),
)
if event.get("type") == "Message" and event.get("content", {}).get("content_type") == "Text":
print(event["sender_id"], event["content"]["text"], event.get("verified"))
```
```typescript theme={null}
const conversationKeys = new Map>();
async function signingKeysFor(userId: string) {
const resp = await client.chat.getUserPublicKeys(userId, {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key', 'identity_public_key_signature',
],
});
return resp.data.map((r: {
public_key_version: string;
public_key: string;
signing_public_key: string;
identity_public_key_signature: string;
}) => ({
userId,
publicKeyVersion: r.public_key_version,
publicKey: r.signing_public_key,
identityPublicKey: r.public_key,
identityPublicKeySignature: r.identity_public_key_signature,
}));
}
async function handlePayload(payload: {
conversation_id: string;
encoded_event: string;
sender_id: string;
conversation_key_change_event?: string;
}) {
const cid = payload.conversation_id;
if (payload.conversation_key_change_event) {
conversationKeys.set(
cid,
chat.extractConversationKeys([payload.conversation_key_change_event]).keys,
);
}
const event = chat.decryptEvent(
payload.encoded_event,
conversationKeys.get(cid) ?? {},
await signingKeysFor(payload.sender_id),
);
if (event.type === 'message' && event.content?.contentType === 'text') {
console.log(event.senderId, event.content.text, event.verified);
}
}
```
```rust theme={null}
// Build Vec from GET /2/users/{id}/public_keys
// (public_key_version, public_key, signing_public_key, identity_public_key_signature)
if let Some(kc) = key_change_b64.as_deref() {
let extracted = chat.extract_conversation_keys(&[kc]);
conv_keys.extend(extracted.keys);
}
let event = chat.decrypt_event(&encoded_event, &conv_keys, &sender_signing_keys)?;
```
```go theme={null}
if keyChange != "" {
extracted, _ := chat.ExtractConversationKeys([]string{keyChange})
for v, k := range extracted.Keys {
convKeys[v] = k
}
}
event, err := chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys)
if err == nil && event.Type == "Message" {
fmt.Println(event.AsMessage().Text())
}
```
```csharp theme={null}
if (!string.IsNullOrEmpty(keyChangeB64))
{
var extracted = chat.ExtractConversationKeys(new[] { keyChangeB64 });
foreach (var kv in extracted.Keys)
convKeys[kv.Key] = kv.Value;
}
var evt = chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys);
if (evt.GetProperty("type").GetString() == "Message")
Console.WriteLine(evt.GetProperty("content").GetProperty("text").GetString());
```
```java theme={null}
if (keyChangeB64 != null && !keyChangeB64.isEmpty()) {
var extracted = chat.extractConversationKeys(List.of(keyChangeB64));
convKeys.putAll(extracted.keys);
}
JsonNode evt = chat.decryptEvent(encodedEvent, convKeys, senderSigningKeys);
if ("Message".equals(evt.path("type").asText())) {
System.out.println(evt.path("content").path("text").asText());
}
```
全言語向けの完全なポール&リプライボット: [chat-xdk/examples](https://github.com/xdevplatform/chat-xdk/tree/main/examples)。
***
## ベストプラクティス
* 未加工の会話鍵と送信者の公開鍵をキャッシュし、署名検証が失敗した場合は更新する
* `event_uuid` でライブ配信の重複を排除する
* ページネーションが完了するまでイベント履歴をページングし、鍵変更のメタデータを見逃さないようにする
* 本番環境でパスコード、秘密鍵、メッセージ平文をログに残さない
* Web アプリでは、OAuth トークン(および鍵バックアップ realm トークン発行)をサーバー側で保持し、秘密鍵はクライアントの Chat XDK 内でのみ保持することが望ましい
***
## 次のステップ
すべての言語バインディングのメソッドと型
暗号化された画像とファイル添付
複数参加者の会話とメタデータ
Webhook とアクティビティ配信
# グループ会話
Source: https://docs.x.com/ja/xchat/groups
共有された会話鍵、暗号化されたタイトル、メンバー管理、署名付きメッセージを備えた複数参加者の X Chat グループ会話を作成します。
グループチャットは、1:1 の X Chat と**同じ暗号化モデル**を使用します: メンバーで共有する 1 つの**会話鍵**を、各メンバーの **identity 公開鍵**にラップし、メッセージは Chat XDK によって暗号化・署名されます。変わるのは、**メンバーシップ**、**会話の作成方法**、そしてしばしば会話上の**暗号化されたタイトル/アバター**フィールドです。
1:1 のフローは [Getting Started](/xchat/getting-started) にあります。エンドポイントの詳細は **API リファレンス → Conversations and messages** の下にあります。
***
## グループと 1:1 の違い
| トピック | 1:1 | グループ |
| :------- | :---------------------------- | :------------------------------ |
| 識別 | 多くの場合、パス内でピアユーザー ID によって指定される | 会話 ID は通常 `g` で始まる |
| 作成 | 鍵 + ユーザーへのメッセージ送信 | グループ作成/初期化 API、その後鍵 |
| 参加者 | あなた + 1 人のピア | 多数のユーザー;メンバーシップは変更可能 |
| メタデータ | 最小限 | 名前、アバターなどが**暗号文**の可能性あり(会話鍵で復号) |
| 鍵ローテーション | 頻度は少ない | メンバーの参加や離脱時によく発生 |
暗号処理は依然として: 鍵とペイロードには **Chat XDK**、グループの作成、参加者鍵ラップの公開、メッセージの送信、イベントのロードには **X API** です。
***
## グループの作成と鍵の確立
1. `POST /2/chat/conversations/group/initialize` でグループ ID を発行します — レスポンスの `data.conversation_id` は、以下のすべての箇所で使用する g プレフィックス付きの ID です。
2. 各メンバーの identity 公開鍵と `public_key_version` をロードします(**Encryption keys** の下にある `GET` 公開鍵ルート;[`GET /2/users/public_keys`](/x-api/users/get-public-keys-for-multiple-users) は複数のユーザーを 1 回のリクエストで取得します)。使用前に各レコードを `verify_key_binding` で検証してください([Getting Started](/xchat/getting-started#4-set-up-conversation-keys) の警告を参照)。
3. **`prepare_group_create`** を、**すべての**メンバー(自分自身を含む)、g プレフィックス付き ID、メンバー/管理者 ID リストとともに一度実行します。1 回の呼び出しで会話鍵を生成し、すべてのメンバー用にラップし、作成に署名します — **2 つ**のアクション署名(会話鍵の変更とグループ作成)を返します。
4. `POST /2/chat/conversations/group` に、グループのメンバー/管理者、`conversation_key_version`、`conversation_participant_keys`(SDK **`encrypted_key`** → API **`encrypted_conversation_key`**)、および**両方**の `action_signatures` を送信します。検証失敗は、安定した人間が読めるメッセージとして返されます。たとえば `"Too many members: adding these members would exceed the allowed group size."` や `"Cannot add all members: one or more of the requested members cannot be added to this conversation."` です。
5. 暗号化/復号のために、**未加工の**会話鍵と**バージョン**を保持します。
`prepare_group_create` に渡す `title` と `avatar_url` は署名され、グループ作成イベントにそのまま埋め込まれます。サーバーはリクエストに対してそれらを照合します — したがって、POST ボディの `group_name` / `group_avatar_url` の値は SDK に渡したものと**バイト単位で同一**でなければなりません。そうでなければ、呼び出しは署名検証に失敗します。
```python theme={null}
prepared = chat.prepare_group_create(
"YOUR_USER_ID", signing_key_version, member_public_keys,
group_id, # g-prefixed id from POST /2/chat/conversations/group/initialize
member_ids, admin_ids, title="Project team",
)
# POST /2/chat/conversations/group with group_members, group_admins,
# conversation_key_version, conversation_participant_keys, and BOTH
# entries of prepared["action_signatures"]
```
```typescript theme={null}
const prepared = chat.prepareGroupCreate({
senderId: myUserId, signingKeyVersion, publicKeys: memberPublicKeys,
conversationId: groupId, // g-prefixed id from POST /2/chat/conversations/group/initialize
memberIds, adminIds, title: 'Project team',
});
// prepared.actionSignatures has two entries — send both
```
```rust theme={null}
let mut params = GroupCreateParams::new(
&sender_id, &signing_key_version, member_public_keys,
&group_id, member_ids, admin_ids,
);
params.title = Some("Project team".into());
let prepared = chat.prepare_group_create(params)?;
// prepared.action_signatures has two entries — send both
```
```go theme={null}
prepared, err := chat.PrepareGroupCreate(chatxdk.GroupCreateParams{
SenderID: myUserID, SigningKeyVersion: signingKeyVersion,
PublicKeys: memberPublicKeys, ConversationID: groupID,
MemberIDs: memberIDs, AdminIDs: adminIDs, Title: "Project team",
})
// prepared.ActionSignatures has two entries — send both
_ = prepared
_ = err
```
```csharp theme={null}
var prepared = chat.PrepareGroupCreate(new GroupCreateParams {
SenderId = myUserId, SigningKeyVersion = signingKeyVersion,
PublicKeys = memberPublicKeys, ConversationId = groupId,
MemberIds = memberIds, AdminIds = adminIds, Title = "Project team",
});
// prepared.ActionSignatures has two entries — send both
```
```java theme={null}
GroupCreateParams params = new GroupCreateParams();
params.senderId = myUserId;
params.signingKeyVersion = signingKeyVersion;
params.publicKeys = memberPublicKeys;
params.conversationId = groupId;
params.memberIds = memberIds;
params.adminIds = adminIds;
params.title = "Project team";
PreparedConversationChange prepared = chat.prepareGroupCreate(params);
// prepared.actionSignatures has two entries — send both
```
参加者鍵とアクション署名のボディマッピング(`message_id`、`encoded_message_event_detail`、ネストされた `message_event_signature`)は、[Getting Started — conversation keys](/xchat/getting-started#4-set-up-conversation-keys) の鍵 POST と同じです。
メンバーシップが変更されたときは、**`prepare_group_members_change`** を新しいメンバー ID と現在のロスター(メンバー、管理者、保留中のメンバー、および設定されている場合は現在のタイトル/アバター/TTL)とともに呼び出します。会話鍵をローテーションし、グループ作成と同様に**2 つ**のアクション署名を返します — すべてを **add members**(`POST /2/chat/conversations/{id}/members`)に POST します。その後、**鍵変更**トラフィックが期待されます: [Getting Started の鍵ローテーション](/xchat/getting-started#6-receive-and-decrypt) のように扱います(`extract_conversation_keys` / `decrypt_events`、その後最新バージョンで暗号化)。
`prepare_group_members_change` は、渡したロスターにのみラップされた**新しい**会話鍵を生成するため、新しいメンバーは新しい鍵バージョンを受け取り、以前のバージョンで送信されたメッセージを復号できません。その逆は真ではありません: ローテーションは**以前の**バージョンへのアクセスを取り消しません — 古い鍵をすでに持っている人は、その下で暗号化されたメッセージを読み続けることができます。会話鍵が漏洩したと疑われる場合は、`prepare_conversation_key_change` でローテーションしてください;これは将来のメッセージのみを保護します。
***
## 暗号化されたグループメタデータ
一部の会話フィールド(たとえば表示**名**や**アバター URL**)は、会話鍵で**暗号化された**状態で到着することがあります。これは `encrypt_message` ではありません。汎用の Chat XDK **`encrypt` / `decrypt`** のペア(UTF-8 文字列入力、base64 暗号文出力、**未加工の**会話鍵を使用)です。
特定のフィールドが暗号化されて保存されるかどうかは、それを書き込むクライアントによって決定されます: `prepare_group_create` は、提供されたとおりにタイトルに署名して送信します(会話鍵はその呼び出しが生成するまで存在しないため、作成時のタイトルはその下で暗号化できません)。フィールドが暗号文である会話を読むときは、フィールドが書き込まれたときにアクティブだった鍵バージョンで `decrypt` して復号します。
```python theme={null}
# Decrypt a field from the conversation object (name may vary by API shape)
group_name = chat.decrypt(conversation["group_name"], raw_conv_key)
# Encrypt before update if your API accepts ciphertext metadata
encrypted_name = chat.encrypt("Project team", raw_conv_key)
```
```typescript theme={null}
const groupName = chat.decrypt(conversation.groupName, rawConvKey);
const encryptedName = chat.encrypt('Project team', rawConvKey);
```
```rust theme={null}
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let group_name = chat.decrypt(&conversation_group_name_b64, &conv_key)?;
let encrypted_name = chat.encrypt("Project team", &conv_key)?;
```
```go theme={null}
groupName, err := chat.Decrypt(conversationGroupNameB64, rawConvKey)
encryptedName, err := chat.Encrypt("Project team", rawConvKey)
_ = groupName
_ = encryptedName
```
```csharp theme={null}
string groupName = chat.Decrypt(conversationGroupNameB64, rawConvKey);
string encryptedName = chat.Encrypt("Project team", rawConvKey);
```
```java theme={null}
String groupName = chat.decrypt(conversationGroupNameB64, rawConvKey);
String encryptedName = chat.encrypt("Project team", rawConvKey);
```
そのメタデータに適用される**現在の**会話鍵バージョンを使用してください。鍵がローテーションされている場合は、フィールドが書き込まれたときにアクティブだったバージョンで復号してください(または、メタデータがローテーション時に常に書き換えられる場合は製品のルールに従ってください)。
***
## メッセージとイベント
グループでの送受信は、未加工の会話鍵を持てば 1:1 と同じです:
* **送信:** `encrypt_message` → メッセージ送信 API([Getting Started](/xchat/getting-started#5-send-a-message))
* **受信:** イベント API または[リアルタイム配信](/xchat/real-time-events) → `decrypt_event` / `decrypt_events`
* **メディア:** グループの会話 ID を使った [Media](/xchat/media)
メンバーシップに起因するローテーション後は、常に**最新の**鍵バージョンで暗号化してください。
***
## チェックリスト
1. `POST /2/chat/conversations/group/initialize` で g プレフィックス付き ID を発行する
2. **すべての**メンバーで `prepare_group_create`;参加者鍵ラップと**両方**のアクション署名を `POST /2/chat/conversations/group` に POST する
3. 未加工の鍵 + バージョンをキャッシュ;鍵変更イベントで更新する
4. メンバーシップ変更時は `prepare_group_members_change`(2 つの署名)→ `POST /2/chat/conversations/{id}/members`
5. フィールドが暗号文の場合は `decrypt` でグループメタデータを復号する
6. 1:1 と同じパターンで送受信する
# Chat API の紹介
Source: https://docs.x.com/ja/xchat/introduction
X Chat API の概要。Chat XDK によるクライアントサイド暗号化で、エンドツーエンド暗号化かつ署名付きのダイレクトメッセージを送受信します。
**Chat API** を使うと、X 上で**エンドツーエンド暗号化**されたダイレクトメッセージを送受信できます。メッセージ本文はクライアント側で暗号化され、X は暗号文をルーティングするだけで平文コンテンツを読むことはできません。メッセージには**署名**も付与されるため、受信者は送信者を検証できます。
***
## アプリに必要な要素
| 要素 | 役割 |
| :------------------------------- | :---------------------------------------------------------------------------------------- |
| **[Chat XDK](/xchat/xchat-xdk)** | 鍵生成、暗号化・復号、署名・検証、オプションのパスコード保護された安全な鍵バックアップ(Python、JS、Rust、Go、C#、Java) |
| **X API アクセス** | 公開鍵、会話鍵、メッセージ、イベント、メディア — **[XDK](/xdks/python/overview)**(Python/TypeScript)または HTTPS 経由 |
| **配信** | ライブイベント用の [Webhook またはアクティビティストリーム](/xchat/real-time-events);履歴用のイベント API |
完全な実装は **[Getting Started](/xchat/getting-started)** に従ってください。概念のみを知りたい場合は、**[暗号化入門](/xchat/cryptography-primer)** を参照してください。
***
## 暗号化の仕組み(概要)
1. **identity** キーペアと **signing** キーペアを作成し、秘密鍵を安全に保存します(安全な鍵バックアップまたは保護された blob)。
2. **公開鍵を公開**して、他のユーザーがあなたと会話鍵を交換し、署名を検証できるようにします。
3. 各参加者向けに暗号化されたコピーを投稿して、**会話鍵**を共有します。
4. 送信メッセージを**暗号化して署名**し、X には暗号文のみを送信します。
5. Webhook、ストリーム、またはイベント履歴経由で暗号文を**受信**します。
6. Chat XDK を使って**検証と復号**を行います。
***
## 便利なエンドポイント
サイドバーの **API reference** にまとめられており、以下を含みます:
* 公開鍵 — 登録と取得
* 会話とメッセージ — 会話の一覧/取得、鍵の追加/ローテーション、イベント、送信、タイピング、既読、グループメンバーシップ
* メディア — 暗号化された添付ファイルのアップロードとダウンロード([ガイド](/xchat/media))
***
## 認証に関する注意
DM 関連スコープ(`dm.read`、`dm.write`、必要に応じて `users.read` / `tweet.read`;アップロード用に `media.write`)を伴う **OAuth 2.0 ユーザーコンテキスト**を使用してください。ユーザーの X Chat アクティビティにはそのユーザーの認可が必要です。安全な鍵バックアップの設定は、**あなたの**公開鍵レコード(`juicebox_config` フィールド)で返されます — Getting Started を参照してください。
***
## 次のステップ
1. [暗号化入門](/xchat/cryptography-primer) — E2EE の概念に関する任意の背景知識
2. [Getting Started](/xchat/getting-started) — 鍵の実装、送信、受信
3. [Chat XDK](/xchat/xchat-xdk) — 暗号化 SDK リファレンス
4. 必要に応じて [リアルタイムイベント](/xchat/real-time-events)、[メディア](/xchat/media)、[トラブルシューティング](/xchat/troubleshooting)
# メディアと添付ファイル
Source: https://docs.x.com/ja/xchat/media
Chat XDK のストリーム暗号化とメディアアップロードエンドポイントを使い、X Chat で画像やファイル添付を暗号化・アップロード・送信・ダウンロード・復号します。
画像やその他のファイルは、テキストと**同じ会話鍵**を使用します。Chat XDK(`encrypt_stream` / `decrypt_stream`)でバイトを暗号化し、**`/2/chat/media/upload`** ルート(サイドバー **API リファレンス → Media**)経由でアップロードし、`encrypt_message` で **`media_hash_key`** を添付します。
アップロード時は、DM スコープに **`media.write`** を含めてください。パスにはハイフン付きの会話 ID を使います(`:` → `-`)。MIME や寸法は**復号済みの**バイトから取得することが望ましいです。
このパスは Posts メディアモデル(`expansions=attachments.media_keys`、`media.fields=variants` など)**ではありません**。それらのパラメータは **Posts** に適用されます;E2EE X Chat の blob は **`media_hash_key`** と X Chat メディアダウンロードでアドレス指定されます。
```mermaid theme={null}
flowchart LR
A[Plain bytes] --> B[encrypt_stream]
B --> C[Upload 3 steps]
C --> D[media_hash_key]
D --> E[encrypt_message + send]
F[GET media] --> G[decrypt_stream]
G --> H[Plain bytes]
```
***
## 暗号化
```python theme={null}
from chat_xdk import detect_mime_type, detect_image_dimensions
with open("photo.jpg", "rb") as f:
plaintext = f.read()
mime = detect_mime_type(plaintext)
dims = detect_image_dimensions(plaintext)
width, height = dims if dims else (0, 0)
encrypted_blob = chat.encrypt_stream(plaintext, raw_conv_key)
```
```typescript theme={null}
import { detectMimeType, detectImageDimensions } from '@xdevplatform/chat-xdk';
import { readFile } from 'fs/promises';
const plaintext = await readFile('photo.jpg');
const mime = detectMimeType(plaintext);
const dims = detectImageDimensions(plaintext);
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;
const encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
```
```rust theme={null}
use chat_xdk_core::{detect_image_dimensions, detect_mime_type};
let plaintext = std::fs::read("photo.jpg")?;
let _mime = detect_mime_type(&plaintext);
let dims = detect_image_dimensions(&plaintext);
let (width, height) = dims.map(|d| (d.width as i64, d.height as i64)).unwrap_or((0, 0));
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let encrypted_blob = chat.encrypt_stream(&plaintext, &conv_key)?;
```
```go theme={null}
plaintext, err := os.ReadFile("photo.jpg")
mime, _ := chatxdk.DetectMimeType(plaintext)
dims, _ := chatxdk.DetectImageDimensions(plaintext)
_ = mime
encrypted, err := chat.EncryptStream(plaintext, rawConvKey)
_ = dims
_ = encrypted
```
```csharp theme={null}
using ChatXdk;
byte[] plaintext = await File.ReadAllBytesAsync("photo.jpg");
string? mime = ChatXdkUtilities.DetectMimeType(plaintext);
var dims = ChatXdkUtilities.DetectImageDimensions(plaintext);
int width = (int)(dims?.Width ?? 0);
int height = (int)(dims?.Height ?? 0);
byte[] encryptedBlob = chat.EncryptStream(plaintext, rawConvKey);
```
```java theme={null}
import com.x.chatxdk.ChatXdkUtilities;
import com.x.chatxdk.Types.ImageDimensions;
byte[] plaintext = Files.readAllBytes(Path.of("photo.jpg"));
String mime = ChatXdkUtilities.detectMimeType(plaintext);
ImageDimensions dims = ChatXdkUtilities.detectImageDimensions(plaintext);
int width = dims != null ? (int) dims.width : 0;
int height = dims != null ? (int) dims.height : 0;
byte[] encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
```
`encrypt_stream` / `decrypt_stream` はペイロード全体をメモリ内で処理します。大きなファイルの場合、`stream_encryptor()` / `stream_decryptor()` はインクリメンタルなオブジェクト(`StreamEncryptor` / `StreamDecryptor`)を返します: `push` でチャンクを供給し、最後に `finish` を 1 回呼び出します — ストリームが切り詰められた場合、`finish` はエラーを返します。
***
## アップロード
| ステップ | メソッド | パス |
| :--- | :----- | :----------------------------------- |
| 初期化 | `POST` | `/2/chat/media/upload/initialize` |
| 追加 | `POST` | `/2/chat/media/upload/{id}/append` |
| 確定 | `POST` | `/2/chat/media/upload/{id}/finalize` |
**API リファレンス → Media** の下にある OpenAPI ページのリクエストボディを使用してください。サイズが必要な場合は、**暗号化済みの** blob サイズを優先してください。Finalize は添付とダウンロード用の **`media_hash_key`** を返します。一時的な `5xx` はバックオフで再試行してください。Python/TypeScript ではメディアヘルパーが存在する場合は XDK を使用できます;それ以外は任意の言語で Bearer トークンを使って POST します。
***
## 添付ファイル付きで送信する
メディア添付付きで暗号化し、その後メッセージ送信ボディを POST します(フィールドマッピングは [Getting Started](/xchat/getting-started#5-send-a-message) と同じ)。
```python theme={null}
import uuid
from xdk.chat.models import SendMessageRequest
message_id = str(uuid.uuid4())
payload = chat.encrypt_message(
message_id,
sender_id,
conversation_id,
raw_conv_key,
caption or "",
conversation_key_version,
signing_key_version,
attachments=[{
"attachment_type": "media",
"media_hash_key": media_hash_key,
"width": width,
"height": height,
"filesize_bytes": len(plaintext),
"filename": "photo.jpg",
}],
)
client.chat.send_message(
conversation_id.replace(":", "-"),
SendMessageRequest(
message_id=message_id,
encoded_message_create_event=payload.encrypted_content,
encoded_message_event_signature=payload.encoded_event_signature,
),
)
```
```typescript theme={null}
const messageId = crypto.randomUUID();
const payload = chat.encryptMessage({
messageId,
senderId,
conversationId,
conversationKey: rawConvKey,
text: caption || '',
conversationKeyVersion,
signingKeyVersion,
attachments: [{
attachmentType: 'media',
mediaHashKey: mediaHashKey,
width,
height,
filesizeBytes: plaintext.byteLength,
filename: 'photo.jpg',
}],
});
await client.chat.sendMessage(conversationId.replace(/:/g, '-'), {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
});
```
```rust theme={null}
// Set attachments on EncryptMessageParams per chat_xdk_core AttachmentDescriptor::Media
let payload = chat.encrypt_message(params_with_media_attachment)?;
let body = serde_json::json!({
"message_id": message_id,
"encoded_message_create_event": payload.encrypted_content,
"encoded_message_event_signature": payload.encoded_event_signature,
});
let path_id = conversation_id.replace(':', "-");
http.post(format!("https://api.x.com/2/chat/conversations/{path_id}/messages"))
.header("Authorization", &auth)
.json(&body)
.send()?;
```
```go theme={null}
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawConvKey, Text: caption,
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
Attachments: []chatxdk.AttachmentDescriptor{{
AttachmentType: "media",
MediaHashKey: mediaHashKey,
Width: width,
Height: height,
FilesizeBytes: int64(len(plaintext)),
Filename: "photo.jpg",
}},
})
// POST payload.EncryptedContent / EncodedEventSignature to /2/chat/conversations/{id}/messages
```
```csharp theme={null}
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId,
SenderId = senderId,
ConversationId = conversationId,
ConversationKey = rawConvKey,
Text = caption ?? "",
ConversationKeyVersion = conversationKeyVersion,
SigningKeyVersion = signingKeyVersion,
// Attachments = media descriptor with MediaHashKey, Width, Height,
// FilesizeBytes, and Filename (as in the Go tab above)
});
// POST EncryptedContent / EncodedEventSignature as for text messages
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawConvKey;
params.text = caption != null ? caption : "";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
// params.attachments — media type with mediaHashKey, width, height, filename
SendPayload payload = chat.encryptMessage(params);
// POST to /2/chat/conversations/{id}/messages
```
***
## ダウンロードして復号する
パス: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/download-chat-media)。レスポンスボディは暗号文です。受信メッセージでは、復号された添付ファイル / `media_hashes` から `media_hash_key` を読み取ります。
**イベントの鍵バージョンで鍵を選択します。** 各復号済みメッセージイベントは、そのコンテンツが暗号化された `keyVersion`(JS;他のバインディングでは `key_version`)を保持しています。添付ファイルは**その**バージョンの会話鍵で復号してください — `conversationKeys.keys[event.keyVersion]` — 最新のものではありません。鍵ローテーション(たとえばメンバー追加)の後、最新の鍵では古いメッセージに添付されたメディアを復号できません。
```python theme={null}
keys = result["conversation_keys"]["keys"]
key_for_media = keys[event["key_version"]] # not the latest version
plaintext = chat.decrypt_stream(encrypted_blob, key_for_media)
```
```typescript theme={null}
const keys = result.conversationKeys.keys;
const keyForMedia = keys[event.keyVersion]; // not the latest version
const plaintext = chat.decryptStream(encryptedBlob, keyForMedia);
```
```python theme={null}
import requests
from chat_xdk import detect_mime_type
api_id = conversation_id.replace(":", "-")
url = f"https://api.x.com/2/chat/media/{api_id}/{media_hash_key}"
r = requests.get(url, headers={"Authorization": f"Bearer {access_token}"})
r.raise_for_status()
plaintext = chat.decrypt_stream(r.content, raw_conv_key)
mime = detect_mime_type(plaintext) or "application/octet-stream"
```
```typescript theme={null}
import { detectMimeType } from '@xdevplatform/chat-xdk';
const apiId = conversationId.replace(/:/g, '-');
const res = await fetch(
`https://api.x.com/2/chat/media/${apiId}/${mediaHashKey}`,
{ headers: { Authorization: `Bearer ${accessToken}` } },
);
const encryptedBlob = new Uint8Array(await res.arrayBuffer());
const plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
const mime = detectMimeType(plaintext) ?? 'application/octet-stream';
```
```rust theme={null}
let api_id = conversation_id.replace(':', "-");
let encrypted_blob = http
.get(format!("https://api.x.com/2/chat/media/{api_id}/{media_hash_key}"))
.header("Authorization", &auth)
.send()?
.bytes()?;
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let plaintext = chat.decrypt_stream(&encrypted_blob, &conv_key)?;
```
```go theme={null}
url := fmt.Sprintf("https://api.x.com/2/chat/media/%s/%s",
strings.ReplaceAll(conversationID, ":", "-"), mediaHashKey)
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := http.DefaultClient.Do(req)
// read body into []byte → chat.DecryptStream(encryptedBlob, rawConvKey)
_ = resp
_ = err
```
```csharp theme={null}
var apiId = conversationId.Replace(':', '-');
byte[] encryptedBlob = await http.GetByteArrayAsync(
$"https://api.x.com/2/chat/media/{apiId}/{mediaHashKey}");
byte[] plaintext = chat.DecryptStream(encryptedBlob, rawConvKey);
string? mime = ChatXdkUtilities.DetectMimeType(plaintext);
```
```java theme={null}
String apiId = conversationId.replace(':', '-');
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/media/" + apiId + "/" + mediaHashKey))
.header("Authorization", "Bearer " + accessToken)
.GET()
.build();
byte[] encryptedBlob = http.send(req, HttpResponse.BodyHandlers.ofByteArray()).body();
byte[] plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
String mime = ChatXdkUtilities.detectMimeType(plaintext);
```
***
## ヒント
* メディアが暗号化されたときと同じ**会話鍵バージョン**を使用する
* 平文メディアや未加工の鍵をログに出力しない
* MIME は復号**後**に検出する
* Web クライアント: 可能な場合はクライアント側で暗号化・復号する;OAuth トークンはサーバー側に保持する
各メディアルート(アップロード初期化、チャンク追加、アップロード確定、メディアダウンロード)の完全なリクエストとレスポンスのスキーマは、サイドバーの **API リファレンス → Media** の下にあります。
# リアルタイム X Chat イベント
Source: https://docs.x.com/ja/xchat/real-time-events
Webhook またはアクティビティストリーム経由で chat.received、chat.sent などの暗号化された X Chat アクティビティを受信し、Chat XDK でペイロードを復号します。
X は **`chat.received`**、**`chat.sent`**、および関連する X Chat アクティビティを、ペイロード内の**暗号文**とともに配信します。[Chat XDK](/xchat/xchat-xdk) で復号します。
| レイヤー | 役割 |
| :----------------- | :---------------------------------------------------------------------------------------------------------------------- |
| **X Activity API** | `GET /2/activity/stream`;`POST` / `GET` / `PUT` / `DELETE` `/2/activity/subscriptions`(オペレーションごとの OpenAPI security を参照) |
| **Webhooks** | 独自の HTTPS URL で終端する場合のオプションの `POST` / `GET` `/2/webhooks` および `PUT` / `DELETE` `/2/webhooks/{webhook_id}` ルート |
| **Chat XDK** | `extract_conversation_keys`、`decrypt_event` / `decrypt_events` |
プライベート X Chat イベントタイプは、監視するユーザーに対する認可が必要です。暗号化された X Chat ファイル添付は、Post API の `expansions=attachments.media_keys` / `media.fields=variants` ではなく、**`media_hash_key`** と X Chat メディアダウンロードを使用します。
***
## イベントタイプ
| イベント | いつ |
| :----------------------- | :--------------------------- |
| `chat.received` | サブスクライブされたユーザーが暗号化された DM を受信 |
| `chat.sent` | サブスクライブされたユーザーが暗号化された DM を送信 |
| `chat.conversation_join` | サブスクライブされたユーザーがグループに参加(提供時) |
***
## 1. 配信方法を選択する
**アクティビティストリーム(ボットには多くの場合最もシンプル):** アプリの Bearer トークンで `GET /2/activity/stream`(オプションの `backfill_minutes`、`start_time`、`end_time` は OpenAPI ごと)。クライアント側で `chat.received` / `chat.sent` をフィルタリングします。
**アクティビティサブスクリプション:** 以下で永続的なサブスクリプションを管理します:
* `POST /2/activity/subscriptions` — 作成
* `GET /2/activity/subscriptions` — 一覧(ページネーション)
* `PUT /2/activity/subscriptions/{subscription_id}` — 更新
* `DELETE /2/activity/subscriptions/{subscription_id}` または `DELETE /2/activity/subscriptions?ids=` — 削除
リクエストボディと必要なスコープは、各ルートの OpenAPI オペレーションで定義されています。X Activity API(XAA)サブスクリプションの作成には、監視対象ユーザーに対する**ユーザーコンテキスト認可**(`dm.read` などチャットイベントに関連するスコープを持つ OAuth 2.0 ユーザーコンテキスト)が必要です。
**Webhook:** HTTPS エンドポイントでイベントを終端する場合、`POST /2/webhooks` で Webhook を登録し、CRC チャレンジをパスし、その後 `POST /2/activity/subscriptions` で `webhook_id` を参照してアクティビティサブスクリプションを作成します(OpenAPI の Webhooks および Activity オペレーションを参照)。Python/TypeScript XDK は、SDK のバージョンに含まれる場合、Webhook とアクティビティのヘルパーを公開することがあります。
```python theme={null}
from xdk import Client
# Stream (app token) — exact helper names depend on your XDK version
stream_client = Client(bearer_token="YOUR_BEARER_TOKEN")
# for event in stream_client.activity.stream():
# handle_payload(event) # see "Decrypt with the Chat XDK" below
# Or create a subscription — requires user-context auth for the monitored user
client = Client(access_token="YOUR_OAUTH2_USER_TOKEN")
client.activity.create_subscription({
"event_type": "chat.received",
"filter": {"user_id": "USER_ID_TO_MONITOR"},
})
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
// Creating a subscription requires user-context auth for the monitored user
const client = new Client({ accessToken: 'YOUR_OAUTH2_USER_TOKEN' });
await client.activity.createSubscription({
event_type: 'chat.received',
filter: { user_id: 'USER_ID_TO_MONITOR' },
});
// Stream: client.activity.stream() when available in your SDK version
```
送信コピーが必要な場合は `chat.sent` にもサブスクライブしてください。他の言語: 同じ `/2/activity/*` HTTPS ルートを直接呼び出します(サブスクリプションの作成にはユーザーコンテキストトークン、ストリームにはアプリの Bearer トークン)。
***
## 2. CRC(Webhook のみ)
Webhook を使用する場合、コンシューマシークレットを使ったトークンの HMAC-SHA256 を、Webhook 製品が期待する JSON 形式(通常は `sha256=`)で Challenge-Response Checks(GET `crc_token`)に応答してください。
***
## 3. Chat XDK で復号する
ライブフィールド: **`payload.encoded_event`**、オプションの **`payload.conversation_key_change_event`**。**`event_uuid`** で重複を排除します。
JavaScript は camelCase のイベントタイプ(`message`)を使用します;他のバインディングは `"Message"` と snake\_case フィールドを使用します。
```python theme={null}
from chat_xdk import Chat
chat = Chat(JUICEBOX_CONFIG_JSON)
chat.unlock("YOUR_PASSCODE")
chat.set_key_version(SIGNING_KEY_VERSION)
conversation_keys = {}
def signing_keys(user_id: str):
resp = api_client.chat.get_user_public_keys(
user_id,
public_key_fields=[
"public_key_version", "public_key", "signing_public_key", "identity_public_key_signature",
],
)
return [
{
"user_id": user_id,
"public_key_version": r["public_key_version"],
"public_key": r["signing_public_key"],
"identity_public_key": r["public_key"],
"identity_public_key_signature": r["identity_public_key_signature"],
}
for r in resp.data
]
data = body.get("data") or {}
if data.get("event_type") in ("chat.received", "chat.sent"):
p = data.get("payload") or {}
cid = p.get("conversation_id")
if p.get("conversation_key_change_event"):
conversation_keys[cid] = chat.extract_conversation_keys(
[p["conversation_key_change_event"]]
)["keys"]
ev = chat.decrypt_event(
p["encoded_event"],
conversation_keys.get(cid, {}),
signing_keys(p["sender_id"]),
)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: JUICEBOX_CONFIG_JSON,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(SIGNING_KEY_VERSION);
const conversationKeys = new Map>();
async function signingKeys(userId: string) {
const resp = await apiClient.chat.getUserPublicKeys(userId, {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key', 'identity_public_key_signature',
],
});
return resp.data.map((r: any) => ({
userId,
publicKeyVersion: r.public_key_version,
publicKey: r.signing_public_key,
identityPublicKey: r.public_key,
identityPublicKeySignature: r.identity_public_key_signature,
}));
}
const data = body?.data ?? {};
if (data.event_type === 'chat.received' || data.event_type === 'chat.sent') {
const p = data.payload ?? {};
const cid = p.conversation_id as string;
if (p.conversation_key_change_event) {
conversationKeys.set(
cid,
chat.extractConversationKeys([p.conversation_key_change_event]).keys,
);
}
const ev = chat.decryptEvent(
p.encoded_event,
conversationKeys.get(cid) ?? {},
await signingKeys(p.sender_id),
);
}
```
```rust theme={null}
// chat: ChatCore or Chat, already unlocked / keys imported
if let Some(kc) = key_change.as_deref() {
let extracted = chat.extract_conversation_keys(&[kc]);
conv_keys.extend(extracted.keys);
}
// sender_signing_keys from GET /2/users/{sender_id}/public_keys
let event = chat.decrypt_event(&encoded_event, &conv_keys, &sender_signing_keys)?;
```
```go theme={null}
if keyChange != "" {
extracted, _ := chat.ExtractConversationKeys([]string{keyChange})
for v, k := range extracted.Keys {
convKeys[v] = k
}
}
event, err := chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys)
if err == nil && event.Type == "Message" {
fmt.Println(event.AsMessage().Text())
}
```
```csharp theme={null}
if (!string.IsNullOrEmpty(keyChangeB64))
{
var extracted = chat.ExtractConversationKeys(new[] { keyChangeB64 });
foreach (var kv in extracted.Keys)
convKeys[kv.Key] = kv.Value;
}
var evt = chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys);
if (evt.GetProperty("type").GetString() == "Message")
Console.WriteLine(evt.GetProperty("content").GetProperty("text").GetString());
```
```java theme={null}
if (keyChangeB64 != null && !keyChangeB64.isEmpty()) {
var extracted = chat.extractConversationKeys(List.of(keyChangeB64));
convKeys.putAll(extracted.keys);
}
JsonNode evt = chat.decryptEvent(encodedEvent, convKeys, senderSigningKeys);
if ("Message".equals(evt.path("type").asText())) {
System.out.println(evt.path("content").path("text").asText());
}
```
履歴: [`GET /2/chat/conversations/{id}/events`](/x-api/chat/get-chat-conversation-events) + **`decrypt_events`** — [Getting Started](/xchat/getting-started#6-receive-and-decrypt) を参照。
***
## ペイロードの形(ライブ)
```json theme={null}
{
"data": {
"event_type": "chat.received",
"event_uuid": "0f52b591-4b7e-4f13-92cd-30e6b2a3f18a",
"payload": {
"conversation_id": "1215441834412953600-1843439638876491776",
"sender_id": "1843439638876491776",
"encoded_event": "BASE64_ENCODED_MESSAGE_EVENT",
"conversation_key_version": "1782945126642",
"conversation_key_change_event": "BASE64_ENCODED_KEY_CHANGE_EVENT"
}
}
}
```
***
## プラクティス
* プラットフォームの要件に従って Webhook 署名を検証する
* 会話鍵と送信者の公開鍵をキャッシュする
* 依存メッセージを復号する前に鍵変更 blob を適用する
* `event_uuid` で重複を排除する
# トラブルシューティング
Source: https://docs.x.com/ja/xchat/troubleshooting
Chat XDK のエラー、セキュアな鍵バックアップからの復元、復号の失敗など、X Chat の暗号化に関するよくある問題を診断します。
このページでは、**X Chat の暗号化と Chat XDK に特有の**問題(鍵、安全な鍵バックアップ、復号/検証、暗号化された送信ペイロードの構築)を扱います。
Webhook、OAuth、HTTP ステータスコード、レート制限については、一般的な [X API](/x-api/introduction) および [認証](/fundamentals/authentication/overview) のドキュメントを参照してください。
***
## 鍵と安全な鍵バックアップ
### アンロックに失敗する(無効なパスコード)
* パスコードが `setup` で使用したものと一致するか確認する
* 試行の間で待機する;realm は間違った推測をレート制限し、多くの失敗の後に復元をロックすることがある
```python theme={null}
try:
chat.unlock(passcode)
except ValueError as e:
print(e) # may mention InvalidPin or guesses remaining
```
```typescript theme={null}
try {
await chat.unlock(passcode);
} catch (e) {
console.error((e as Error).message);
}
```
```rust theme={null}
chat.unlock(passcode_bytes).await?;
```
```go theme={null}
if err := chat.Unlock(passcode, juiceboxConfigJSON); err != nil {
log.Println(err)
}
```
```csharp theme={null}
try { chat.Unlock(passcode, juiceboxConfigJson); }
catch (Exception e) { Console.WriteLine(e.Message); }
```
```java theme={null}
try { chat.unlock(passcode, juiceboxConfigJson); }
catch (Exception e) { System.out.println(e.getMessage()); }
```
### 鍵がロードされていないため暗号化または復号に失敗する
まず秘密鍵をロードし、次に X のレコードから公開鍵**バージョン**を設定します。
```python theme={null}
chat.unlock(passcode) # or: chat.import_keys(blob)
chat.set_key_version(signing_key_version)
```
```typescript theme={null}
await chat.unlock(passcode);
chat.setKeyVersion(signingKeyVersion);
```
```rust theme={null}
chat.import_keys(&blob)?;
chat.set_key_version(&signing_key_version);
```
```go theme={null}
blob, _ := chatxdk.Base64ToBytes(privateKeysB64)
_ = chat.ImportKeys(blob)
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
chat.ImportKeys(blobBytes);
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
chat.importKeys(blobBytes);
chat.setKeyVersion(signingKeyVersion);
```
### メッセージに対する会話鍵が欠落している
そのメッセージの `conversation_key_version` に対応する**未加工の**鍵を持っていません。
1. `extract_conversation_keys` で `conversation_key_change_event`(ライブイベント)または `meta.conversation_key_events`(履歴)から鍵素材を復号する、**または**これらの blob を `decrypt_events` に含める
2. そのバージョンの会話鍵が追加されていること、およびあなたがまだ参加者であることを確認する([Getting Started](/xchat/getting-started#4-set-up-conversation-keys) を参照)
### ピアが公開鍵を持っていない
彼らはオンボーディングを完了していない可能性があります。彼らが登録した後、**API リファレンス → Encryption keys** から `public_key`、`signing_public_key`、`identity_public_key_signature`、`public_key_version` をロードしてください。
***
## 復号と署名
### 復号が失敗する
* 古いまたは間違った**未加工の**会話鍵、または間違った鍵バージョン
* 不完全な `encoded_event` 文字列
* イベントタイプが復号可能なコンテンツとして扱える暗号化メッセージではない
### 署名が検証されない
検証は**デフォルトで fail-closed**(`reject_unverified = true`)です: SDK はすでに検証されていない署名付きイベントを拒否しているため、ここでの失敗はチェックをオンにする必要があるという意味ではなく、検証入力が間違っていることを意味します。一般的な原因:
* **送信者**の署名鍵エントリが欠落または不完全(Chat XDK に必要なすべてのフィールド — [Chat XDK](/xchat/xchat-xdk) リファレンスを参照)
* 送信者がバージョンをローテーションした — 公開鍵を再取得する
* 受け入れフロアより下の鍵バージョンは検証されない
`set_reject_unverified` セッターは、このデフォルトから**オプトアウト**する(`false`、推奨されません)ために存在します。以前に無効化した場合は、fail-closed のデフォルトを復元してください:
```python theme={null}
chat.set_reject_unverified(True)
```
```typescript theme={null}
chat.setRejectUnverified(true);
```
```rust theme={null}
chat.set_reject_unverified(true);
```
```go theme={null}
chat.SetRejectUnverified(true)
```
```csharp theme={null}
chat.SetRejectUnverified(true);
```
```java theme={null}
chat.setRejectUnverified(true);
```
### 古いイベントが恒久的に検証に失敗する
**古い**イベントでの `signature missing or no matching signing key` や ECDSA の不一致のようなエラーは恒久的です。署名は不変であり、イベント自体から署名済みペイロードを再構築することで検証されるため、異なるバイトに対して署名された(またはそもそも署名されていない)イベントは、将来のすべてのロードで失敗します — 再試行、鍵の更新、または API 呼び出しでは治せません。これらのイベントは、再試行可能なエラーではなくトゥームストーンとして扱ってください。会話鍵をローテーションすると、その時点からクリーンで検証可能な履歴が始まります;新しいメッセージには影響しません。
***
## 送信ペイロードの構築
これらのミスは X Chat の暗号化に特有のものです(一般的な HTTP エラーではありません):
| 問題 | 修正 |
| :--------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| 間違った鍵バイト | API からの暗号化された鍵文字列ではなく、**未加工の**会話鍵バイトを Chat XDK に渡す |
| 間違った JSON フィールド名 | `encrypted_content` → `encoded_message_create_event`、`encoded_event_signature` → `encoded_message_event_signature` にマップする |
| メッセージ ID の欠落 | `message_id` を自分で生成し、同じ値をリクエストボディで送信する |
| バージョンの不一致 | `conversation_key_version` を使用する鍵と揃える;署名鍵バージョンを `set_key_version` / 公開鍵レコードと揃える |
| パス ID の形式 | URL パスには依然としてハイフン付きの会話 ID が必要(`:` → `-`)ですが、署名の場合、SDK は任意の形式を受け付けます: `A:B`、`A-B`(どちらの順序でも)、または受信者のユーザー ID だけ — すべては同じ署名バイトに正規化される |
### 状態を変更する呼び出しに対して API が 400 を返す
状態を変更するすべてのチャット呼び出し — 会話鍵の追加やローテーション、グループの作成、メンバーの追加 — は、リクエストボディに **`action_signatures`** を要求し、API 境界で検証されます。エントリの欠落や不正な形式(それぞれに `message_id`、`encoded_message_event_detail`、および `signature`、`public_key_version`、`signature_version` を持つ `message_event_signature` が必要)は、即座に HTTP 400 problem-details レスポンスを返します。SDK の prepare メソッド(`prepare_conversation_key_change`、`prepare_group_create`、`prepare_group_members_change`)を使い、返された**すべての**署名を送信してください — グループ作成とメンバー追加は 2 つ返します。
***
## メディアの暗号化と復号
* 添付を参照するメッセージと**同じ**会話鍵(およびバージョン)を使用する
* ダウンロードレスポンスは `decrypt_stream` を実行するまで**暗号文**として扱う
* MIME タイプは復号**後**に推測する;ダウンロードの `Content-Type` は実際の画像タイプでないことがよくある
詳細: [Media](/xchat/media)。
***
## 安全なデバッグ
暗号処理の失敗を調査する際:
* 会話 ID、イベント ID、鍵の**バージョン**のみをログに記録する
* 平文、パスコード、秘密鍵、または完全な鍵 blob は**ログに記録しない**
* `set_key_version` が公開鍵レコードの `public_key_version` と一致することを確認する
* 履歴が不完全な場合、復号する前に鍵変更のメタデータがスキップされないよう、**すべての**イベントページをページングする
# Chat XDK リファレンス
Source: https://docs.x.com/ja/xchat/xchat-xdk
X Chat 用に鍵管理、暗号化、復号、署名を処理する暗号化 SDK である Chat XDK のリファレンス。サポート対象言語で利用できます。
**Chat XDK** は、X Chat の鍵管理、暗号化、復号、および署名を処理します。X の HTTP API は呼び出し**ません** — [Python](/xdks/python/overview) または [TypeScript](/xdks/typescript/overview) の **XDK**、あるいは HTTPS とユーザーアクセストークンと組み合わせて使用してください。
アプリのウォークスルー: [Getting Started](/xchat/getting-started)。サンプルボット: [chat-xdk/examples](https://github.com/xdevplatform/chat-xdk/tree/main/examples)。
### インストール
```bash theme={null}
pip install chatxdk
```
PyPI パッケージは `chatxdk` です。`chat_xdk` としてインポートします。Python 3.10+ が必要です。
```bash theme={null}
npm install @xdevplatform/chat-xdk
npm install juicebox-sdk # optional peer dependency — required for setup()/unlock() secure key backup
```
コンパイル済みの WASM エンジンはパッケージに同梱されています。ビルド手順は不要です。Node.js 18+ が必要です。
```toml theme={null}
[dependencies]
# chat-xdk-core is not yet on crates.io — use the git dependency.
# It exports both ChatCore and the async secure-key-backup Chat type.
chat-xdk-core = { git = "https://github.com/xdevplatform/chat-xdk", tag = "v0.2.1" }
# Required until thrift 0.24 is released on crates.io
[patch.crates-io]
thrift = { git = "https://github.com/apache/thrift.git", rev = "deb36fa409849de45973b04ffc3ce49d277ca90a" }
```
```bash theme={null}
go get github.com/xdevplatform/chat-xdk/go/chatxdk
```
プリコンパイル済みの静的ライブラリが含まれています(macOS arm64/amd64、Linux amd64 glibc/musl)。C コンパイラは必要ですが、Rust は不要です。Go 1.21+ が必要です。
```bash theme={null}
dotnet add package XDevPlatform.ChatXdk
```
パッケージは自己完結型です。macOS(arm64、x64)、Linux(x64)、Windows(x64)用のネイティブライブラリが同梱されています。.NET 8+ が必要です。
```xml theme={null}
com.xchatxdk0.2.1
```
Maven Central で入手できます。jar には macOS(arm64、x64)、Linux(x64)、Windows(x64)用のネイティブライブラリが同梱されており、`jna.library.path` の設定は不要です。`com.x.chatxdk` からインポートします。JDK 17+ が必要です。
***
## クイックスタート
バックログを復号し、鍵をキャッシュし、1 つのイベントを復号し、返信を暗号化します。[Getting Started](/xchat/getting-started) のように、送信ボディを [`POST /2/chat/conversations/{id}/messages`](/x-api/chat/send-chat-message) に接続します。
```python theme={null}
from chat_xdk import Chat
chat = Chat(juicebox_config_json) # or Chat() + import_keys(blob)
chat.unlock("YOUR_PASSCODE")
chat.set_key_version(signing_key_version)
result = chat.decrypt_events(raw_events, signing_keys)
for dm in result["messages"]:
ev = dm["event"]
if ev.get("type") == "Message":
print(ev.get("sender_id"), ev.get("content", {}).get("text"))
cached = result["conversation_keys"]["keys"]
event = chat.decrypt_event(one_event_b64, cached, sender_signing_keys)
raw_key = cached[result["conversation_keys"]["latest_version"]]
payload = chat.encrypt_message(
message_id, sender_id, conversation_id, raw_key, "Hi!",
conversation_key_version, signing_key_version,
)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: juiceboxConfigJson,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(signingKeyVersion);
const result = chat.decryptEvents(rawEvents, signingKeys);
for (const dm of result.messages) {
if (dm.event.type === 'message') {
console.log(dm.event.senderId, dm.event.content?.text);
}
}
const cached = result.conversationKeys.keys;
const event = chat.decryptEvent(oneEventB64, cached, senderSigningKeys);
const rawKey = cached[result.conversationKeys.latestVersion!];
const payload = chat.encryptMessage({
messageId, senderId, conversationId, conversationKey: rawKey, text: 'Hi!',
conversationKeyVersion, signingKeyVersion,
});
```
```rust theme={null}
// ChatCore + import_keys, or chat_xdk_core::Chat + unlock().await
let result = chat.decrypt_events(&raw_events, &signing_keys);
let cached = &result.conversation_keys.keys;
let event = chat.decrypt_event(one_event_b64, cached, &sender_signing_keys)?;
// cached values are XChatConversationKey; encrypt_message wants owned bytes
let latest = result.conversation_keys.latest_version.as_deref().unwrap_or_default();
let conv_key = cached[latest].to_bytes();
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id, &sender_id, &conversation_id, conv_key, "Hi!",
&conversation_key_version, &signing_key_version,
))?;
```
```go theme={null}
chat := chatxdk.New()
defer chat.Close()
blob, _ := chatxdk.Base64ToBytes(privateKeysB64)
_ = chat.ImportKeys(blob)
chat.SetKeyVersion(signingKeyVersion)
result, err := chat.DecryptEvents(rawEvents, signingKeys)
cached := result.ConversationKeys.Keys
event, err := chat.DecryptEvent(oneEventB64, cached, senderSigningKeys)
rawKey := cached[*result.ConversationKeys.LatestVersion]
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawKey, Text: "Hi!",
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
})
_ = event
_ = payload
_ = err
```
```csharp theme={null}
using var chat = new Chat();
chat.ImportKeys(privateKeyBytes);
chat.SetKeyVersion(signingKeyVersion);
var result = chat.DecryptEvents(rawEvents, signingKeys);
var cached = result.ConversationKeys.Keys;
var evt = chat.DecryptEvent(oneEventB64, cached, senderSigningKeys);
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId, SenderId = senderId, ConversationId = conversationId,
ConversationKey = rawKey, Text = "Hi!",
ConversationKeyVersion = conversationKeyVersion, SigningKeyVersion = signingKeyVersion,
});
```
```java theme={null}
try (Chat chat = new Chat()) {
chat.importKeys(privateKeyBytes);
chat.setKeyVersion(signingKeyVersion);
DecryptEventsResult result = chat.decryptEvents(rawEvents, signingKeys);
Map cached = result.conversationKeys.keys;
JsonNode event = chat.decryptEvent(oneEventB64, cached, senderSigningKeys);
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawKey;
params.text = "Hi!";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
}
```
***
## ライフサイクルと鍵
SDK を構築し、秘密鍵を保存し(パスコード保護された安全な鍵バックアップまたはローカル鍵 blob)、**公開**鍵を Chat API に登録し、アンロックまたはインポート後に登録済みの**公開鍵バージョン**を設定します。安全な鍵バックアップは **Juicebox** で実装されており、関連する設定フィールドがその名前を持つのはこのためです。デバイス/アプリ ID ごとに `generate_keypairs` を 1 回呼び出します;登録ペイロードを公開鍵エンドポイントに投稿します。すべてのバインディングで安全な鍵バックアップには `setup` / `unlock`(および関連するパスコードヘルパー)を使用します。`export_keys` / `import_keys`(ボットとサーバー用の未加工鍵 blob 永続化)は、**ネイティブバインディングのみ** — Python、Go、.NET、JVM、Rust — で利用できます。JS/WASM バインディングは未加工の鍵のエクスポートやインポートを公開しません: ブラウザではインスタンスに到達するスクリプトは identity を流出できるため、JS は鍵を安全な鍵バックアップ内に保持します。リクエストごとのバックアップ realm ラウンドトリップを避けたい JS サーバーは、リクエスト間で 1 つのアンロック済み `Chat` インスタンスを再利用するか、鍵 blob がサポートされているネイティブバインディングを実行するべきです。
```python theme={null}
from chat_xdk import Chat
# Secure key backup (client)
chat = Chat(juicebox_config_json)
chat.setup("YOUR_PASSCODE") # first time — generates keypairs
# chat.unlock("YOUR_PASSCODE") # later sessions
chat.set_key_version(version) # from add-public-key / get-public-keys response
reg = chat.get_public_keys() # or registration fields from generate_keypairs
# Key blob (server / bot)
chat2 = Chat()
chat2.import_keys(secret_blob)
chat2.set_key_version(version)
blob = chat2.export_keys() # treat as a password
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: juiceboxConfigJson,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.setup('YOUR_PASSCODE');
// await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(version);
const publics = chat.getPublicKeys();
// JS/WASM stores keys only through secure key backup — there is no raw key
// export/import here. For key-blob persistence, use a native binding.
```
```rust theme={null}
// chat_xdk_core::Chat — async secure key backup unlock, or ChatCore + import_keys
chat.setup("YOUR_PASSCODE").await?;
// chat.unlock("YOUR_PASSCODE").await?;
chat.set_key_version(&version);
let publics = chat.get_public_keys()?;
let blob = chat.export_keys()?;
chat.import_keys(&blob)?;
```
```go theme={null}
chat := chatxdk.New()
defer chat.Close()
// Prefer ImportKeys for servers; secure key backup unlock where supported
keyBlob, _ := chatxdk.Base64ToBytes(privateKeysB64)
if err := chat.ImportKeys(keyBlob); err != nil {
log.Fatal(err)
}
chat.SetKeyVersion(version)
publics, err := chat.GetPublicKeys()
blob, err := chat.ExportKeys()
_ = publics
_ = blob
_ = err
```
```csharp theme={null}
using var chat = new Chat();
chat.ImportKeys(privateKeyBytes);
// or secure key backup setup / unlock when config is available
chat.SetKeyVersion(version);
var publics = chat.GetPublicKeys();
var blob = chat.ExportKeys();
```
```java theme={null}
try (Chat chat = new Chat()) {
chat.importKeys(privateKeyBytes);
chat.setKeyVersion(version);
var publics = chat.getPublicKeys();
byte[] blob = chat.exportKeys();
}
```
安全な鍵バックアップ設定は 3 つの形を受け付けます: X API の `juicebox_config` オブジェクト(推奨 — そのまま渡す)、完全な `sdk_config` ラッパー、または裸の `token_map`。
オプション: 署名検証は**デフォルトで有効**(`reject_unverified = true`)— 無効にするには `set_reject_unverified(false)` を呼び出します(推奨されません);バックアップ realm 設定が変更された場合は `update_config`;UI 状態には `is_unlocked` / `has_identity_key`。完全なフィールドリストは [chat-xdk リポジトリ](https://github.com/xdevplatform/chat-xdk) のスタブにあります。
***
## 会話鍵
3 つの **prepare** メソッドは、それぞれ 1 回の呼び出しで鍵変更に必要なすべて(新しい会話鍵の生成、渡された公開鍵からすべての参加者向けに暗号化、変更への署名)を行います。すべて同じ **`PreparedConversationChange`** 形を返し、POST の準備が整います — SDK フィールドの `encrypted_key` を `conversation_participant_keys` の中で **`encrypted_conversation_key`** に名前を変え、アクション署名を必須の **`action_signatures`** ボディフィールドにマップしてください。
| シナリオ | メソッド | 返されるアクション署名 |
| :------------------------------------------------------------------ | :-------------------------------- | :---------- |
| 1:1 を開始(会話 ID を省略 — SDK が導出)または任意の会話の鍵をローテーション(ID を渡す) | `prepare_conversation_key_change` | 1 |
| グループの作成(`POST /2/chat/conversations/group/initialize` によって発行される ID) | `prepare_group_create` | 2 — 両方送信 |
| グループへのメンバー追加 | `prepare_group_members_change` | 2 — 両方送信 |
**未加工の**鍵バイトを `encrypt_message` およびメディア用に保持してください;API の暗号化エンベロープを encrypt に渡してはいけません。
**ラップする前に取得した鍵を検証してください。** prepare メソッドは、渡された任意の公開鍵に対して新しい会話鍵を暗号化します。渡す前に、各取得済みレコードに対して `verify_key_binding(identity, signing, signature)` を呼び出してください — public-keys API のレコードの `public_key`、`signing_public_key`、`identity_public_key_signature` フィールド — 置き換えられた identity 鍵が会話鍵を受け取れないようにするためです。
鍵変更イベントペイロードで `extract_conversation_keys` を使い、`{ keys, latest_version }` を再構築します。`decrypt_conversation_key` は単一の ECIES blob をアンラップします。
```python theme={null}
# One entry per participant public key, from the public-keys API:
# participants = [
# {"user_id": "1215441834412953600", "public_key": "BASE64_IDENTITY_PUBLIC_KEY", "key_version": "1733889755256"},
# {"user_id": "1843439638876491776", "public_key": "BASE64_IDENTITY_PUBLIC_KEY", "key_version": "1766181805686"},
# ]
prepared = chat.prepare_conversation_key_change(my_user_id, signing_key_version, participants)
# prepared["conversation_key"] — raw bytes for encrypt_message
# prepared["participant_keys"] — per-user wraps; rename encrypted_key → encrypted_conversation_key on POST
# prepared["action_signatures"] — required on the POST body
extracted = chat.extract_conversation_keys(key_change_blobs)
keys = extracted["keys"]
latest = extracted["latest_version"]
raw = keys[latest]
one = chat.decrypt_conversation_key(encrypted_blob)
```
```typescript theme={null}
const prepared = chat.prepareConversationKeyChange({
senderId: myUserId, signingKeyVersion, publicKeys: participants,
});
// prepared.conversationKey — Uint8Array for encryptMessage
// prepared.participantKeys / prepared.actionSignatures — POST body fields
const extracted = chat.extractConversationKeys(keyChangeBlobs);
const raw = extracted.keys[extracted.latestVersion!];
const one = chat.decryptConversationKey(encryptedBlob);
```
```rust theme={null}
let prepared = chat.prepare_conversation_key_change(
ConversationKeyChangeParams::new(&my_user_id, &signing_key_version, participants),
)?;
let extracted = chat.extract_conversation_keys(&key_change_blobs);
let latest = extracted.latest_version.as_deref().unwrap_or_default();
let raw = &extracted.keys[latest];
let one = chat.decrypt_conversation_key(&encrypted_blob)?;
```
```go theme={null}
prepared, err := chat.PrepareConversationKeyChange(chatxdk.ConversationKeyChangeParams{
SenderID: myUserID, SigningKeyVersion: signingKeyVersion, PublicKeys: participants,
})
// prepared.ConversationKey feeds EncryptMessage
// prepared.ParticipantKeys / prepared.ActionSignatures — POST body fields
extracted, err := chat.ExtractConversationKeys(keyChangeBlobs)
one, err := chat.DecryptConversationKey(encryptedBlob)
_ = prepared
_ = extracted
_ = one
_ = err
```
```csharp theme={null}
var prepared = chat.PrepareConversationKeyChange(new ConversationKeyChangeParams {
SenderId = myUserId, SigningKeyVersion = signingKeyVersion, PublicKeys = participants,
});
var extracted = chat.ExtractConversationKeys(keyChangeBlobs);
var raw = extracted.Keys[extracted.LatestVersion];
var one = chat.DecryptConversationKey(encryptedBlob);
```
```java theme={null}
ConversationKeyChangeParams keyParams = new ConversationKeyChangeParams();
keyParams.senderId = myUserId;
keyParams.signingKeyVersion = signingKeyVersion;
keyParams.publicKeys = participants;
PreparedConversationChange prepared = chat.prepareConversationKeyChange(keyParams);
ConversationKeyBundle extracted = chat.extractConversationKeys(keyChangeBlobs);
byte[] raw = extracted.keys.get(extracted.latestVersion);
byte[] one = chat.decryptConversationKey(encryptedBlob);
```
グループの作成とメンバー追加については、各メソッドが必要とするパラメータを渡します(`prepare_group_create` にはメンバー/管理者 ID リスト;`prepare_group_members_change` には新規プラス現在のロスター) — サンプルは [Groups](/xchat/groups#create-the-group-and-establish-keys) を参照してください。両方とも**2 つ**のアクション署名を返します;POST には両方含める必要があります。
***
## 復号
**`decrypt_events`** は履歴とバックログ用です: ストリームから会話鍵を取り出し、復号済みメッセージを返し、バッチ全体を失敗させる代わりにイベントごとのエラーを**収集**します。**`decrypt_event`** は、鍵キャッシュをすでに持っている場合の単一のライブイベント用です。失敗時に raise/throw します。
送信者を SDK が検証できるように**署名鍵**を渡します。API の公開鍵フィールドを `SigningKeyEntry` にマップします: `public_key_version` → `public_key_version`(同じ名前)、`signing_public_key` → `public_key`、`public_key` → `identity_public_key`、加えて `identity_public_key_signature` と `user_id`。検証はデフォルトで必須です: 空の署名鍵リストを省略または渡してもスキップされ**ません** — 署名付きイベントは失敗します(`decrypt_events` では `errors` に収集され、`decrypt_event` ではスローされます)。実際に検証をスキップするには、まず `set_reject_unverified(false)` を呼び出す必要があります(本番環境では推奨されません)。
```python theme={null}
signing_keys = [{
"user_id": uid,
"public_key_version": row["public_key_version"],
"public_key": row["signing_public_key"],
"identity_public_key": row["public_key"],
"identity_public_key_signature": row["identity_public_key_signature"],
} for row in api_public_keys]
result = chat.decrypt_events(raw_events, signing_keys)
for idx, msg in (result.get("errors") or {}).items():
log.warning("event %s failed: %s", idx, msg)
for dm in result["messages"]:
ev = dm["event"]
if ev.get("type") == "Message":
text = ev.get("content", {}).get("text")
cached = result["conversation_keys"]["keys"]
live = chat.decrypt_event(one_event_b64, cached, signing_keys_for_sender)
```
```typescript theme={null}
const signingKeys = apiPublicKeys.map((row) => ({
userId: uid,
publicKeyVersion: row.public_key_version,
publicKey: row.signing_public_key,
identityPublicKey: row.public_key,
identityPublicKeySignature: row.identity_public_key_signature,
}));
const result = chat.decryptEvents(rawEvents, signingKeys);
for (const [idx, msg] of Object.entries(result.errors ?? {})) {
console.warn(`event ${idx} failed: ${msg}`);
}
const cached = result.conversationKeys.keys;
const live = chat.decryptEvent(oneEventB64, cached, signingKeysForSender);
```
```rust theme={null}
let result = chat.decrypt_events(&raw_events, &signing_keys);
for (idx, msg) in &result.errors {
eprintln!("event {idx} failed: {msg}");
}
let cached = &result.conversation_keys.keys;
let live = chat.decrypt_event(one_event_b64, cached, &signing_keys_for_sender)?;
```
```go theme={null}
result, err := chat.DecryptEvents(rawEvents, signingKeys)
for idx, msg := range result.Errors {
log.Printf("event %s failed: %s", idx, msg)
}
cached := result.ConversationKeys.Keys
live, err := chat.DecryptEvent(oneEventB64, cached, signingKeysForSender)
_ = live
_ = err
```
```csharp theme={null}
var result = chat.DecryptEvents(rawEvents, signingKeys);
foreach (var kv in result.Errors) { /* kv.Key = event index, kv.Value = error */ }
var cached = result.ConversationKeys.Keys;
var live = chat.DecryptEvent(oneEventB64, cached, signingKeysForSender);
```
```java theme={null}
DecryptEventsResult result = chat.decryptEvents(rawEvents, signingKeys);
Map cached = result.conversationKeys.keys;
JsonNode live = chat.decryptEvent(oneEventB64, cached, signingKeysForSender);
```
***
## 暗号化と送信ヘルパー
**`encrypt_message`** は、テキストメッセージ用の署名済み暗号文を構築します(オプションの entities、`media_hash_key` 経由の attachments、TTL、通知フラグ)。返されたペイロードを送信メッセージボディにマップします: `encrypted_content` → **`encoded_message_create_event`**、`encoded_event_signature` → **`encoded_message_event_signature`**、および **`message_id`**。
返信とリアクション(`sequence_id` は親をターゲットにします)には、**`encrypt_reply`**、**`encrypt_add_reaction`**、および **`encrypt_remove_reaction`** を使用します。**`encrypt` / `decrypt`** は、会話鍵の下での UTF-8 メタデータ(たとえば暗号化されたグループ名)用です — メッセージエンベロープ用ではありません。**`encrypt_stream` / `decrypt_stream`** は添付バイトを暗号化します;[Media](/xchat/media) を参照してください。低レベルの **`sign` / `verify` / `verify_key_binding`** は高度なフローをサポートします;会話鍵の変更、グループの作成、およびメンバーの追加は [prepare メソッド](#conversation-keys) によって署名されます。
`encrypt_message` / `encrypt_reply` に渡す会話 ID は、保持している任意の形式で構いません — イベントからの `A:B`、リストや URL パスからの `A-B`(どちらの順序でも)、または受信者のユーザー ID だけ — SDK は署名する前に正規化します。グループ ID(`g` プレフィックス付き)はそのまま渡されます。
```python theme={null}
payload = chat.encrypt_message(
message_id, sender_id, conversation_id, raw_conversation_key, "Hello",
conversation_key_version, signing_key_version,
# Optional keyword args: entities, attachments, should_notify, ttl_msec
)
body = {
"message_id": message_id,
"encoded_message_create_event": payload["encrypted_content"],
"encoded_message_event_signature": payload["encoded_event_signature"],
}
# POST body to /2/chat/conversations/{id}/messages
reply = chat.encrypt_reply(
reply_message_id, sender_id, conversation_id, raw_conversation_key,
"Sounds good", conversation_key_version, signing_key_version,
parent_sequence_id, # reply_to_sequence_id — the message being replied to
)
name_ct = chat.encrypt("Group title", raw_conversation_key)
title = chat.decrypt(name_ct, raw_conversation_key)
```
```typescript theme={null}
const payload = chat.encryptMessage({
messageId, senderId, conversationId, conversationKey: rawConversationKey, text: 'Hello',
conversationKeyVersion, signingKeyVersion,
});
const body = {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
};
const reply = chat.encryptReply({
messageId: replyMessageId, senderId, conversationId, conversationKey: rawConversationKey,
text: 'Sounds good', conversationKeyVersion, signingKeyVersion,
replyToSequenceId: parentSequenceId, // the message being replied to
});
const nameCt = chat.encrypt('Group title', rawConversationKey);
const title = chat.decrypt(nameCt, rawConversationKey);
```
```rust theme={null}
// conv_key: XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id, &sender_id, &conversation_id, conv_key.to_bytes(), "Hello",
&conversation_key_version, &signing_key_version,
))?;
// Map payload fields into the send-message JSON body as above
let name_ct = chat.encrypt("Group title", &conv_key)?;
let title = chat.decrypt(&name_ct, &conv_key)?;
```
```go theme={null}
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawKey, Text: "Hello",
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
})
// body: message_id, encoded_message_create_event, encoded_message_event_signature
nameCt, err := chat.Encrypt("Group title", rawKey)
title, err := chat.Decrypt(nameCt, rawKey)
_ = payload
_ = title
_ = err
```
```csharp theme={null}
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId, SenderId = senderId, ConversationId = conversationId,
ConversationKey = rawKey, Text = "Hello",
ConversationKeyVersion = conversationKeyVersion, SigningKeyVersion = signingKeyVersion,
});
// Map EncryptedContent / EncodedEventSignature into the send-message body
var nameCt = chat.Encrypt("Group title", rawKey);
var title = chat.Decrypt(nameCt, rawKey);
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawKey;
params.text = "Hello";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
// Map to encoded_message_create_event / encoded_message_event_signature on POST
String nameCt = chat.encrypt("Group title", rawKey);
String title = chat.decrypt(nameCt, rawKey);
```
***
## メディアストリーム
テキストに使用されたものと**同じ**会話鍵でファイルバイトを暗号化し、Chat メディア API 経由でアップロードし、`encrypt_message` で **`media_hash_key`** を添付します。これは Posts メディアモデル(`expansions=attachments.media_keys`)ではありません。完全なアップロード/ダウンロードフロー: [Media](/xchat/media)。
```python theme={null}
ciphertext = chat.encrypt_stream(file_bytes, raw_conversation_key)
# Upload `ciphertext`; the `media_hash_key` you attach on encrypt_message
# comes from the media-upload finalize step, not from encrypt_stream.
plain = chat.decrypt_stream(ciphertext, raw_conversation_key)
```
```typescript theme={null}
const ciphertext = chat.encryptStream(fileBytes, rawConversationKey);
// Upload `ciphertext`; mediaHashKey comes from the upload finalize step.
const plain = chat.decryptStream(ciphertext, rawConversationKey);
```
```rust theme={null}
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let ciphertext = chat.encrypt_stream(&file_bytes, &conv_key)?;
let plain = chat.decrypt_stream(&ciphertext, &conv_key)?;
```
```go theme={null}
ciphertext, err := chat.EncryptStream(fileBytes, rawKey)
plain, err := chat.DecryptStream(ciphertext, rawKey)
_ = plain
_ = err
```
```csharp theme={null}
var ciphertext = chat.EncryptStream(fileBytes, rawKey);
var plain = chat.DecryptStream(ciphertext, rawKey);
```
```java theme={null}
byte[] ciphertext = chat.encryptStream(fileBytes, rawKey);
byte[] plain = chat.decryptStream(ciphertext, rawKey);
```
### 大きなメディア向けのインクリメンタルストリーミング
大きなファイルの場合、ペイロード全体をメモリに保持しないでください: `stream_encryptor()` / `stream_decryptor()` は、`StreamEncryptor` / `StreamDecryptor` を返します。`push(chunk)` でチャンク(約 1 MB ずつ)を供給し、最後に `finish()` を 1 回呼び出します。復号では、`finish()` は切り詰められたストリームを検出します(最終フレームより前に入力が終わった場合は失敗します)ので、成功するまでプッシュされた平文を完全なものとして扱わないでください。
**JS/WASM のみ:** `finish()` は基になる WASM オブジェクトを消費して解放します — `finish()` の後には決して `free()` を呼び出さないでください(例外がスローされます)。`free()` は、finish の**前に**ストリームを放棄する場合(たとえばエラーパス)にのみ呼び出してください。
```python theme={null}
enc = chat.stream_encryptor(raw_conversation_key)
chunks = [enc.push(chunk) for chunk in read_in_chunks(file_bytes, 1 << 20)]
chunks.append(enc.finish())
ciphertext = b"".join(chunks)
dec = chat.stream_decryptor(raw_conversation_key)
out = [dec.push(chunk) for chunk in read_in_chunks(ciphertext, 1 << 20)]
out.append(dec.finish()) # raises on truncation
plain = b"".join(out)
```
```typescript theme={null}
const enc = chat.streamEncryptor(rawConversationKey);
const parts: Uint8Array[] = [];
try {
for (const chunk of readInChunks(fileBytes, 1 << 20)) parts.push(enc.push(chunk));
parts.push(enc.finish()); // consumes + frees enc — do not call enc.free() after this
} catch (e) {
enc.free(); // only when abandoning before finish()
throw e;
}
const ciphertext = concat(parts);
```
***
## ユーティリティ
Base64/hex ヘルパー、MIME スニッフィング、および画像寸法は、モジュールレベルの関数(Python/JS/Rust/Go)または `ChatXdkUtilities`(C#/Java)として利用できます — 追加のライブラリを取り込まずに添付メタデータを構築するときに便利です。
```python theme={null}
from chat_xdk import (
bytes_to_base64, base64_to_bytes, bytes_to_hex, hex_to_bytes,
detect_mime_type, detect_image_dimensions,
)
b64 = bytes_to_base64(raw)
raw2 = base64_to_bytes(b64)
hexed = bytes_to_hex(raw)
raw3 = hex_to_bytes(hexed)
mime = detect_mime_type(file_bytes)
w, h = detect_image_dimensions(file_bytes)
```
```typescript theme={null}
import { bytesToBase64, base64ToBytes, bytesToHex, hexToBytes, detectMimeType, detectImageDimensions } from '@xdevplatform/chat-xdk';
const b64 = bytesToBase64(raw);
const raw2 = base64ToBytes(b64);
const hexed = bytesToHex(raw);
const raw3 = hexToBytes(hexed);
const mime = detectMimeType(fileBytes);
const dims = detectImageDimensions(fileBytes);
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;
```
```rust theme={null}
let b64 = chat_xdk_core::bytes_to_base64(&raw);
let raw2 = chat_xdk_core::base64_to_bytes(&b64)?;
let hexed = chat_xdk_core::bytes_to_hex(&raw);
let raw3 = chat_xdk_core::hex_to_bytes(&hexed);
let mime = chat_xdk_core::detect_mime_type(&file_bytes);
let dims = chat_xdk_core::detect_image_dimensions(&file_bytes);
let (w, h) = dims.map(|d| (d.width, d.height)).unwrap_or((0, 0));
```
```go theme={null}
b64, _ := chatxdk.BytesToBase64(raw)
raw2, err := chatxdk.Base64ToBytes(b64)
hexed, err := chatxdk.BytesToHex(raw)
raw3, err := chatxdk.HexToBytes(hexed)
mime, _ := chatxdk.DetectMimeType(fileBytes)
dims, _ := chatxdk.DetectImageDimensions(fileBytes)
w, h := dims.Width, dims.Height
_ = b64
_ = raw2
_ = hexed
_ = raw3
_ = mime
_ = w
_ = h
_ = err
```
```csharp theme={null}
var b64 = ChatXdkUtilities.BytesToBase64(raw);
var raw2 = ChatXdkUtilities.Base64ToBytes(b64);
var hexed = ChatXdkUtilities.BytesToHex(raw);
var raw3 = ChatXdkUtilities.HexToBytes(hexed);
var mime = ChatXdkUtilities.DetectMimeType(fileBytes);
var dims = ChatXdkUtilities.DetectImageDimensions(fileBytes);
var w = dims?.Width ?? 0;
var h = dims?.Height ?? 0;
```
```java theme={null}
String b64 = ChatXdkUtilities.bytesToBase64(raw);
byte[] raw2 = ChatXdkUtilities.base64ToBytes(b64);
String hexed = ChatXdkUtilities.bytesToHex(raw);
byte[] raw3 = ChatXdkUtilities.hexToBytes(hexed);
String mime = ChatXdkUtilities.detectMimeType(fileBytes);
ImageDimensions wh = ChatXdkUtilities.detectImageDimensions(fileBytes);
long width = wh.width, height = wh.height;
```
***
## 重要な型
これらの概念的な型は、複数の言語にわたって現れます(正確なフィールド名は異なります;JS では `message` のように camelCase のイベント識別子を使うことが多いです):
* **SendPayload** — `encrypt_message` および関連する暗号化ヘルパーの戻り値;Chat API 送信ボディにマップします。
* **PublicKeyRegistrationPayload** — add-public-key API 用の `generate_keypairs` / 公開鍵ゲッターの出力。
* **SigningKeyEntry** — 署名検証のために decrypt に渡される送信者の公開素材。
* **PreparedConversationChange** — 3 つの prepare メソッドの出力: 導出されたまたは渡された `conversation_id`、未加工の `conversation_key` バイト、`conversation_key_version`、`participant_keys`(`user_id`、`encrypted_key`、`public_key_version`)、および `action_signatures`(`message_id`、`encoded_message_event_detail`、`signature`、`signature_version`、`public_key_version`、オプションの `signature_payload` — そのペイロードが平文の鍵を埋め込むため鍵変更署名では省略されます)。
* **DecryptEventsResult** — メッセージ、オプションのエラー、抽出された `conversation_keys`。
完全なフィールドリストについては、[chat-xdk リポジトリ](https://github.com/xdevplatform/chat-xdk) の言語スタブ(`docs/API.md`、`*.pyi`、`index.d.ts`)を使用してください。
***
## エラー
Python は通常、記述的なメッセージ(たとえば無効なパスコード)で **`ValueError`** を発生させます。TypeScript/JavaScript は **`Error`** をスローします。Go は `(value, error)` を返します。履歴には **`decrypt_events`** を優先してください、そうすれば 1 つの不良イベントがバッチを中止しません;部分的な失敗については errors コレクションを検査してください。
一部の検証エラーは**恒久的**です。署名は不変であり、イベント自体から署名済みペイロードを再構築することで検証されるため、`signature missing or no matching signing key` または ECDSA の不一致で失敗する古いイベントは、将来のすべてのロードで失敗します — 再試行、鍵の更新、または API 呼び出しでは治せません。これらは一時的なエラーではなく、トゥームストーンとして扱ってください。会話鍵をローテーションすると、その時点からクリーンで検証可能な履歴が始まります。
***
## 次のステップ
Chat XDK を Chat API に接続する
ストリーム暗号化とメディア REST
Webhook とアクティビティ配信
よくある失敗
# 변경 로그
Source: https://docs.x.com/ko/changelog
X API v2, Enterprise API, Ads API, SDK, 스트리밍, 웹훅 및 개발자 플랫폼에 대한 릴리스 노트와 버전 기록. 신규 기능, 엔드포인트 변경, 지원 중단, 마이그레이션 가이드, 요청 한도 업데이트를 한곳에서 확인할 수 있습니다.
업데이트를 구독하려면 [**@API**](https://x.com/api)의 [**"알림 켜기"**](https://help.x.com/en/managing-your-account/notifications-on-mobile-devices#:~:text=In%20the%20top%20menu,%20you,you%20would%20like%20to%20receive)를 활성화하세요. 또한 [**RSS 피드**](https://docs.x.com/changelog/rss.xml)를 통해 피드 리더에서 이 변경 로그를 구독할 수도 있습니다.
### Articles 초안 작성 및 게시 엔드포인트
오늘, X API를 통해 Articles의 초안을 작성하고 게시할 수 있는 [새로운 엔드포인트](/x-api/articles/introduction)를 추가했습니다.
### X Activity API의 Post 생성 및 삭제 이벤트
오늘 [X Activity API](https://docs.x.com/x-api/activity/introduction)에 `post.create`와 `post.delete` 이벤트를 추가했습니다. 이제 사용자 ID로 구독하여 사용자가 Post를 생성하거나 삭제할 때 실시간 알림을 받을 수 있습니다.
사용자별 기본 Post 활동에는 XAA를 사용하세요. 고급 키워드 필터링과 Filtered Stream의 전체 연산자 집합이 필요하다면 계속해서 [Filtered Stream](/x-api/posts/filtered-stream/introduction)을 사용하세요.
### Post의 `paid_partnership` 필드
Post에 `paid_partnership` 필드 지원이 추가되었습니다.
* `POST /2/tweets`로 Post를 생성할 때 `"paid_partnership": true`로 설정하면 해당 Post가 유료 파트너십(즉, 작성자가 유료 프로모션을 포함하고 있음을 공개)임을 나타냅니다. 해당 Post에는 유료 프로모션 라벨이 표시됩니다.
* Post를 읽을 때 `tweet.fields=paid_partnership`을 요청하면 값을 가져올 수 있습니다(작성자가 해당 Post를 유료 프로모션을 포함한다고 공개한 경우 `true`).
### 검색 엔드포인트를 새 검색 인덱스로 마이그레이션
오늘 X API v2 검색 엔드포인트(`/2/tweets/search/recent`, `/2/tweets/search/all`, `/2/tweets/counts/recent`, `/2/tweets/counts/all`)를 새로운 X 코어 플랫폼 검색 인덱스로 마이그레이션했습니다. 이를 통해 성능이 크게 향상되고 503 오류가 대폭 감소하며 세 가지 새로운 정밀도 연산자(`min\_likes:`, `min\_replies:`, `min\_reposts:`)가 도입됩니다. 참고: 리포스트는 더 이상 키워드 기반 검색 결과에 반환되지 않습니다(Filtered Stream은 변경되지 않음). 자세한 내용은 [여기](https://devcommunity.x.com/t/important-update-x-api-search-endpoints-migrating-to-new-search-index/264595)를 참조하세요.
### X API 가격 업데이트: Owned Reads가 이제 \$0.001
2026년 4월 20일부로 본인의 데이터에 접근하는 대상 엔드포인트(`GET /2/users/{id}/bookmarks`, `/blocking`, `/muting`, `/pinned_lists`, `/tweets`, `/mentions`, `/liked_tweets`, `/followers`, `/following`, `/owned_lists`, `/followed_lists`, `/list_memberships`)에 대해 새로운 "Owned Reads" 가격인 \*\*리소스당 $0.001**(1,000건당 $1)을 도입했습니다. 쓰기 작업도 업데이트되어 `POST /2/tweets`는 포스트당 $0.015이며 URL이 포함된 포스트는 포스트당 $0.20입니다(소환된 답글은 그대로 \$0.01 유지). API를 통한 팔로우, 좋아요, 인용 포스트는 모든 셀프 서비스 등급에서 제거되었습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/x-api-pricing-update-owned-reads-now-0-001-other-changes-effective-april-20-2026/263025)를 참조하세요.
### Account Activity Replay 엔드포인트 지원 중단
오늘 `POST /2/account_activity/replay/webhooks/{webhook_id}/subscriptions/all`의 지원 중단을 발표했으며, 2026년 3월 25일 오후 12:00 ET부로 적용됩니다. 대신 새로운 통합 엔드포인트인 `POST /2/webhooks/replay`를 사용하세요. 동일한 기능을 제공합니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/deprecation-of-account-activity-replay-endpoint/260354)를 참조하세요.
### X Activity API 구독을 위한 Direction 필터
오늘 X Activity API 구독에 선택적 `direction` 필터를 추가했습니다. 구독자는 이제 DM 및 채팅 이벤트를 `sent`, `received` 또는 둘 다로 범위 지정할 수 있으므로 송신 또는 수신 이벤트만 필요한 경우 노이즈를 줄일 수 있습니다.
### X Activity API의 이벤트 유형 형식 업데이트
오늘 2026년 3월 18일부터 적용되는 X Activity API의 이벤트 유형 명명 규칙 변경을 발표했습니다. PascalCase 이벤트 유형(예: `ProfileBioUpdate`)은 점으로 구분된 소문자 형식(예: `profile.update.bio`)으로 대체됩니다. 이전 값에 의존하는 필터링, switch 문 또는 역직렬화 로직을 업데이트하세요. 자세한 내용은 [여기](https://devcommunity.x.com/t/updates-to-event-types-format-in-the-x-activity-api/259765)를 참조하세요.
### X Activity API의 레거시 다이렉트 메시지 이벤트
오늘 레거시 DM 이벤트(`dm.received`, `dm.sent`, `dm.read`, `dm.indicate_typing`)를 [X Activity API](https://docs.x.com/x-api/activity/introduction)에 추가했습니다. 이를 통해 DM 이벤트 전달이 Account Activity API에서 지연 시간이 더 짧은 XAA 파이프라인으로 이전됩니다.
### LLM 생성 스팸 대응
오늘 X 상의 자동화된 저품질 답글을 줄이기 위한 변경 사항을 적용했습니다. `POST /2/tweets`를 통한 프로그래밍 방식의 답글은 원본 포스트 작성자가 답글 작성자를 "소환"한 경우(해당 계정을 @멘션하거나 그 계정의 포스트 중 하나를 인용)에만 허용됩니다. 사용자를 프로그래밍 방식으로 @멘션하거나 인용하는 데에도 추가 제한이 적용됩니다. 이러한 변경 사항은 셀프 서비스 등급에만 영향을 미치며 Enterprise 액세스에는 영향을 미치지 않습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/x-api-v2-update-addressing-llm-generated-spam/257909)를 참조하세요.
### X API 사용량 기반(Pay-Per-Use) 가격 정식 출시
오늘 **X API Pay-Per-Use** 가격 모델을 공식적으로 출시했습니다. 인디 개발자, 스타트업 및 취미 개발자를 위해 설계된 유연한 크레딧 기반 모델입니다. 주요 내용:
* [console.x.com](https://console.x.com)의 새로운 Developer Console
* 퍼스트 파티 Python 및 TypeScript SDK가 포함된 [XDK (X Developer Kit)](https://docs.x.com/xdks/overview)
* 테스트를 위한 대화형 [Playground](https://github.com/xdevplatform/playground)
* AI 모델용 [MCP 서버](https://github.com/xdevplatform/xmcp)
* X API에 사용한 1달러당 최대 **20%를 xAI/Grok API 크레딧으로 적립**
Public Utility Apps는 계속해서 무료 확장 액세스를 받습니다. 최근 활성 상태였던 Legacy Free 등급 사용자는 일회성 \$10 바우처를 받습니다. Basic 및 Pro 플랜은 계속 제공되며 기존 구독자는 Pay-Per-Use로 전환할 수 있습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-launch-of-x-api-pay-per-use-pricing/256476)를 참조하세요.
### X Activity API의 Spaces 이벤트
오늘 Spaces 라이프사이클 이벤트(`spaces.start`, `spaces.end`)를 [X Activity API](https://docs.x.com/x-api/activity/introduction)에 추가했습니다. 사용자 ID로 구독하면 Space가 시작되거나 종료될 때 실시간으로 알림을 받을 수 있습니다.
### 개수 기반 연산자 지원 중단
오늘 `/2/tweets/search/recent` 및 `/2/tweets/search/all`에서 `min\_likes`, `min\_replies`, `min\_reposts` 연산자의 지원을 중단했습니다. 이 변경 사항은 Filtered Stream의 동일한 연산자에는 영향을 미치지 않습니다. 향후 이러한 연산자를 최선의 형태로 다시 활성화할 방법을 검토하고 있습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/deprecating-count-based-operators-in-the-x-api/254933)를 참조하세요.
### Account Activity API v2에 OAuth 2.0 지원 추가
오늘 [Account Activity API v2](https://docs.x.com/x-api/account-activity/introduction)에 OAuth 2.0을 완전히 지원하도록 추가했습니다. 이제 개발자는 OAuth 1.0a의 전부 아니면 전무(all-or-nothing) 권한 모델 대신, 세분화된 스코프(예: `follow.read`)를 사용하여 OAuth 2.0으로 구독을 생성할 수 있습니다. 기존 OAuth 1.0a 기반 통합은 중단 없이 계속 작동합니다. OAuth 1.0a 권한이 있는 경우 OAuth 2.0 스코프를 완전히 재정의합니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcement-oauth2-0-support-added-to-account-activity-api-v2/254633)를 참조하세요.
### X API Playground 출시
오늘 [X API Playground](https://github.com/xdevplatform/playground)를 소개했습니다. X API v2 엔드포인트를 에뮬레이트하는 셀프 호스팅 로컬 서버입니다. 실제 API 호출을 수행하거나 속도 제한에 도달하지 않고 통합을 개발하고 테스트하세요. 현실적인 모의 데이터, 상태 영속화, OpenAPI 검증, 속도 제한 시뮬레이션 및 웹 UI를 포함합니다. `go install github.com/xdevplatform/playground/cmd/playground@latest`로 설치하세요. 자세한 내용은 [여기](https://devcommunity.x.com/t/introducing-x-api-playground-local-development-tool-for-x-api-v2/253442)를 참조하세요.
### News 엔드포인트 출시
오늘 X API v2에 새로운 [News 엔드포인트](https://docs.x.com/x-api/news/introduction)를 출시했습니다:
* `GET /2/news/search` — 검색 쿼리와 일치하는 트렌딩 뉴스 기사를 반환합니다
* `GET /2/news/{id}` — ID로 특정 뉴스 기사를 조회합니다
두 엔드포인트 모두 `name`, `summary`, `contexts`, `cluster\_posts\_results`, `last\_updated\_at\_ms`와 같은 필드를 선택할 수 있는 `news.fields`를 지원합니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-news-endpoints-in-the-x-api-v2/251833)를 참조하세요.
### Python 및 TypeScript XDK 출시
오늘 X API v2를 위한 공식 퍼스트 파티 [Python](https://docs.x.com/xdks/python/overview) 및 [TypeScript](https://docs.x.com/xdks/typescript/overview) XDK(X Developer Kit)를 출시했습니다. XDK는 인증(Bearer Token, OAuth 2.0 PKCE, OAuth 1.0a), 자동 페이지네이션, 재연결 처리가 포함된 실시간 스트리밍 및 모든 v2 엔드포인트에 대한 포괄적인 커버리지를 처리합니다. `pip install xdk` 또는 `npm install @xdevplatform/xdk`로 설치하세요. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-python-and-typescript-xdks-for-the-x-api-v2/250860)를 참조하세요.
### X Activity API 구독을 위한 키워드 필터링
오늘 X Activity API 구독에 키워드 필터링을 추가했습니다. 사용자 ID 필터링 외에 이제 구독자는 키워드로 이벤트 전달을 더 세밀하게 좁힐 수 있습니다. News 이벤트와 같이 이벤트 볼륨이 높아 추가 필터링이 필요한 다른 이벤트 유형에 유용합니다.
### X Activity API의 인증 배지, 제휴 배지 및 핸들 업데이트 이벤트
오늘 [X Activity API](https://docs.x.com/x-api/activity/introduction)를 확장하여 추가 프로필 관련 이벤트 유형을 전달합니다:
* `profile.update.verified` — 사용자의 인증 상태가 변경될 때
* `profile.update.affiliate` — 사용자의 제휴 배지가 변경될 때
* `profile.update.screenname` — 사용자가 @핸들을 변경할 때
### X API Pay-Per-Use 가격 파일럿
오늘 새로운 크레딧 기반의 사용량 기반 가격 모델에 대한 제한된 비공개 파일럿을 발표했습니다. 개발자는 크레딧을 선구매하고 요청별로 청구됩니다. 고정 구독 요금이나 월별 객체 한도가 없습니다. 초기 파일럿 요금: Post Read $0.005, User Read $0.01, DM Event Read $0.01, Content Create $0.01, DM Interaction $0.01, User Interaction $0.015. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-x-api-pay-per-use-pricing-pilot/250253)를 참조하세요.
### X Activity API 오픈 베타 출시
오늘 [X Activity API](https://docs.x.com/x-api/activity/introduction)의 오픈 베타를 출시했습니다. 이는 1초 미만의 지연 시간으로 X의 실시간 활동 이벤트를 구독할 수 있는 새로운 엔드포인트 모음입니다. 프로필 이벤트 유형(`ProfileBioUpdate`, `ProfilePictureUpdate`, `ProfileBannerUpdate`, `ProfileGeoUpdate`, `ProfileUrlUpdate`)을 구독하고 사용자 ID로 필터링하여 영구 HTTP 스트림(`GET /2/activity/stream`) 또는 웹훅을 통해 일치하는 이벤트를 받습니다. 구독은 `POST /2/activity/subscriptions`를 통해 관리됩니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-x-activity-api-open-beta/250099)를 참조하세요.
### X API를 통한 포스트 편집
오늘 X API를 통해 최근 포스트를 프로그래밍 방식으로 편집하는 기능을 출시했습니다. 기존 `POST /2/posts` 엔드포인트를 `previous_post_id`가 포함된 새로운 `edit_options` 객체와 함께 사용하세요. 요구 사항: 인증된 사용자가 X Premium에 가입되어 있어야 하고, 포스트가 본인의 것이어야 하며, 최근 1시간 이내에 작성되어야 합니다. 업데이트된 [Create or Edit Post](https://docs.x.com/x-api/posts/create-post) 문서를 참조하세요. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-post-editing-via-the-x-api/249534)를 참조하세요.
### 활성 스트리밍 연결 관리를 위한 Connections API
오늘 활성 스트리밍 연결을 프로그래밍 방식으로 관리하기 위한 [Connections API](https://docs.x.com/x-api/connections/introduction)를 출시했습니다:
* `GET /2/connections` — 활성 및 과거 스트리밍 연결을 나열합니다
* `DELETE /2/connections/all` — 앱의 모든 활성 스트리밍 연결을 종료합니다
* `DELETE /2/connections/{endpoint_id}` — 특정 스트리밍 엔드포인트의 연결을 종료합니다
* `DELETE /2/connections` — UUID로 특정 연결을 종료합니다
이를 통해 개발자는 "TooManyConnections" 오류를 해결하고 타임아웃을 기다리지 않고도 오래된 연결을 정리할 수 있습니다.
### Community Notes: Evaluate Note 엔드포인트
오늘 [Community Notes API](https://docs.x.com/x-api/community-notes/introduction)에 `POST /2/evaluate_note` 엔드포인트를 추가했습니다. 이제 AI Note Writer는 제출 전에 작성된 노트를 평가하여 잠재적인 유용성, 주장/의견 정렬 및 기타 모델 피드백에 대한 신호를 받을 수 있습니다.
### Filtered Stream Webhooks API 출시
오늘 [Filtered Stream Webhooks API](https://docs.x.com/x-api/webhooks/stream/introduction)를 출시했습니다. 영구 연결을 필요로 하는 대신 일치하는 공개 포스트를 등록된 웹훅에 비동기적으로 전달합니다. 규칙은 기존 `/2/tweets/search/stream/rules` 엔드포인트를 사용해 관리되며, 일치하는 포스트(편집 이력 포함)는 JSON 형태로 웹훅에 전달됩니다. Enterprise 개발자에게 제공되며, 프로젝트당 25,000개 이상의 규칙과 규칙당 최대 2,048자를 지원합니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-filtered-stream-webhooks-api/248464)를 참조하세요.
### Free 등급에서 Like 및 Follow 엔드포인트 제거
악용, 플랫폼 조작 및 가짜 참여를 방지하기 위해 `POST /2/users/:id/likes` 및 `POST /2/users/:id/following`을 X API Free 등급에서 즉시 제거했습니다. 유료 등급(Basic, Pro, Enterprise)은 영향을 받지 않습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/update-to-x-api-free-tier-removal-of-like-and-follow-endpoints/247646)를 참조하세요.
### PowerStream Rules Lookup 엔드포인트
오늘 `GET /2/powerstream/rules` 엔드포인트를 추가하여 PowerStream 고객이 PowerStream 인스턴스에 구성된 규칙을 프로그래밍 방식으로 조회할 수 있도록 했습니다.
### `share_with_followers`를 통한 Community 포스트 브로드캐스트
오늘 `POST /2/tweets`에 새로운 선택적 부울 매개변수 `share_with_followers`를 추가했습니다. `community_id`와 `share_with_followers: true`로 포스트를 작성하면 해당 Community 포스트가 인증된 사용자의 팔로워 타임라인에도 브로드캐스트됩니다. 이는 x.com의 "팔로워와도 공유" 체크박스에 해당합니다.
### Community Notes API 출시
오늘 [Community Notes API](https://docs.x.com/x-api/community-notes/introduction)를 출시했습니다. AI Note Writer가 Community Notes에 프로그래밍 방식으로 참여할 수 있도록 하는 새로운 엔드포인트 모음입니다:
* `GET /2/notes/search/posts_eligible_for_notes` — Community Note 작성 대상 포스트를 검색합니다
* `GET /2/notes/search/notes_written` — 인증된 AI Note Writer가 이전에 작성한 노트를 조회합니다
* `POST /2/notes` — Community Note를 제출합니다
액세스에는 X Developer AI 등록과 Community Notes AI Note Writer 승인이 필요합니다.
### DM Events 동작 변경
오늘 X API V2 DM Events 동작을 변경했습니다. 새로운 변경 사항에 따라 `participant_ids` 배열은 `ParticipantsJoin` 및 `ParticipantsLeave` 이벤트에만 포함되며, 이벤트 발생 시점에 참여하거나 떠난 참가자만 나열됩니다. `MessageCreate` 이벤트에는 더 이상 `participant_ids` 배열이 포함되지 않습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/upcoming-change-to-x-api-dm-events-endpoints-behavior/241841)에서 확인하세요.
### Account Activity API 엔드포인트 출시
오늘 새로운 X API v2 [Account Activity API 엔드포인트](/x-api/webhooks/introduction)를 출시했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/account-activity-api-is-now-available-in-v2/242895)에서 확인하세요.
### 미디어 업로드 엔드포인트 개선
개발자 경험을 향상시키기 위해 미디어 업로드 엔드포인트에 몇 가지 개선 사항을 추가했습니다. [Media Upload 엔드포인트](/x-api/media/introduction)에 Chunked Media Upload용 전용 엔드포인트를 도입했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/media-upload-endpoints-update-and-extended-migration-deadline/241818)에서 확인하세요.
### OAuth 2.0을 통한 이메일 주소 조회 지원
오늘 X API V2에서 OAuth 2.0을 통한 이메일 주소 조회 지원을 추가했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-support-for-email-address-retrieval-with-oauth-2-0-in-the-x-api-v2/240555)에서 확인하세요.
### 사용자 제휴 데이터 변경
오늘 X API V2 User Affiliation 데이터에 변경 사항을 적용했습니다. 새로운 변경 사항에 따라 `affiliation.user_id`는 `user_ids` 배열을 반환합니다. 이전에는 사용자가 여러 제휴를 가지고 있더라도 단일 `user_id`를 문자열로 반환했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/change-to-x-api-user-affiliation-data/237164)에서 확인하세요.
### Media Upload 엔드포인트 출시
오늘 새로운 X API v2 [Media Upload 엔드포인트](/x-api/media/introduction)를 출시했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-media-upload-endpoints-in-the-x-api-v2/234175/3)에서 확인하세요.
### 새로운 문서 사이트 출시
오늘 새로운 X Developer Platform 문서 사이트 [https://docs.x.com](https://docs.x.com)을 출시했습니다.
### xurl 도구 출시
오늘 OAuth 2.0을 지원하는 X 개발자용 API 테스트를 단순화하는 새로운 도구인 [xurl](https://github.com/xdevplatform/xurl)을 출시했습니다.
### Community ID Tweet 필드 추가
오늘 X API v2에 `community_id` Tweet 필드를 추가했습니다. 자세한 내용은 [여기](https://x.com/tapshah21/status/1860061806653317126)에서 확인하세요.
### DM 차단 엔드포인트 추가
오늘 X API v2에 DM 차단 및 DM 차단 해제 엔드포인트를 추가했습니다.
### 장문 게시물 지원
오늘 4k 대신 25k 길이의 장문 게시물을 작성할 수 있는 기능을 추가했습니다.
### 장문 게시물 지원
오늘 X API v2를 사용하여 장문 게시물을 만들 수 있는 기능을 추가했습니다
### 사용자 제휴 가져오기
오늘 X API v2를 사용하여 프로그래밍 방식으로 사용자의 제휴를 가져올 수 있는 기능을 추가했습니다
### Article 메타데이터 가져오기
오늘 X API v2를 사용하여 Article 메타데이터를 가져올 수 있는 기능을 추가했습니다
### 프로필 이미지 및 커버 사진 가져오기
오늘 X V2 API를 통해 프로필 이미지 및 커버 사진 URL을 가져올 수 있는 기능을 추가했습니다
### Connection Status 필드 추가
오늘 X API v2에 `connection_status` 필드를 추가했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-connection-status-field-in-the-user-object-in-the-x-api-v2/212588)에서 확인하세요.
### Trends Lookup 엔드포인트 추가
오늘 X API v2에 Trends lookup 엔드포인트를 추가했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567)에서 확인하세요.
### Users Search 엔드포인트 추가
오늘 X API v2에 Users Search 엔드포인트를 추가했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567)에서 확인하세요.
### DM 권한 가져오기
오늘 X API v2를 통해 DM 권한을 가져올 수 있는 기능을 추가했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/dm-permissions-available-in-the-x-api-v2/209688)에서 확인하세요.
### Subscription Type 필드 출시
오늘 X API v2의 User 객체에 `subscription_type` 필드를 출시했습니다. 자세한 내용은 [여기](https://devcommunity.x.com/t/new-subscription-type-field-is-available-in-the-twitter-api-v2/209219/2)에서 확인하세요.
### Get Posts Usage 엔드포인트
오늘 X API v2에서 게시물 사용량을 프로그래밍 방식으로 가져오는 엔드포인트를 출시했습니다. 자세한 내용은 [여기](https://developer.x.com/en/docs/twitter-api/usage/tweets/api-reference/get-usage-tweets)에서 확인하세요.
### Reposts Lookup 엔드포인트 출시
오늘 X API v2에서 게시물의 리포스트를 조회하는 엔드포인트를 출시했습니다. 자세한 내용은 [여기](https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweets)에서 확인하세요.
### Search 엔드포인트 사용 중단
오늘 X API v1.1에서 `search/tweets`, `users/search`, `geo/search` 엔드포인트를 사용 중단합니다. 자세한 내용은 [여기](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features)에서 확인하세요.
### Replay API 엔드포인트 사용 중단
오늘 엔터프라이즈 X API에서 Replay API 엔드포인트를 사용 중단합니다. 대신 [recovery](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features) 기능을 사용할 수 있습니다.
### Historical Powertrack 엔드포인트 사용 중단
오늘 엔터프라이즈 X API에서 Historical Powertrack 및 Insights Track 엔드포인트를 사용 중단합니다.
### Basic 및 Pro 등급에서 Follows 엔드포인트 제거
오늘 X API v2의 Basic 및 Pro 등급에서 Follows 및 List Follows 엔드포인트를 제거합니다.
### Manage Blocks 엔드포인트 제거
오늘 X API v2에서 Manage Blocks 엔드포인트를 제거합니다.
### Bookmarks Count 및 장문 게시물 지원
오늘 X API v2에서 bookmarks count 가져오기 지원 및 280자 이상의 게시물 가져오기 기능을 추가했습니다.
### Statuses/Filter 엔드포인트 사용 중단
오늘 X API v1.1의 `statuses/filter` 엔드포인트를 사용 중단합니다. 개발자는 X API v2의 filtered stream 엔드포인트를 사용할 수 있습니다.
### View Counts 지원
오늘 X API v2에 view counts 지원을 추가합니다. 게시물 페이로드의 `public_metrics`에서 `impression_count`라는 새로운 필드를 사용할 수 있습니다.
### Verified Type 필드 추가
오늘 사용자 계정이 가지고 있는 인증 유형(blue, business, government 또는 none)을 나타내는 `verified_type` 사용자 필드를 X API v2에 추가합니다.
### Source 필드 제거
오늘 X API의 게시물 페이로드에서 `source` 필드를 제거합니다.
### Direct Messages 엔드포인트 추가
오늘 v2 Direct Messages 엔드포인트 6개를 추가합니다. 이번 릴리스에는 Direct Message 대화 이벤트를 조회하기 위한 GET 메서드 3개와 새로운 Direct Message를 생성하기 위한 POST 메서드 3개가 포함됩니다. 이러한 메서드는 처음으로 그룹 대화를 지원합니다.
이 업데이트에 대한 자세한 내용은 [블로그 게시물](https://developer.x.com/en/blog/product-news/2022/new-v2-direct-messages-endpoints)을 참조하세요.
### 편집된 게시물 메타데이터 지원
오늘 개발자가 X API v2를 사용하여 편집된 게시물 메타데이터를 가져올 수 있는 기능을 추가합니다.
이 업데이트에 대한 자세한 내용은 [블로그 게시물](https://developer.x.com/en/blog/product-news/2022/supporting-edit-tweet-functionality)을 참조하세요.
### 필터링 연산자 별칭 추가
필터링/쿼리 연산자 "별칭"이 엔터프라이즈, 프리미엄 및 v2 전반에 걸쳐 search 및 filtered stream 엔드포인트에 추가되었습니다. 많은 경우에 연산자는 statuses 대신 posts를 참조합니다. 예를 들어 `in_reply_to_status_id`의 별칭으로 `in_reply_to_tweet_id`가 있습니다. 다른 경우에는 새로운 연산자 별칭이 수행되는 일치에 더 많은 명확성을 추가합니다. 예를 들어 게시물은 하나의 비디오 첨부 파일만 가질 수 있으므로 `has:videos`에 대한 새로운 `has:video_link` 별칭이 제공됩니다. 더 많은 예시를 보려면 [v2 filtered stream 연산자 표](https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule#list)를 확인하세요.
### Reverse Chronological Home Timeline 업데이트
오늘부터 reverse chronological home timeline v2 엔드포인트는 지난 7일 동안 타임라인에 생성된 모든 게시물과 생성 날짜에 관계없이 가장 최근 800개를 반환할 수 있습니다.
### Filtered Stream용 새로운 필터링 연산자
오늘부터 filtered stream 엔드포인트로 빌드하는 모든 개발자가 10개의 새로운 v2 필터링 연산자를 사용할 수 있으며, 추가로 10개가 더 폭넓게 제공됩니다.
이 업데이트에 대한 자세한 내용은 [블로그 게시물](https://developer.x.com/en/blog/product-news/2022/twitter-api-v2-filtered-stream)을 참조하세요.
### Streaming 엔드포인트 지연 시간 업데이트
오늘 X API v2의 streaming 엔드포인트를 업데이트하여 지연 시간을 50% 감소시킵니다.
### Essential Access에서 v1.1 Media 엔드포인트 활성화
오늘 X API v2의 Essential 액세스에서 v1.1 media 엔드포인트를 활성화합니다.
이 업데이트에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/v1-1-media-endpoints-available-for-essential-access-in-the-twitter-api-v2/171664)를 참조하세요.
### Reverse Chronological Home Timeline 엔드포인트 출시
오늘 팔로우하는 사람이 게시한 가장 최근 게시물과 리포스트의 모음을 가져올 수 있는 새로운 엔드포인트를 출시합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/reverse-chronological-home-timeline-in-the-twitter-api-v2/171549)를 참조하세요.
새로운 엔드포인트와 함께 [media 객체](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/media)에 `variants` 필드를 사용할 수 있습니다. 이를 통해 URL에 첨부된 콘텐츠의 유형을 가져올 수 있습니다.
### Bookmarks 엔드포인트 출시
오늘 X API v2를 사용하여 Bookmarks를 관리하고 조회할 수 있는 새로운 엔드포인트를 출시합니다. Bookmarks 기능은 X 앱에서 오랫동안 사용되어 왔지만, 지금까지 API를 통해 Bookmarks를 가져오거나 생성하거나 관리하는 솔루션을 빌드할 수 있는 엔드포인트는 없었습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/build-with-bookmarks-on-the-twitter-api-v2/168804)를 참조하세요.
### Quotes Lookup 엔드포인트 출시
오늘 게시물 ID의 인용을 가져올 수 있는 [quotes lookup 엔드포인트](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction)를 출시합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/introducing-the-quote-tweets-lookup-endpoint-to-the-twitter-api-v2/168370)를 참조하세요.
### 문서 탐색 업데이트
여러분의 피드백을 들었습니다. 문서에서 콘텐츠를 찾는 것이 어려웠고, 링크를 클릭하면 완전히 다른 사이드 탐색으로 이동되어 혼란스러웠습니다.
오늘 단일 사이드 탐색에서 X Developer Platform의 전체 제공을 탐색할 수 있는 업데이트된 문서 탐색을 출시했습니다. 이번 출시에서 중복 페이지를 제거하고, 혼란스러운 아이콘을 없애고, 탐색 내의 다양한 요소와 상호 작용하는 방식을 개선했습니다.
피드백이 있다면 [피드백 채널](https://twitterdevfeedback.uservoice.com/forums/930250-twitter-api)을 통해 알려주세요.
### Reposts 및 Likes Lookup 엔드포인트 개선
오늘 [reposts lookup](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) 및 [Likes lookup](https://developer.x.com/en/docs/twitter-api/tweets/likes/introduction) 엔드포인트에 개선 사항을 출시하여 게시물을 좋아하거나 리포스트한 마지막 100개 계정뿐만 아니라 전체 계정 목록을 가져올 수 있습니다.
이 출시에 대한 자세한 내용은 포럼 공지를 참조하세요.
### OAuth 2.0 인증 지원
오늘 모든 개발자는 Developer Console에서 OAuth 2.0을 인증 방법으로 선택하여 인증할 수 있습니다. 이번 릴리스의 일환으로 confidential 및 public 클라이언트에 대한 지원과 이 인증 방법을 사용할 모든 관련 v2 엔드포인트를 추가했습니다.
OAuth 2.0은 개발자에게 애플리케이션의 scope에 대한 더 많은 제어 권한을 제공하고 여러 기기에서 인증 흐름을 개선하는 업계 표준 인증 프로토콜입니다. 즉, X 사용자를 위한 애플리케이션을 빌드하는 개발자는 앱이 사용자에게 요청하는 정보를 더 잘 제어할 수 있으므로, 필요한 데이터와 정보만 최종 사용자에게 요청하면 됩니다.
이 현대적인 인증 프로토콜을 통해 사용자에게 앱을 인증하기 위한 보다 간소화된 동의 흐름을 제공할 수 있으며, 요청한 특정 scope만 표시됩니다.
이 출시에 대한 자세한 내용은 포럼 공지를 참조하세요.
### X API v2 주요 플랫폼 업데이트
**주요 플랫폼 업데이트: X API v2가 이제 기본 버전이 되며, 새로운 Essential 및 Elevated 액세스 및 정책 변경**
오늘 X API v2가 이제 X API의 기본 버전임을 발표합니다. X API 위에 빌드된 모든 기존 앱의 90% 요구 사항을 충족하기에 충분한 엔드포인트와 기능을 X API v2에 출시했습니다.
X API v2 개발자 경험을 더욱 향상시키기 위해 오늘 다음 변경 사항을 출시합니다:
* API에 대한 빠르고 무료인 Essential 액세스와 사용 사례가 승인된 개발자에게 무료 Elevated 액세스. About the X API 페이지에서 이러한 액세스 수준에 대한 자세한 내용을 확인할 수 있습니다.
* Developer Policy에서 X의 핵심 기능을 사용한 빌드 방법을 제한하고 앱을 통해 지원할 수 있는 사용자 수를 제한하는 문구를 제거하고 있습니다.
* X를 더 좋고, 더 건강하며, 공공의 대화를 확장하는 도구와 제품을 빌드하도록 권장하기 위해 플랫폼을 개방하고 있습니다. [빌드해 주기를 바라는 솔루션 목록을 확인하세요](https://developer.x.com/en/docs/twitter-api/what-to-build).
* 특히 X의 핵심 기능을 포함한 X 경험 복제를 제한하는 용어와 많은 사용자 토큰을 가지려면 허가가 필요한 용어를 제거했습니다.
* X에서 사람들을 돕는 솔루션을 빌드하는 것은 종종 개발자가 X에서 사용할 수 있는 일부 기능을 빌드(또는 복제)해야 함을 의미한다는 것을 알고 있습니다. Developer Policy에 대한 이러한 변경 사항은 개발자 생태계에 명확성을 제공하고 개발자가 공공의 대화에 빌드, 혁신, 영향을 미치는 것을 쉽게 만드는 개방형 API 플랫폼을 제공하기 위한 것입니다.
이 출시와 이 순간으로 이어진 X API 출시에 대한 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/ushering-in-a-new-era-for-the-twitter-developer-platform-with-the-twitter-api-v2/162087)을 참조하세요.
이전 changelog 항목을 살펴보는 것 외에도 X API v2에 지금까지 출시된 모든 내용을 이해하기 위해 검토할 수 있는 몇 가지 주요 리소스를 모았습니다:
* [X API endpoint map](/x-api/migrate/x-api-endpoint-map)
* [About the X API](/x-api/getting-started/about-x-api)
### List Lookup 엔드포인트 출시
오늘 X API v2에 새로운 List lookup 엔드포인트를 출시합니다. 이러한 엔드포인트를 통해 사용자는 팔로워, 멤버, 게시물 등 지정된 Lists의 세부 정보를 가져올 수 있습니다. 가져온 데이터는 큐레이션, 분석 및 검색 사용 사례 및 요구 사항을 해결하는 솔루션을 빌드하는 데 사용할 수 있습니다. 새로운 List 엔드포인트 외에도 Academic Research 액세스 수준에서 새로운 `list:` 연산자를 사용할 수 있습니다. 이는 search posts 및 post counts에 사용할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-list-lookup-endpoints-for-the-twitter-api-v2/161965)를 참조하세요.
### Spaces 엔드포인트 추가 기능
Spaces 엔드포인트에 Space의 티켓을 구매한 사람들의 목록을 반환하는 기능과 Topics에 대한 지원을 추가합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/adding-new-functionality-to-spaces-endpoints/161959)를 참조하세요.
### Manage Posts 엔드포인트 출시
오늘 X API v2에 새로운 manage posts 엔드포인트를 출시합니다. 게시물 작성 및 게시물 삭제 기능 외에도 폴 게시, 이미지에 사람 태그 지정, 답글 설정으로 게시물 작성, Super Followers에 게시 기능을 추가했습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-manage-tweets-endpoints-for-the-twitter-api-v2/161501)를 참조하세요.
### Embedded 버튼 변경 사항
오늘 X의 embedded 버튼에 일부 변경 사항을 적용합니다. 버튼이 X.com 버튼과 일치하도록 더 둥글게 변경되었으며 (아주 약간) 색상 팔레트가 업데이트되었습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/embedded-buttons-have-a-new-look/160528)를 참조하세요.
### Lists 엔드포인트 그룹 출시
오늘 X API v2에 새로운 Lists 엔드포인트 그룹을 출시합니다. 이러한 엔드포인트를 통해 선호도, 관심사, 그룹 또는 주제를 기반으로 게시물을 큐레이션하고 정리하는 솔루션을 빌드할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-manage-list-endpoints/159980)를 참조하세요.
### Mutes Lookup 엔드포인트 출시
오늘 X API v2에 새로운 [mutes lookup](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) 엔드포인트를 출시합니다. 이 엔드포인트를 통해 인증된 사용자는 음소거한 계정에 대한 정보를 가져올 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-new-mutes-lookup-endpoint-for-the-twitter-api-v2/159680)를 참조하세요.
### OAuth 2.0 베타 출시
오늘 X API v2에서 OAuth 2.0 및 세분화된 scope의 베타를 출시합니다. X Developer Platform에서 OAuth 2.0의 미래를 형성하는 데 관심이 있는 개발자는 OAuth 2.0 베타에 대한 액세스를 요청할 수 있습니다.
OAuth 2.0은 인증을 위한 업계 표준이며 보다 현대적인 인증 경험을 제공합니다.
OAuth 2.0 베타를 통해 v2 Project 및 관련 App에서 이 새로운 기능을 테스트하고 General Availability 출시 전에 피드백을 제공할 수 있습니다. 그러나 이 OAuth 2.0 구현은 현재 개발 중이므로 공개, 프로덕션 환경 또는 앱에서 테스트하지 않는 것이 강력히 권장됩니다.
이 출시에 대한 자세한 내용은 포럼 공지를 참조하세요.
### Batch Compliance 엔드포인트 출시
오늘 X API를 사용하는 개발자가 X 데이터를 [Developer Agreement and Policy](https://developer.x.com/en/developer-terms/policy)에 따라 유지하기 쉽도록 X API v2에 새로운 [batch compliance 엔드포인트](https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/introduction)를 출시합니다. 이러한 엔드포인트를 통해 개발자와 연구자는 많은 양의 게시물 또는 사용자 ID를 배치 업로드하고 데이터 세트가 사용자의 의도와 X의 현재 콘텐츠 상태를 반영하도록 보장하기 위해 필요한 조치를 이해할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-batch-compliance-endpoints-available-on-the-twitter-api-v2/158534)를 참조하세요.
### Spaces 엔드포인트 출시
오늘 X API v2에 새로운 [Spaces 엔드포인트](https://developer.x.com/en/docs/twitter-api/spaces/overview)와 [새로운 최상위 Spaces 데이터 사전](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/space)을 출시합니다. Spaces 엔드포인트를 사용하면 Space ID 또는 사용자 ID로 Spaces를 조회하거나, 제목에 언급된 사람의 키워드, 해시태그 또는 사용자 이름을 사용할 수 있습니다. 새로운 데이터 사전에는 제목, 티켓 판매 상태, 참가자 메트릭과 같은 Space에 대한 관련 정보가 포함됩니다. 모든 사용자 ID는 전체 객체로 확장될 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/introducing-new-spaces-endpoints-on-the-twitter-api-v2/158213)를 참조하세요.
### 비디오 조회 수 제한을 위한 새로운 객체
이전에는 엔터프라이즈 \[Engagement API]/x-api/enterprise-gnip-2.0/fundamentals/engagement-api)에서 1800일 이상 된 게시물에 대해 비디오 조회 메트릭을 요청할 때, 컨텍스트 없이 0 값을 전달했습니다. 오늘부터 이러한 경우 `unsupported_for_video_views_tweet_ids`라는 새로운 객체를 전달하기 시작합니다. 여기에는 1800일 이상 된 게시물 ID의 쉼표로 구분된 목록이 포함됩니다. 이러한 게시물에 대해 요청된 다른 모든 메트릭은 별도의 객체에서 계속 받게 됩니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-engagement-api-video-views-object-to-clarify-limitation/158163)를 참조하세요.
### Alt Text 필드 추가
오늘 개발자가 접근성을 더 의식적으로 구축할 수 있도록 X API v2의 media 객체에 `alt_text` 필드를 사용할 수 있게 합니다.
이 필드를 요청하려면 `expansions=attachments.media_keys` 매개변수와 `media.fields=alt_text` 매개변수를 전달해야 합니다. 요청에 포함되면 이 필드는 alt text가 포함된 이미지를 포함하는 모든 게시물에 대한 alt text를 반환합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/media-alt-text-field-now-available-in-twitter-api-v2/157939)를 참조하세요.
### Reposts 엔드포인트 출시
오늘 X API v2에 새로운 [reposts](https://developer.x.com/en/docs/twitter-api/tweets/retweets) 엔드포인트를 출시합니다. 개발자는 이제 이러한 엔드포인트를 사용하여 인증된 사용자를 대신해 게시물을 리포스트하거나 리포스트를 취소하거나, 주어진 게시물을 리포스트한 사람을 조회할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-retweets-endpoints/156827)를 참조하세요.
### Manage Mutes 엔드포인트 출시
오늘 X API v2에 새로운 [manage mutes](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) 엔드포인트를 출시합니다. 이러한 엔드포인트를 통해 인증된 사용자는 계정을 음소거하거나 음소거 해제할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-new-manage-mutes-endpoints-for-the-twitter-api-v2/156261)를 참조하세요.
이제 `tweet.fields` 매개변수와 함께 `context_annotations` 필드를 요청할 때 [full-archive search](/x-api/posts/full-archive-search) 엔드포인트에서 전달할 수 있는 `max_results`를 100으로 줄였습니다. 즉, 페이지당 최대 100개의 게시물만 가져올 수 있습니다.
### Streaming 엔드포인트의 신뢰성 기능
오늘 X API v2의 filtered stream 및 sampled stream에 backfill 및 redundant connections라는 두 가지 신뢰성 streaming 기능을 출시하며, 이는 현재 Academic Research 제품 트랙에서 사용 가능합니다.
redundant connections 기능을 사용하면 주어진 stream에 두 번 연결할 수 있어 하나의 stream이 연결 해제를 경험하는 경우 streaming 가동 시간을 최대화하는 데 도움이 됩니다.
Backfill은 streaming 요청에 `backfill_minutes` 매개변수와 1에서 5 사이의 정수를 추가하여 사용할 수 있으며, 연결이 끊긴 stream으로 인해 누락된 데이터를 요청할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-reliability-and-recovery-functionality-available-for-twitter-api-v2-streaming-endpoints/156244/2)를 참조하세요.
### Post Counts 엔드포인트 출시
오늘 X API v2에 새로운 [post counts 엔드포인트](/x-api/posts/counts/introduction)를 출시합니다. 여기에는 두 가지 다른 엔드포인트가 포함됩니다: 모든 제품 트랙에서 사용 가능한 Recent post counts와 현재 Academic Research 제품 트랙에서만 사용 가능한 full-archive post counts. 이러한 엔드포인트를 사용하여 지정된 쿼리와 일치하는 게시물 수를 받을 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/introducing-new-tweet-counts-endpoints-to-the-twitter-api-v2/155997)를 참조하세요.
### Teams 개선
오늘 커뮤니티에서 들은 피드백을 바탕으로 teams 기능의 주요 개선 사항을 출시합니다. team 페이지의 스타일과 디자인을 업데이트했습니다. 또한 팀원을 초대하거나 초대가 실패한 이유에 대해 자세히 알아보기 쉽도록 초대 흐름을 변경했습니다. team 계정이 있는 경우 Developer Console의 [teams 페이지](https://developer.x.com/en/portal/teams)를 보면 변경 사항을 확인할 수 있습니다. teams에 대한 자세한 내용은 \[이 주제에 대한 문서]\([https://developer.x.com/en/docs/Developer](https://developer.x.com/en/docs/Developer) Console/overview#team)와 관련 \[FAQ]\([https://developer.x.com/en/docs/Developer](https://developer.x.com/en/docs/Developer) Console/faq#dev-portal-management-faq)를 확인하세요.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-improvements-to-the-functionality-of-teams/155447/2)를 참조하세요.
### Configuration 엔드포인트 사용 중단
오늘 standard v1.1 `GET /help/configuration` 엔드포인트를 사용 중단했습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/retiring-the-1-1-configuration-endpoint/153319)를 참조하세요.
### oEmbed 엔드포인트 통합
오늘 새로운 기능이 일관된 방식으로 지원될 수 있도록 v1.1 oEmbed 엔드포인트가 2021년 11월 23일에 사용 중단되고 제거될 것이라는 사실을 공유합니다. 그 날짜 이후 X oEmbeds(embedded 게시물 및 timelines)에 대한 유일한 공식 및 지원되는 API 엔드포인트는 publish.x.com/oembed가 될 것입니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/consolidating-the-oembed-functionality/154690/2)를 참조하세요.
### Blocks 및 Likes Lookup 엔드포인트 출시
오늘 X API v2에 새로운 [blocks](/x-api/users/blocks) 및 [Likes](/x-api/posts/likes) lookup 엔드포인트를 출시합니다. 이러한 엔드포인트를 사용하면 v2 API를 사용하여 계정이 좋아한 게시물, 게시물을 좋아한 사용자, 본인 또는 인증된 사용자가 차단한 사람에 대한 정보를 가져올 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-twitter-api-v2-likes-lookup-and-blocks-lookup/154353)를 참조하세요.
### Manage Likes 엔드포인트 출시
오늘 X API v2에 새로운 [manage Likes](https://developer.x.com/en/docs/twitter-api/tweets/likes) 엔드포인트를 출시합니다. 이러한 엔드포인트를 사용하면 v2 API를 사용하여 게시물에 좋아요를 추가하거나 좋아요를 취소할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-new-manage-likes-endpoints-for-thetwitter-api-v2/152780)를 참조하세요.
### Manage Blocks 엔드포인트 출시
오늘 X API v2에 새로운 [manage blocks](/x-api/users/blocks) 엔드포인트를 출시합니다. 이러한 엔드포인트를 사용하면 사용자 ID를 사용하여 사용자를 대신해 계정을 차단하거나 차단 해제할 수 있습니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/announcing-manage-blocks-for-twitter-api-v2/152358/2)를 참조하세요.
### Embedded Timelines 지원 제거
오늘 [embedded timeline 위젯](https://developer.x.com/en/docs/x-for-websites/timelines/overview)의 미래에 대한 계획을 공유합니다. 2021년 6월 23일에 Likes, Collections 및 Moments timelines를 사용 중단할 계획입니다. [Profile](https://developer.x.com/en/docs/x-for-websites/timelines/guides/profile-timeline) 및 [Lists](https://developer.x.com/en/docs/x-for-websites/timelines/guides/list-timeline) timelines를 사용하는 것이 좋습니다. 이는 더 빠르고, 사용하기 쉽고, X 기능 및 기능과 최신 상태를 유지하도록 업데이트하고 있습니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/removing-support-for-embedded-like-collection-and-moment-timelines/150313)에서 확인할 수 있습니다.
### Manage Follows 엔드포인트 출시
오늘 X API v2에 새로운 [manage follows](/x-api/users/follows) 엔드포인트를 출시합니다. 이러한 엔드포인트를 사용하면 사용자의 사용자 ID를 사용하여 사용자를 대신해 계정을 팔로우하거나 언팔로우할 수 있습니다. 이 출시는 계정의 팔로워와 그들이 팔로우하는 사람을 가져올 수 있는 [follows lookup](/x-api/users/follows) 엔드포인트 출시 몇 달 후에 이루어집니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/introducing-the-new-manage-follows-endpoints-to-the-twitter-api-v2/149465)를 참조하세요.
### Academic Research 제품 트랙 소개
오늘 [X API v2](/x-api/introduction)에 새로운 [Academic Research 제품 트랙](/resources/fundamentals/developer-apps)을 소개합니다. 이 업데이트는 Academic Researchers를 위한 새로운 신청 프로세스를 도입하며, 승인된 사람들에게 더 큰 액세스와 고급 기능을 잠금 해제할 Academic Research [Project](/resources/fundamentals/developer-apps)를 제공합니다.
새로운 Academic Research 제품 트랙을 통해 다음에 액세스할 수 있습니다:
* 현재 Academic Research 제품 트랙에서만 사용 가능한 새로운 X API v2 [full-archive search 엔드포인트](/x-api/posts/full-archive-search).
* Basic [액세스 수준](https://developer.x.com/en/products/x-api/early-access/guide#na_2)에서 [Standard 제품 트랙](/resources/fundamentals/developer-apps)에 사용 가능한 500,000개에서 증가한 1천만 개의 [post cap](/x-api/fundamentals/post-cap).
* `$` (cashtag), `bio` (filtered stream을 통해서만 사용 가능), `bio_name` (filtered stream을 통해서만 사용 가능), `bio_location` (filtered stream을 통해서만 사용 가능), `place`, `place_country`, `point_radius`, `bounding_box`, `-is:nullcast`, `has:cashtags` 및 `has:geo`를 포함하여 [recent search](/x-api/posts/recent-search), [full-archive search](/x-api/posts/full-archive-search) 및 [filtered stream](/x-api/posts/filtered-stream)에서 사용 가능한 새로운 필터 연산자.
* Standard 제품 트랙의 Basic 액세스 수준에서 사용 가능한 25개에서 증가한 1,000개의 동시 규칙에 대한 filtered stream의 증가된 규칙 제한.
* Standard 제품 트랙의 Basic 액세스 수준에서 사용 가능한 512자 제한에서 증가한 1,024자의 쿼리 및 규칙 문자 제한
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/introducing-the-new-academic-research-product-track/148632)를 참조하세요.
### Reply Settings 필드 추가
오늘 게시물 객체에 `reply_settings`라는 새로운 필드를 출시합니다. 이 필드는 post lookup, hide replies, recent search, sampled stream, filtered stream, follows lookup, user post timeline 및 user mention timeline 엔드포인트를 포함하여 게시물을 반환하는 모든 X API v2 엔드포인트 또는 모든 엔드포인트에서 게시물 객체를 [확장](/x-api/fundamentals/expansions)하여 사용할 수 있습니다.
이 필드는 게시물 작성자가 다른 사람이 게시물에 답글을 달 수 있도록 허용한 방법을 나타냅니다. 모두, 게시물에서 언급한 사람만, 또는 팔로우하는 사람만입니다. `reply_settings` 필드에서 반환되는 필드 값은 `everyone`, `mentionedUsers` 및 `following`을 포함합니다. 게시물에 대화 컨트롤이 설정되지 않은 경우에도 필드에 `everyone` 값이 있는 게시물 객체에 표시됩니다.
### User Post 및 Mention Timeline 엔드포인트 출시
오늘 X API v2에 새로운 [user post timeline 및 user mention timeline 엔드포인트](/x-api/posts/timelines)를 출시합니다. 이러한 엔드포인트를 사용하면 X에서 지정된 계정이 작성하거나 언급한 게시물을 요청할 수 있습니다. 자세한 내용은 포럼 게시물 공지를 참조하세요.
### Follows Lookup 엔드포인트 출시
오늘 X API v2에 새로운 [follows lookup 엔드포인트](/x-api/users/follows)를 출시합니다. 이러한 엔드포인트를 사용하면 사용자 ID를 사용하여 계정의 팔로워와 그들이 팔로우하는 사람을 가져올 수 있습니다. 자세한 내용은 포럼 게시물 공지를 참조하세요.
### Labs v2 엔드포인트 사용 중단
Labs v2 recent search 및 hide replies 엔드포인트를 사용 중단했습니다
다음 엔드포인트를 사용 중단했습니다. 이러한 엔드포인트의 Labs 버전을 사용하고 있었다면 연결된 마이그레이션 가이드를 사용하여 통합을 업데이트하고 새로운 X API v2 버전을 사용할 수 있습니다:
* [Recent search v2](/x-api/posts/search/migrate/overview)
* [Hide replies v2](/x-api/posts/hide-replies/migrate)
새로운 X API v2로의 마이그레이션에 대한 추가 세부 정보는 [마이그레이션 허브](/x-api/migrate/overview)를 통해 확인할 수 있습니다.
질문이 있으면 [Labs 포럼 카테고리](https://devcommunity.x.com/c/labs/57)에 문의하세요.
### Labs v1 엔드포인트 사용 중단
2020년 8월 12일에 새로운 X API v2: Early Access를 출시했습니다. 이 릴리스에서 Labs 프로그램의 여러 엔드포인트를 X API v2로 졸업시키고, 엔드포인트의 Labs 버전이 사용 중단 상태로 60일 동안 유지된 후 사용 중단된다고 발표했습니다.
오늘은 출시 후 60일이 되는 날로, 다음 엔드포인트를 사용 중단했음을 의미합니다. 이러한 엔드포인트의 Labs 버전을 사용하고 있다면 연결된 마이그레이션 가이드를 사용하여 통합을 업데이트하고 새로운 X API v2 버전을 사용할 수 있습니다:
* Post metrics v1
* Filtered stream v1
* Sampled stream v1
새로운 X API v2로의 마이그레이션에 대한 추가 세부 정보는 [마이그레이션 허브](/x-api/migrate/overview)를 통해 확인할 수 있습니다.
질문이 있으면 [Labs 포럼 카테고리](https://devcommunity.x.com/c/labs/57)에 문의하세요.
### 게시물 사용 상태 바 추가
새로운 Developer Console의 [메인 대시보드 페이지](https://developer.x.com/en/portal/dashboard)에서 이제 월 500,000개의 게시물 [post cap](/x-api/fundamentals/post-cap)에 대한 사용량을 확인할 수 있습니다. 이 cap은 Basic 액세스의 다음 v2 엔드포인트(filtered stream 및 recent search)에서 Project 수준으로 적용됩니다.
이 기능을 보고 새로운 v2 엔드포인트를 사용하려면 [새로운 Developer Console 경험](https://developer.x.com/en/portal/opt-in.html)을 활성화해야 합니다.
### Hide Replies 엔드포인트 출시
오늘 v2 X API에 새로운 hide replies 엔드포인트를 출시합니다. 이 엔드포인트를 사용하면 게시물에 대한 욕설, 방해 또는 오해의 소지가 있는 답글을 숨길 수 있습니다. 이는 공공의 대화의 건강을 개선하는 데 중요한 부분입니다. 자세한 내용은 포럼 게시물 공지를 참조하세요.
X Developer Labs의 동일한 엔드포인트는 이제 사용 중단되었으며 90일 후에 사용 중단됩니다. [v2 엔드포인트로 마이그레이션하는 방법을 알아보세요.](/x-api/posts/hide-replies#comparing-twitter-apis-hide-replies-endpoints)
### X API v2 엔드포인트에 대한 Early Access
오늘 [새로운 X API의 첫 엔드포인트에 대한 Early Access](https://blog.x.com/developer/en_us/topics/tools/2020/introducing_new_twitter_api.html)를 발표했습니다!
새로운 X API는 새로운 기능을 더 빠르게 제공할 수 있는 새로운 API 기반, 받는 필드를 더 잘 제어할 수 있는 업데이트된 데이터 형식 및 새로운 기능, 새로운 post, user 및 media 필드, 그리고 다음을 포함하여 게시물을 듣고 분석할 수 있는 업데이트된 엔드포인트 세트를 특징으로 합니다:
* [Post lookup](/x-api/posts/post-lookup-by-post-ids)
* [User lookup](/x-api/users/user-lookup-by-id)
* [Recent search](/x-api/posts/recent-search)
* [Filtered stream](/x-api/posts/filtered-stream)
* [Sampled stream](/x-api/stream/stream-sampled-posts)
사용 가능한 새로운 기능의 전체 목록과 마이그레이션 리소스는 \[X API v2: Early Access 문서 페이지][https://developer.x.com/en/docs/x-api/early-access)에서](https://developer.x.com/en/docs/x-api/early-access\)에서) 확인할 수 있습니다.
계획에 대한 자세한 내용은 «\[Guide to the future of the X API][https://developer.x.com/en/docs/x-api/early-access)»에서](https://developer.x.com/en/docs/x-api/early-access\)»에서) 확인하세요.
### Labs 엔드포인트 사용 중단
이번 릴리스에서 X API v2 대체품 출시로 인해 특정 Labs 엔드포인트를 사용 중단합니다.
다음 Labs v1 엔드포인트는 오늘 출시일로부터 60일 후에 사용 중단됩니다:
* Post metrics v1
* Filtered stream v1
* Sampled stream v1
다음 Labs v2 엔드포인트는 오늘 출시일로부터 90일 후에 사용 중단됩니다:
* Recent search v2
### Hide Replies 개선
답글 숨김 해제 기능을 추가했습니다. 또한 이전에 숨김 해제된 답글을 이 엔드포인트를 통해 다시 숨길 수 있습니다.
자세한 내용은 [Hide replies 문서](https://developer.x.comhttps://developer.x.com/en/docs/labs)에서 확인하세요.
### Labs v1 엔드포인트 사용 중단
오늘 Labs v1 posts and users, hide replies 및 recent search 엔드포인트를 사용 중단합니다.
Labs v1 계획에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/update-on-labs-v1-endpoints/138641)에서 확인할 수 있습니다.
### Quote Tweets 메트릭 추가
오늘 [/totals](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api#post-insights-engagement) 엔드포인트를 통해 'unowned' 게시물에 대해 `quote_tweets` 메트릭을 사용할 수 있게 되었습니다. 즉, 앱 전용 인증을 사용하여 모든 게시물의 인용 수에 액세스할 수 있습니다.
이 변경 사항에 대한 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131)에서 확인할 수 있습니다.
### 새로운 게시물 메트릭 추가
오늘 X Developer Labs post lookup 엔드포인트의 게시물 객체에 두 개의 새로운 비공개 메트릭 하위 필드 `user_profile_clicks` 및 `url_link_clicks`를 추가합니다. `non_public_metrics`, `organic_metrics` 또는 `promoted_metrics` 값 중 하나를 `tweet.fields` 매개변수와 함께 사용할 때 반환됩니다.
자세한 내용은 [post lookup API 참조](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets-id)를 참조하세요
### 리포스트 수 변경
오늘부터 X 웹, iOS 및 Android는 게시물당 총 'reposts and comments' 수를 표시합니다. X API를 사용하여 X 인터페이스와 일치하는 총 'reposts and comments' 수는 사용 가능한 경우 `retweet_count`와 `quote_count`를 추가하여 계산할 수 있습니다. 또한 `quote_count`는 게시물을 인용한 게시물의 총 수가 아니라 게시물을 인용한 총 고유 계정 수가 됩니다. 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/how-the-new-retweets-and-comments-metric-is-returned-with-the-twitter-api/139131/2)을 참조하세요.
### Organic 및 Promoted 메트릭 그룹화
post lookup 엔드포인트의 post 및 media 객체에 `organic_metrics` 및 `promoted_metrics`를 추가합니다.
### 엔드포인트에 메트릭 추가
post lookup 및 recent search 엔드포인트의 post 및 media 객체에 메트릭을 추가합니다.
이러한 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/adding-metrics-to-the-tweets-and-recent-search-endpoints-in-labs/135315)에서 확인할 수 있습니다
### COVID-19 엔드포인트 출시
오늘 새로운 COVID-19 stream 엔드포인트와 함께 제공되는 compliance 엔드포인트를 출시합니다.
이러한 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-covid-19-stream-endpoint-available-in-twitter-developer-labs/135540)에서 확인할 수 있습니다.
### Replay API 사용자 프로필 업데이트
오늘부터 Replay API는 Replay API가 실행될 때 참조된 사용자를 반영하는 사용자 프로필 객체를 전달합니다. 현재 사용자 프로필 객체를 전달하기 위한 이 변경 사항은 2019년 11월 25일의 최근 Historical PowerTrack 업데이트와 유사합니다.
### Post Annotations 추가
posts 및 recent search 엔드포인트의 게시물 객체에 주석을 추가합니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/adding-annotations-to-tweets-and-recent-search-endpoints-in-labs/135193)에서 확인할 수 있습니다.
### Developer Policy 업데이트
오늘 [Developer Policy의 중요한 업데이트](https://developer.x.com/en/developer-terms/policy)를 발표했습니다. [포럼](https://devcommunity.x.com/t/a-new-easier-to-understand-twitter-developer-policy/135038) 및 [블로그](https://blog.x.com/developer/en_us/topics/community/2020/twitter_developer_policy_update.html) 게시물을 통해 자세한 내용을 읽고 개정된 정책을 검토할 것을 권장합니다. Developer Policy는 X API 사용의 기초 중 하나이며 약속을 이해하는 것이 중요합니다.
### Hide Replies 엔드포인트 출시
우리는 사람들이 X에서 대화를 안전하고 편안하게 느낄 수 있도록 돕고 싶습니다. 그 일환으로 오늘 새로운 [엔드포인트](/x-api/posts/hide-replies)로 hide replies 기능을 지원하여 게시물 작성자가 시작하는 대화를 더 잘 제어할 수 있게 되어 기쁩니다.
이 새로운 엔드포인트에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/introducing-the-hide-replies-endpoint/134683)에서 확인할 수 있습니다.
### Labs 엔드포인트 v2 출시
오늘 posts and Users, Recent Search 및 Hide Replies 엔드포인트를 Labs의 v2로 가져옵니다. Labs v1 엔드포인트를 사용 중단하고 이 초기 릴리스 후 90일 이후에 완전히 사용 중단할 것입니다. 또한 이 기간 동안 v1 문서를 사용할 수 있도록 유지합니다. [피드백 채널](https://twitterdevfeedback.uservoice.com/)을 통해 이 버전 관리 전략에 대한 피드백을 제공할 수 있습니다.
posts and Users에 다음 변경 사항을 릴리스합니다:
* 쿼리 매개변수로 [fields](/x-api/fundamentals/fields) 도입
* 쿼리 매개변수로서 [formats](https://developer.x.com/en/docs/labs#payload) 제거
* posts and Users에서 단일 ID [lookup](https://developer.x.com/en/docs/labs/overview/versioning/migration-guide#id-lookup-path)을 위한 경로 변수 추가
* GET /users에서 단일 및 다중 사용자 이름 [lookup](/x-api/migrate/overview#username-lookup-path)을 위한 경로 및 쿼리 매개변수 조정
* 필드 이름 `stats`를 `public_metrics`로 변경
기타 변경 사항은 다음과 같습니다:
* Users에서 `most_recent_tweet_id` 확장 제거
* 해당 필드를 더 쉽게 구문 분석할 수 있도록 posts의 `source` 필드에서 HTML 태그 제거
Recent Search의 핵심 검색, 페이지 매김 및 기타 기능은 동일하게 유지됩니다.
v1에서 v2로 업데이트할 때 사용할 [마이그레이션 자료](/x-api/migrate/overview)를 모았습니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/releasing-a-new-version-of-labs-endpoints/134219)에서 확인할 수 있습니다.
### Compliance Firehose에 Drop/Undrop 이벤트 추가
오늘 Compliance Firehose API에 새로운 drop/undrop 이벤트 유형을 추가했습니다. 자세한 내용은 [문서](/x-api/enterprise-gnip-2.0/fundamentals/firehouse)를 참조하세요.
### Access Token 관리 변경
오늘 [developer.x.com의 응용 프로그램 대시보드](https://developer.x.com/content/developer-twitter/en/apps) 내에서 Access Token 및 Access Token Secret이 표시되고 관리되는 방식을 변경합니다.
API 통합을 더 안전하게 만들기 위해 이러한 값이 처음 생성된 이후에는 대시보드에서 Access Token 및 Access Token Secret을 더 이상 표시하지 않습니다.
처음 이후에는 이러한 자격 증명을 가져올 수 없습니다. 대시보드에서 토큰을 재생성할 수 있지만 이는 현재 토큰과 시크릿을 무효화합니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/upcoming-changes-to-access-token-and-secret-management/130851)에서 확인할 수 있습니다.
### SPDY 지원 제거
2020년 1월 15일부터 X API(및 다른 모든 X 도메인)에 대한 모든 연결은 더 이상 SPDY 연결을 지원하지 않습니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/removing-support-for-spdy-protocol-on-twitter/132530)에서 확인할 수 있습니다.
### Labs에서 Recent Search 엔드포인트 출시
오늘 [지난 7일 동안 게시된 게시물을 검색](/x-api/posts/recent-search)할 수 있는 새로운 엔드포인트를 출시합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-recent-search-endpoint-available-in-labs/133076)를 참조하세요.
### Twurl CLI 업데이트
X API CLI인 `[twurl](https://github.com/twitter/twurl)`의 새로운 업데이트된 메이저 릴리스를 이제 사용할 수 있습니다. 이 릴리스에는 여러 버그 수정 및 개선 사항이 포함되어 있으며, Premium 및 X Developer Labs 엔드포인트 주변의 기능을 추가하는 데 도움이 되는 Bearer Token 지원을 도입합니다. 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/twurl-0-9-5-released/132966)을 참조하세요.
### Streams에 Post Annotations 추가
오늘 X Developer Labs에서 기본 게시물 페이로드에 새로운 메타데이터 요소를 출시합니다. 이러한 새로운 필드는 게시물 페이로드의 일부로 렌더링되며 게시물에 대한 더 많은 맥락 정보를 제공합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/tweet-annotations-added-to-the-tweet-object-for-the-sampled-stream-and-filtered-stream-endpoints-in-labs/132407)에서 확인할 수 있습니다.
### Historical PowerTrack 사용자 프로필 업데이트
오늘 "batch historical posts" 엔드포인트(Historical PowerTrack)를 업데이트하여 작업 처리 시 적용된 값을 반영하는 사용자 프로필 위치, bio 설명 및 표시 이름 정보를 제공합니다. 업데이트된 사용자 객체가 전달되면 User/Actor 객체에 새로운 "updated" 문자열 배열이 있습니다.
최대 3개의 가능한 값이 있습니다: name, description, location:
`"updated": ["name", "description", "location"]`
자세한 내용은 [Historical PowerTrack의 데이터 형식에 대한 문서](https://aem-author-production-version-6-3.twitter.biz/content/developer-twitter/en/docs/tweets/batch-historical/guides/powertrack-data-format.html)를 참조하세요.
### Account Activity API에 추가
오늘 구독한 사용자를 언급하는 계정이 차단되었는지 여부를 볼 수 있는 기능을 개발자에게 제공하는 새로운 기능을 Account Activity API에 출시합니다.
`user_has_blocked` [데이터 객체 구조](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure)에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-release-account-activity-api-user-has-blocked-field/131157)에서 확인할 수 있습니다.
### Labs에서 Sampled Stream 엔드포인트 출시
오늘 게시될 때 모든 공개 게시물의 샘플을 실시간으로 [스트리밍](/x-api/posts/recent-search)할 수 있는 새로운 엔드포인트를 출시합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-sampled-stream-endpoint-available-in-labs/130958)를 참조하세요.
### Labs에서 Filtered Stream 엔드포인트 출시
오늘 X Developer Labs에서 게시물을 가져오기 위한 [새로운 streaming 엔드포인트](/x-api/posts/filtered-stream)와 필터를 관리하는 엔드포인트를 출시합니다. 이러한 엔드포인트를 사용하면 월 최대 500,000개의 게시물(초당 최대 50개의 게시물)을 가져올 수 있습니다. stream에 최대 10개의 필터 규칙을 설정할 수 있습니다(동시에 적용 가능).
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-filtered-stream-endpoints-available-in-labs-and-the-future-of-statuses-filter/129888)에서 확인할 수 있습니다.
API 참조 페이지에 문서화된 요청 매개변수는 이제 선택 사항 또는 필수로 명확하게 표시됩니다. 또한 API 참조 페이지는 요청에 의해 허용되는 경우 JSON 본문 페이로드를 설명합니다.
### Labs에서 Post Metrics 출시
이제 소유/승인된 계정의 게시물 또는 게시물 목록에 대한 engagement 데이터를 가져올 수 있습니다. 쿼리하는 게시물은 30일 이내여야 하며 리포스트가 될 수 없습니다.
[GET /tweets/metrics/private](https://developer.x.com/en/docs/labs/tweet-metrics/overview.html)은 다음 메트릭을 지원합니다:
* `impressions`
* `reposts`
* `quotes`
* `likes`
* `replies`
* `video views`
* `video view quartiles` (요청자가 미디어 작성자이기도 한 경우)
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-twitter-developer-labs-release-metrics-endpoint/129122)를 참조하세요.
### DM 권한 변경
오늘부터 Direct Messages를 생성해야 하는 응용 프로그램은 "Read, Write, and Direct Messages" 앱 권한(RW+DM)을 가져야 합니다. RW 앱 권한만으로 Direct Messages를 생성하려는 응용 프로그램은 다음 오류를 받습니다:
`{"code": 93,"message": "This application is not allowed to access or delete your direct messages."}`
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/updates-to-app-permissions-direct-message-write-permission-change/128221)를 참조하세요.
### Pinned Post 확장 추가
`pinned_tweet_id`는 user 객체 확장을 통해 사용자의 고정된 게시물을 확장합니다.
### Quote Counts 메타데이터 추가
개발자는 새로운 Labs 엔드포인트를 사용하여 인용 수를 가져올 수 있습니다.
### Most Recent Post 확장 추가
`most_recent_tweet_id`는 user 객체 확장을 통해 사용자의 가장 최근 게시물을 확장합니다.
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/update-to-twitter-developer-labs/128060)를 참조하세요.
### TLS 1.2 요구 사항
오늘 X API(및 다른 모든 X 도메인)에 대한 모든 연결은 TLS 1.2를 요구합니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/removing-support-for-legacy-tls-versions-1-0-1-1-on-twitter/126648/2)를 참조하세요.
### 새로운 Account Activity API 엔드포인트
오늘부터 응용 프로그램 전용 OAuth를 사용하여 사용자 구독을 비활성화하는 새로운 [Account Activity API 엔드포인트](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference)를 소개합니다.
이 새로운 엔드포인트는 개발자에게 구독한 사용자의 액세스 토큰을 요구하지 않고 bearer token만 제공하여 구독을 비활성화할 수 있는 편리함을 제공합니다.
3-Legged OAuth로 사용자 구독을 비활성화하는 데 사용된 기존 엔터프라이즈 Account Activity API 엔드포인트를 즉시 사용 중단으로 표시합니다. 이 엔드포인트는 2020년 1월 15일부터 사용 중단되고 더 이상 사용할 수 없게 됩니다.
개발자는 이 API에 대한 자세한 내용을 [문서](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference)에서 확인할 수 있습니다.
### Tweets 엔드포인트에 대한 새로운 확장
\[GET /tweets][https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets.html](https://developer.x.com/en/docs/labs/tweets-and-users/api-reference/get-tweets.html)) 엔드포인트에 두 개의 새로운 확장을 추가했습니다:
`entities.mentions.username`은 게시물에서 인식된 사용자 언급의 사용자 이름을 전체 user 객체로 확장합니다.
`referenced_tweets.id.author_id`는 요청된 게시물 중 하나가 리포스트, 인용 게시물 또는 답글인 경우 참조된 게시물의 작성자 ID를 확장합니다. 이 확장은 참조된 게시물 ID도 전체 객체로 확장합니다.
### Labs에서 Tweets 및 Users 엔드포인트 지원
처음 두 개의 엔드포인트가 Labs 포털을 통해 사용 가능합니다. 이러한 엔드포인트로 시작하려면 승인된 개발자 계정이 있고 Labs 액세스를 신청했는지 확인하세요.
v1.1 동등한 기능과의 [주요 차이점](https://developer.x.com/content/developer-twitter/en/docs/labs/overview/whats-new)은 다음을 포함합니다:
* 단일 객체 "show" 기능과 배치 "lookups"를 위한 단일 엔드포인트
* \[Expansion parameters])는 하나의 요청의 일부로 추가 객체(예: 언급된 사용자, 참조된 게시물 등)의 포함을 지원합니다
* \[Format parameters])는 더 자세하거나 덜 자세한 페이로드로 다른 데이터 프로젝션을 지원합니다
* 인증 방법(사용자 컨텍스트 또는 bearer token)에 관계없이 속도 제한은 앱 수준에 있습니다
이 출시에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/twitter-developer-labs-is-open-to-all-developers/126717)에서 확인할 수 있습니다.
### Terms 및 Privacy 엔드포인트 사용 중단
Terms of Service 및 Privacy 엔드포인트를 완전히 사용 중단했습니다. 우리의 [Privacy Policy](https://x.com/en/privacy) 및 [Terms of Service](https://x.com/en/tos)의 현재 상태는 최신 웹 페이지에서 가장 잘 제공됩니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/terms-of-service-and-privacy-endpoints-will-no-longer-serve-content-after-june-10/125714)를 참조하세요.
### User 객체 필드 변경
오늘 `user.lang`을 포함한 일부 user 객체 필드는 이전에 [포럼 게시물](https://devcommunity.x.com/t/upcoming-changes-to-user-object-and-get-users-suggestions-endpoints/124732)에서 발표된 업데이트된 메타데이터 필드에 대해 'null'을 반환하기 시작합니다.
개발자는 [문서](/x-api/fundamentals/data-dictionary/reference#user)를 통해 이 변경 사항에 대해 알아볼 수 있습니다.
### Account Activity Replay API 출시
오늘부터 [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)의 엔터프라이즈 등급에서 사용할 수 있는 데이터 복구 도구인 [Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)를 소개합니다
[Account Activity Replay API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)를 사용하면 최대 5일 전까지의 이벤트를 가져올 수 있습니다. [webhook](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#api-reference) 서버가 이벤트를 놓치는 시나리오에서 데이터를 복구하는 데 사용해야 합니다
개발자는 이 API에 대한 자세한 내용을 [문서](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)에서 확인할 수 있습니다.
### Quotes에서 네이티브 미디어 지원
오늘부터 네이티브 미디어(사진, 비디오 및 GIF)를 X의 quotes에 추가할 수 있으며, quote 페이로드의 entities 섹션에 추가 미디어 메타데이터로 표시됩니다.
개발자는 [문서](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/tweet)에서 이에 대한 자세한 내용을 알아볼 수 있습니다.
### is:reply 연산자 추가
오늘 `is:reply` 연산자가 [enterprise search APIs](/x-api/enterprise-gnip-2.0/fundamentals/search-api) 및 유료 버전의 [premium search 엔드포인트](https://developer.x.com/content/developer-twitter/en/docs/tweets/search/api-reference/premium-search)와 함께 사용할 수 있게 되었습니다.
`is:reply` 부울 연산자는 게시물에 대한 모든 답글을 필터링하거나 규칙과 일치하는 명시적 답글을 필터링하는 데 사용할 수 있습니다. 이 연산자는 `is:quote` 연산자와 같은 방식으로 작동합니다.
Search API에서는 모든 'is:' 및 'has:' 연산자가 키워드나 해시태그와 같은 독립형 연산자와 함께 사용되어야 한다는 점을 기억하세요.
이 연산자에 대한 자세한 내용은 [문서](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering)에서 확인할 수 있습니다.
### Expanded URL 보강 변경
오늘 expanded URL 보강은 게시물, Moments 또는 프로필로 연결되는 URL에 대해 unwound URL 객체와 메타데이터(title 및 description 필드 포함)를 더 이상 포함하지 않습니다. 다른 URL(웹사이트 등)은 이 메타데이터로 계속 보강되며, url, expanded\_url 및 `display_url`은 계속 사용할 수 있습니다. 이 변경 사항은 [Decahose](/x-api/enterprise-gnip-2.0/fundamentals/decahose-api), [PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api), [Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview) 및 [Search APIs](https://developer.x.com/en/docs/x-api/v1/tweets/search/overview)에 적용됩니다.
### PowerTrack에 is:reply 연산자 추가
오늘 새로운 연산자 `is:reply`를 소개하여 가장 관심 있는 대화로 좁힐 수 있도록 도와드립니다. 이제 결과에서 답글을 필터링할 수 있습니다(리포스트, `is:retweet` 및 인용 게시물, `is:quote`를 필터링하는 기존 기능 외에도). 이 새로운 연산자는 오늘 [PowerTrack](/x-api/enterprise-gnip-2.0/powertrack-api), [Historical PowerTrack](https://developer.x.com/content/developer-twitter/en/docs/tweets/batch-historical/overview) 및 [Replay](/x-api/enterprise-gnip-2.0/powertrack-api#replay-api)에서 사용할 수 있습니다.
`is:reply` 부울 연산자는 게시물에 대한 모든 답글을 필터링하거나 규칙과 일치하는 명시적 답글을 필터링하는 데 사용할 수 있습니다. 이 연산자는 `is:quote` 연산자와 같은 방식으로 작동합니다.
이 연산자에 대한 자세한 내용은 [문서](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering)에서 확인할 수 있습니다.
### Developer Console에서 Apps에 액세스
오늘 X 계정에 로그인한 한 developer.x.com의 [X app 대시보드](https://developer.x.com/content/developer-twitter/en/apps)를 통해 개발자가 기존 [X apps](/resources/fundamentals/developer-apps)를 보고 편집할 수 있는 기능을 추가했습니다. 이전에는 [개발자 계정](/resources/fundamentals/developer-portal)을 신청하거나 승인받은 경우에만 developer.x.com에서 기존 X apps를 보고 편집할 수 있었습니다.
새로운 X apps를 만들려면 여전히 승인된 개발자 계정이 있어야 합니다.
### 비디오 자막 지원
오늘 광고주 및 게시자가 ads.x.com, Media Studio 및 게시자 업로드 API를 통해 비디오에 자막 파일(SRT)을 추가할 수 있다고 발표합니다. 자막은 Android 및 웹에서 자동 재생 비디오(소리가 없는 경우)에서 볼 수 있습니다. iOS 기능은 앞으로 몇 주 안에 출시될 예정입니다.
새로운 자막 엔드포인트에 대한 자세한 내용은 각각의 API 참조 페이지를 검토하세요:
* [POST media/subtitles-create](/x-api/media/create-media-subtitles)
* [POST media/subtitles-delete](/x-api/media/delete-media-subtitles)
### Account Activity API 엔드포인트 업데이트
오늘 [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) 엔드포인트, [GET subscriptions/count](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count)에 대한 업데이트를 발표합니다. 청구 세부 정보 및 API 사용에 대한 가시성을 높이기 위해 오늘부터 Account Activity API 인스턴스와 관련된 프로비저닝된 구독 수를 JSON 내에서 프로그래밍 방식으로 가져올 수 있습니다. 이는 이제 GET subscriptions/count API 엔드포인트를 통해 프로비저닝된 구독 수와 그 한도에 얼마나 가까운지 모두 볼 수 있다는 의미입니다.
이 업데이트는 [Account Activity API 문서](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#get-direct-messages-events-list#get-account-activity-subscriptions-count)에 문서화되어 있습니다.
### POST 엔드포인트에 새로운 속도 제한
오늘 여러 표준 POST 엔드포인트에 새로운 앱 수준 속도 제한을 구현합니다:
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet/:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/get-statuses-retweets-id)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-post-endpoint-rate-limit-enforcement-begins-today/115355)에서 확인할 수 있습니다.
### twitter-text 라이브러리 업데이트
오늘 X가 이모지를 계산하는 방식에 대한 최근 변경 사항을 고려하기 위해 [twitter-text](https://github.com/twitter/twitter-text) 라이브러리에 대한 업데이트를 발표합니다. 이모지가 이전에 2자 이상으로 계산되었다면 이제 그 수는 2자로 줄어들어 사용자가 280자를 최대한 활용할 수 있습니다.
이 변경 사항에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/new-update-to-the-twitter-text-library-emoji-character-count/114607)에서 확인할 수 있습니다.
### 레거시 DM 엔드포인트 사용 중단
레거시 Direct Message 엔드포인트를 완전히 사용 중단했습니다. 사용 중단된 DM 엔드포인트 목록과 대체품은 \[이 페이지]\([https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference에서](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference에서) 찾을 수 있습니다.
이 업데이트에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746)를 참조하세요.
### DM 미디어 액세스 변경
오늘 [Direct Messages에서 첨부된 미디어를 가져오는](https://developer.x.com/en/docs/x-api/v1/direct-messages/message-attachments/overview) 프로세스에 일부 변경 사항을 구현합니다. 인증된 [www.x.com](http://www.x.com) 세션을 통해 `media_url` 또는 `media_url_https`에 액세스하는 것을 더 이상 지원하지 않습니다. `media_url_https`를 가져오는 요청은 OAuth 1.0A를 사용하여 사용자의 액세스 토큰으로 항상 서명되어야 합니다.
이 업데이트에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/direct-message-api-change-to-how-apps-can-access-images-sent-in-direct-messages/112722)를 참조하세요.
### User 및 Site Streams 사용 중단
[User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) 및 [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)를 완전히 사용 중단했습니다.
이 업데이트에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746)를 참조하세요.
### Usage API의 새 버전
오늘 Usage API의 새 버전을 출시합니다. 이 업데이트로 새로운 시스템으로 이동하여 API를 더 안정적으로 만듭니다.
시스템 업데이트로 사용자는 데이터 "구멍"을 경험할 것이며, 개발자는 2018년 5월 1일까지의 데이터만 가져올 수 있습니다. 따라서 향후 1년 동안 몇 개월의 과거 데이터(2019년 6월까지)를 놓치게 됩니다.
Usage API 내에서 제품 이름이 Historical PowerTrack Subscription에서 Historical PowerTrack 2.0으로 변경되어 제품 이름이 다른 사용자 대면 단어와 일관됩니다. 고객은 업데이트로 동일한 형식의 정확히 동일한 데이터를 받게 됩니다. `products.type` JSON 객체 내에서 이 변경 사항을 확인할 수 있습니다.
질문이 있으면 계정 관리자에게 문의하세요.
### API 사용 중단
[Account Activity API DM Beta](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction) 제품이 오늘 완전히 사용 중단되었습니다.
오늘부터 다음 서비스 및 엔드포인트는 성능 저하를 경험합니다:
* [User Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [Site Streams](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)
* [GET direct\_messages](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/list-events)
* [GET direct\_messages/sent](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message)
* [GET direct\_messages/show](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/get-message)
* [POST direct\_messages/new](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/new-message)
* [POST direct\_messages/destroy](https://developer.x.com/content/developer-twitter/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message)
User Streams 및 Site Streams는 8월 23일에 완전히 사용 중단됩니다.
레거시 Direct Messages 엔드포인트는 9월 17일에 완전히 사용 중단됩니다.
이 업데이트에 대한 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/details-and-what-to-expect-from-the-api-deprecations-this-week-on-august-16-2018/110746)를 참조하세요.
### 앱 생성 및 속도 제한 변경
오늘부터 [apps.x.com](https://apps.x.com/)을 통해 새로운 [X apps](/resources/fundamentals/developer-apps)를 더 이상 만들 수 없습니다. 이제 [Developer Console](/resources/fundamentals/developer-portal) 계정으로 리디렉션되거나, Developer Console 계정이 아직 없는 경우 [액세스를 신청할 수 있는 페이지](https://developer.x.com/content/developer-twitter/en/apply-for-access)로 리디렉션됩니다.
또한 2018년 9월 10일에 다음 POST 엔드포인트에 새로운 앱 수준 속도 제한을 구현할 것이라고 발표했습니다.
* [POST statuses/update](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-update)
* [POST statuses/retweet:id](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-statuses-retweet-id)
* [POST friendships/create](https://developer.x.com/en/docs/x-api/v1/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create)
* [POST favorites/create](https://developer.x.com/en/docs/x-api/v1/tweets/post-and-engage/api-reference/post-favorites-create)
* [POST direct\_messages/events/new](https://developer.x.com/en/docs/x-api/v1/direct-messages/sending-and-receiving/api-reference/new-event)
마지막으로, 사람들이 검토를 위해 플랫폼 정책의 의심되는 위반을 보고할 수 있는 새로운 옵션을 소개합니다.
이러한 모든 업데이트에 대한 자세한 내용은 [블로그 게시물](https://cli.re/g32qKr)을 참조하세요.
### Developer Console의 앱 관리
[Developer Console](/resources/fundamentals/developer-portal) 계정이 있는 경우 이제 [X apps](/resources/fundamentals/developer-apps)를 만들고 관리할 수 있습니다. 자세한 내용은 \[포럼 게시물]\([https://devcommunity.x.com/t/app-creation-and-management-now-available-in-the-Developer](https://devcommunity.x.com/t/app-creation-and-management-now-available-in-the-Developer) Console/107723)을 참조하세요.
### Sign in with X 및 Account Activity 변경
오늘 Sign in with X 프로세스와 함께 사용하는 [콜백 URL](/resources/fundamentals/developer-apps#callback-urls)을 등록하도록 요구하기 시작했습니다. 이 업데이트에 대한 자세한 내용은 [여기](https://devcommunity.x.com/t/action-required-sign-in-with-twitter-users-must-whitelist-callback-urls/105342)에서 확인할 수 있습니다.
또한 Account Activity API에 `tweet_delete_events` 활동을 추가한다고 발표했습니다. 이 새로운 활동은 해당 삭제된 이벤트에 대해 전송되어 개발자가 고객 및 응용 프로그램 사용자에게 더 쉽게 규정 준수 경험을 제공할 수 있도록 합니다. 이 새로운 활동에 대한 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/adding-delete-events-to-the-account-activity-api/106783) 또는 [문서](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)에서 확인할 수 있습니다.
### Terms 및 Policies 업데이트
오늘 [Terms of Service](https://x.com/en/tos), [Privacy Policy](https://x.com/en/privacy) 및 \[X Developer Agreement][https://developer.x.com/en/developer-terms/agreement-and-policy에](https://developer.x.com/en/developer-terms/agreement-and-policy에) 개인정보 보호, 보안 및 데이터 보호 업데이트를 포함한 일부 변경 사항을 적용했습니다. 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)을 참조하세요.
### Timezone 필드 비공개화
오늘 X user 객체의 timezone 값이 비공개 필드가 되었습니다. 지금부터 모든\* `time_zone` 및 `utc_offset` 데이터 객체는 null로 반환됩니다. 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)을 참조하세요.
\* 이는 인증된 사용자에 대해서만 `account/settings` 엔드포인트에서 계속 사용할 수 있습니다.
### Klout 데이터 제거
오늘 GDPR 업데이트의 일환으로 게시물 페이로드에서 모든 Klout 데이터를 제거했습니다.
### Profile Background 및 Account Activity 변경
오늘 `profile_background_image_url` 및 `profile_background_image_url_https`의 모든 인스턴스를 기본값으로 변경합니다. 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)을 참조하세요.
위의 변경 사항 외에도 [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) 페이로드에 활동이 전달된 구독을 참조하는 새로운 필드를 추가합니다. 이 JSON 객체는 `for_user_id`라고 하며 해당 활동을 생성한 구독한 사용자의 ID를 값으로 포함합니다. 이 새로운 JSON 객체의 예는 [account activity 객체](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#account-activity-data-object-structure) 페이지에서 확인할 수 있습니다.
### Quote 페이로드 렌더링 변경
오늘 quote 페이로드에서 URL이 렌더링되는 방식에 변경 사항을 추가합니다.
인용된 게시물을 참조할 수 있도록 "quoted\_status\_permalink"라는 새로운 엔티티를 추가하고 인용된 게시물의 "text" 필드에서 t.co 링크를 제거합니다.
새 형식에서는 t.co 링크가 "quoted\_status" 객체의 인용된 게시물의 "text" 필드에 더 이상 추가되지 않습니다.
또한 인용된 게시물의 t.co url, expanded\_url 및 display\_url을 'urls' 엔티티에 더 이상 넣지 않습니다. 대신 "url", "expanded" 및 "display" URL 속성과 함께 새로운 "quoted\_status\_permalink" 객체에 추가됩니다. 이는 "quoted\_status\_permalink" 객체가 인용된 게시물로 돌아가는 t.co 링크에 예약되는 반면, "entities.urls" 배열은 원본 게시물이나 quote 내에서 공유된 모든 링크를 식별하는 데 사용할 수 있음을 의미합니다.
자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/updating-how-urls-are-rendered-in-the-quote-tweet-payload/105473) 및 [업데이트된 문서](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)를 참조하세요.
### X Kit 사용 중단
[X Kit](https://developer.x.com/en/docs/x-for-websites)의 사용 중단 발표. 2018년 10월 31일 이후 X Kit는 더 이상 적극적으로 유지 관리되지 않습니다. 자세한 내용은 [블로그 게시물](https://blog.x.com/developer/en_us/topics/tools/2018/discontinuing-support-for-twitter-kit-sdk.html)을 참조하세요.
### GDPR을 위한 플랫폼 업데이트
오늘 GDPR과 관련된 플랫폼에 대한 여러 업데이트를 발표했습니다. 자세한 내용은 [포럼 게시물](https://devcommunity.x.com/t/upcoming-changes-to-the-developer-platform/104603)을 참조하세요.
### Additional Media Info 객체 추가
post 페이로드에 새로운 객체인 `additional_media_info` 객체를 추가하고 광고주가 비디오 재생을 X 소유 클라이언트로 제한하도록 요청한 홍보 게시물에 대해 일부 비디오 세부 정보(`video_info`)도 제한합니다. 이 변경 사항에 대한 추가 정보는 다음 링크에서 확인할 수 있습니다: [Extended Entities Objects > 네이티브 비디오가 있는 게시물](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities).
### Premium Full-Archive Search 출시
[premium full-archive search 엔드포인트](https://blog.x.com/developer/en_us/topics/tools/2018/access-the-full-history-of-tweets.html) 출시.
### Account Activity APIs 출시
([All Activities](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)) 및 ([Direct Messages](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)) Standard beta Account Activity APIs를 모두 출시했습니다. 이 출시에 대한 자세한 내용은 [블로그](https://blog.x.com/developer/en_us/topics/tools/2017/announcing-more-functionality-to-improve-customer-engagements-on-twitter.html)에서 확인하세요. User streams 및 Site streams 사용 중단 및 2018년 6월 19일(화) 종료 날짜를 발표했습니다.
### twitter-text 라이브러리 업데이트
twitter-text 버전 2.0이 이제 [GitHub](https://github.com/twitter/twitter-text)에서 사용 가능합니다. 이 업데이트는 2017년 11월 7일에 출시된 문자 제한 변경 사항을 다룹니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/shipped-twitter-text-2-0/98577)을 방문하세요.
### Premium APIs 출시
Premium APIs를 출시했습니다.
이러한 새로운 APIs는 엔터프라이즈 데이터 플랫폼의 품질과 안정성을 기반으로 하며, 계층화된 가격 모델을 통해 더 폭넓게 사용할 수 있습니다. 처음으로 30일 동안의 게시물(표준 엔드포인트의 제한된 7일 데이터 대신)을 검색할 수 있으며, 선택적으로 profile geo, URL 확장 및 폴 데이터에 대한 premium 보강에 액세스할 수도 있습니다. 다음은 새로운 기능 중 일부의 맛보기입니다:
* 요청당 더 많은 게시물(Sandbox + Premium)
* 더 복잡한 쿼리를 허용하는 훨씬 풍부한 쿼리 언어(Sandbox + Premium)
* 게시물의 시계열 카운트를 반환하는 counts 엔드포인트(Premium)
* Expanded URLs 및 Profile Geo와 같은 메타데이터 보강(Premium)
이 출시에 대한 자세한 내용은 [블로그](https://blog.x.com/developer/en_us/topics/tools/2017/introducing-twitter-premium-apis.html)에서 확인하세요.
### 280자 게시물 출시
cramming이 문제였던 언어에서 280자 게시물의 공식 출시. 자세한 내용은 [포럼 공지](https://devcommunity.x.com/t/updating-the-character-limit-and-the-twitter-text-library/96425) 또는 공식 [블로그 게시물](https://blog.x.com/official/en_us/topics/product/2017/tweetingmadeeasier.html)을 참조하세요.
### Statuses/Update에서 DM 명령 제거
`statuses/update` API 엔드포인트를 통해 Direct Messages를 전송하는 기능이 완전히 제거되었으며, `enable_dm_commands` 및 `fail_dm_commands` 매개변수는 더 이상 효과가 없습니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653 "on our forum")을 참조하세요.
### OAuth 로그인 흐름 변경
X의 백엔드 OAuth API 엔드포인트에 변경 사항이 적용되어 `/oauth/authenticate` 엔드포인트의 동작이 `/oauth/authorize` 엔드포인트의 동작과 일치하도록 변경되었습니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/recent-changes-to-twitter-s-oauth-login-flow-and-api-endpoints/94943)을 참조하세요.
### Engagement API 메트릭 업데이트
Engagement API가 X 분석 대시보드에서 사용 중인 동일한 메트릭 집계 방법론을 사용하도록 업데이트되었습니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/changes-to-the-engagement-api/94523)을 참조하세요.
### DM 명령 실패 변경
DM `statuses/update` 엔드포인트 내의 `fail_dm_commands` 매개변수의 기본값이 *true*로 변경되었습니다. Direct Messages로 의도된 모든 상태 업데이트는 오류를 반환하기 시작합니다(`enable_dm_commands`가 *false*인 경우 게시물이 게시됩니다). 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653)을 참조하세요.
### 280자 트윗 처리
280자 트윗에 대한 응답 페이로드는 긴 트윗과 동일한 방식으로 처리됩니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/testing-280-characters-for-certain-languages/94126)을 참조하세요.
### Additional Media Info 추가
게시물 페이로드에 새로운 데이터(`additional_media_info object`)를 추가하고 광고주가 비디오 재생을 X 소유 클라이언트로 제한하도록 요청한 홍보 게시물에 대해 일부 비디오 세부 정보(`video_info`)도 제한합니다. 이 변경 사항에 대한 추가 정보는 다음 링크에서 확인할 수 있습니다: [Extended Entities Objects > 네이티브 비디오가 있는 게시물](https://developer.x.com/en/docs/x-api/v1/data-dictionary/object-model/extended-entities)
### 30-Day Search에서 url\_contains 연산자 지원 종료
30-Day 및 Full-Archive Search에서 `url_contains:` 연산자 지원이 종료되었습니다. 이 연산자의 사용 중단은 2016년 8월 Gnip 2.0 마이그레이션의 일환으로 발표되었습니다. `url_contains:` 연산자를 사용하는 모든 Search 쿼리는 잘못된 것으로 거부됩니다.
### Search APIs에서 url\_contains 연산자의 향후 제거
30-Day Search API(30-Day 및 Full-Archive 모두)는 오늘부터 30일 이후 또는 2017년 8월 4일 이후 `url_contains:` 연산자를 더 이상 지원하지 않습니다(`url_contains:` 지원은 실제로 해당 날짜 이후 첫 번째 배포로 종료됩니다). 이 연산자의 사용 중단은 2016년 8월 Gnip 2.0 마이그레이션의 일환으로 발표되었습니다. 연산자 지원이 종료되면 `url_contains:`를 사용하는 모든 쿼리가 잘못된 것으로 거부됩니다.
### xAuth 사용 중단
xAuth 인증 메커니즘이 모든 X APIs에서 제거되었습니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/retirement-of-xauth/88022)을 참조하세요.
### HTTP 헤더 소문자 강제
모든 HTTP 헤더(`content-type`, `x-rate-limit-remaining`, `x-access-level` 등)가 소문자로 강제되었습니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/upcoming-http-header-changes/86715)을 참조하세요.
### DM 명령에 대한 선택적 매개변수
`statuses/update`에 대한 선택적 `enable_dm_commands` 매개변수를 사용하면 응용 프로그램이 전환 기간이 종료되기 전에 일찍 DM 명령 지원을 제거할 수 있습니다. 기본값은 *true*(즉, 현재 레거시 동작)이지만, 새로운 11월 1일 이후 동작을 얻으려면 *false*로 설정할 수 있습니다. `statuses/update`에 대한 선택적 `fail_dm_commands` 매개변수를 *true*로 설정하면 DM 명령이 API에서 HTTP 403(오류 코드 151)을 반환합니다. 기본값은 *false*입니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/retiring-legacy-dm-commands-on-the-standard-tweet-api/86653)을 참조하세요.
### 규칙에서 이모지 지원
이모지가 있는 규칙이 이제 엔터프라이즈 Search APIs에서 사용 가능합니다
### Direct Message APIs의 폭넓은 가용성
여러 새로운 Direct Message APIs에 대한 액세스가 이제 더 폭넓게 사용 가능합니다. 이 업데이트에 대한 자세한 내용은 [블로그](https://blog.twitter.com/developer/en_us/topics/tools/2017/new-apis-to-power-the-future-of-customer-engagement-in-direct-me.html)에서 확인하세요.
### MPEG-DASH 비디오 지원 사용 중단
MPEG-DASH URLs(.mpd)가 비디오를 포함하는 게시물의 페이로드에서 제거되었습니다. 이 업데이트에 대한 자세한 내용은 [포럼](https://devcommunity.x.com/t/retiring-mpeg-dash-video-support-on-march-9th-2017/82761)을 참조하세요.
### 새로운 보강 및 페이로드 변경
새로운 보강! Poll Metadata가 이제 엔터프라이즈 APIs를 통해 사용 가능합니다. 자세한 내용은 [문서](/x-api/enterprise-gnip-2.0/fundamentals/account-activity#migration-introduction)를 참조하세요.
새로운 페이로드 필드: 사용자가 게시물에 사진을 추가할 때 "Add description" 옵션을 선택하는 경우 Image Alt-Text(description) 필드가 페이로드의 `entities.media[]` 및 `extended_entities.media[]` 섹션에 존재할 수 있습니다. 이는 enriched native format에서만 사용할 수 있습니다.
기본 페이로드 형식: Gnip 제품에서 새로 생성된 스트림은 이제 기본적으로 original format JSON으로 설정됩니다.
### Historical PowerTrack 및 Replay API 업데이트
Historical PowerTrack API 및 Replay API
* quote 필터링이 이제 지원됩니다
* 인용된 게시물이 이제 HPT 및 Replay 게시물 페이로드 내에서 완전히 재수화됩니다
### Counts에 대한 새로운 페이로드 필드
새로운 페이로드 필드: `quote_count` 및 `reply_count`가 이제 Realtime 및 Historical APIs 전반에 걸쳐 native enriched format 페이로드에서 사용 가능합니다
### Full-Archive Search에서 Geo 연산자 지원
Full-Archive Search API(FAS):
* 추가 geo 연산자에 대한 지원 추가:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
### PowerTrack에서 ID로 규칙 관리
규칙 ID로 규칙 관리(GET 및 DELETE)가 이제 PowerTrack 2.0 및 PowerTrack Replay 2.0에서 사용 가능합니다
### 30-Day Search에서 Geo 연산자 지원
30-Day Search API:
* 추가 geo 연산자에 대한 지원 추가:
* place:
* place\_country:
* has:profile\_geo:
* profile\_country:
* profile\_region:
* profile\_locality:
# 개발자 가이드라인
Source: https://docs.x.com/ko/developer-guidelines
X API 개발자 정책과 가이드라인으로, 허용된 사용 사례와 제한된 행위, 준수 요구 사항, 앱 배포 및 사용자 데이터 처리에 대한 모범 사례, 정책 위반 시 발생하는 앱 정지, API 액세스 취소, 영구 계정 차단 결과를 자세히 안내합니다.
**위반 시 앱 정지, API 액세스 취소, 영구 계정 차단이 발생할 수 있습니다.** 빌드하기 전에 항상 공식 정책을 검토하세요.
API 액세스에 대한 구속력 있는 법적 약관
X에서 빌드할 때 따라야 할 규칙
봇을 위한 구체적인 규칙
금지된 활동
***
## 빠른 체크: 내 앱은 허용되나요?
빌드하기 전에 다음 질문에 답해보세요. 어느 하나라도 \*\*"아니오"\*\*라면 앱이 X 정책을 위반할 가능성이 있습니다.
상호 작용의 경우, 사용자가 **명시적으로 요청**했나요?
앱의 목적과 동작이 **사용자에게 명확**한가요? (자동화 계정은 라벨이 지정되어야 합니다.)
사용자가 진행 중인 모든 상호 작용에서 **쉽게 옵트아웃**할 수 있나요?
자기 홍보를 넘어 **실질적인 가치**를 제공하나요?
**공식 API만 사용**하고 있나요? (스크래핑/브라우저 자동화 없이)
**속도 제한 내**에서 운영하며 사용 정책을 준수하나요?
의심스러울 때는 "사용자가 이 경험에 만족할까?"라고 자문하세요. 그렇지 않다면 접근 방식을 다시 검토하세요.
***
## 일반적인 시나리오: 허용되나요?
허용되는 사항을 이해하는 데 도움이 되는 실제 예시입니다. **이러한 규칙은 모든 앱에 적용됩니다** — 봇, 모바일 앱, 웹 통합, 브라우저 확장 프로그램, 분석 대시보드 또는 X API를 사용하는 모든 도구에 해당합니다.
| 시나리오 | 허용? | 이유 |
| ---------------------------------------- | :--------------------------: | -------------------- |
| 자동화 계정이 예약된 콘텐츠(뉴스, 날씨, 인용구)를 게시 | | 정보 제공, 원치 않는 멘션 없음 |
| 앱이 사용자를 대신하여 RSS 피드 업데이트를 게시 | | 유용한 방송 |
| 알림 서비스가 지진/재난 알림을 게시 | | 공공 안전 가치 |
| 스포츠 앱이 게임 업데이트를 사용자 타임라인에 게시 | | 정보 제공 |
| 앱이 주식/암호화폐 가격을 일정에 따라 게시 | | 정보 제공, 조작 없음 |
| 앱이 여러 계정에 걸쳐 동일한 콘텐츠를 게시 | | 스팸 / 플랫폼 조작 |
| 앱이 가시성을 얻기 위해 트렌드 주제에 게시 | | 트렌드 조작 |
| 도시별 알림 계정 다수(예: @WeatherNYC, @WeatherLA) | | 허용 — 중복되지 않는 위치별 콘텐츠 |
| 시나리오 | 허용? | 이유 |
| --------------------------------- | :----------------------------------: | ----------------------------------------------------- |
| 앱이 도움을 요청하는 @멘션에 응답 | | 사용자가 시작한 요청 |
| 앱이 키워드를 멘션하는 누구에게나 자동 답글 | | 원치 않는 상호 작용 |
| 앱이 게시물에 답글을 단 사용자에게 자동 답글 | | 사용자가 먼저 참여 — 답글 1개 제한. [조건 적용](#gray-areas-explained) |
| AI 기반 앱이 답글을 생성하여 게시 | | X의 **사전 승인** 필요 |
| 앱이 무작위 사용자에게 "더 보려면 팔로우하세요!"라고 답글 | | 스팸, 원치 않는 |
| 멘션 시 스레드를 풀어주는 유틸리티 앱 | | 사용자가 시작한 유틸리티 |
| 시나리오 | 허용? | 이유 |
| ---------------------------------- | :--------------------------: | ----------------------------------------------- |
| 앱이 유용한 정보로 DM에 응답 | | 사용자가 시작 |
| 사용자가 먼저 DM할 때 앱이 제휴 링크를 전송 | | 사용자가 시작 — 공개 필요. [조건 적용](#gray-areas-explained) |
| 앱이 신규 팔로워에게 환영 메시지를 자동 DM | | 팔로워에게도 원치 않는 |
| 앱이 제품 출시에 대해 사용자에게 대량 DM | | 스팸 |
| 사용자 DM 후 지원 통합이 "어떻게 도와드릴까요?"라고 묻기 | | 사용자가 시작한 대화 |
| 시나리오 | 허용? | 이유 |
| --------------------------------- | :--------------------------: | ---------------------------------------------------- |
| 서드파티 앱이 사용자가 게시물의 좋아요 버튼을 누르도록 허용 | | 앱을 통해 사용자가 시작 |
| 앱이 해시태그를 포함한 게시물을 자동으로 좋아요 | | 자동화, 사용자 시작 아님 |
| 모바일 앱에 선택한 사용자를 위한 "자동 좋아요" 기능 | | 자동화, 사용자 시작 아님 |
| 좋아요를 판매하거나 "대량 좋아요" 패키지를 제공하는 서비스 | | 참여 판매 금지 |
| 앱이 큐레이션된 리스트에서 콘텐츠를 리포스트 | | 정보 목적으로 OK, 대량 스팸 없음. [조건 적용](#gray-areas-explained) |
| 성장 도구가 청중을 늘리기 위해 계정을 대량 팔로우 | | 조작 |
| 앱이 자신을 팔로우하는 누구에게나 맞팔로우 | | 대량/공격적 팔로우 |
| 앱이 사용자를 리스트에 대량 추가 | | 무차별적 리스트 조작 |
**좋아요는 인증된 사용자가 직접 시작해야 합니다.** 키워드, 해시태그, 사용자 또는 일정에 따른 자동 좋아요를 포함한 자동화, 대량 또는 무차별적인 좋아요는 금지됩니다. 앱은 "자동 좋아요" 기능을 제공하거나 좋아요를 서비스로 판매할 수 없습니다. 이는 봇, 모바일 앱, 브라우저 확장 프로그램 또는 모든 통합 등 모든 앱에 적용됩니다.
| 시나리오 | 허용? | 이유 |
| ------------------------- | :----------------------------------: | -------------------------------------------------- |
| 요청 시 앱이 제품 추천을 전송 | | 사용자가 시작 |
| 앱이 무작위 게시물에 제휴 링크로 답글 | | 원치 않는 스팸 |
| 응모를 위해 팔로우/리트윗을 요구하는 경품 앱 | | 위험 — 참여 조작으로 간주될 수 있음 |
| 좋아요/팔로우/리트윗을 판매하는 서비스 | | 엄격히 금지 |
| 사용자 요청 시 암호화폐를 전송하는 팁 서비스 | | 사용자가 시작 — 금융 규제 준수. [조건 적용](#gray-areas-explained) |
| 시나리오 | 허용? | 이유 |
| ---------------------------- | :--------------------------: | ------------------ |
| 앱이 분석 대시보드를 위해 브랜드 멘션을 추적 | | 유효한 사용 사례 |
| 앱이 브라우저 자동화로 X를 스크래핑(API 아님) | | **영구 정지** — API 전용 |
| 앱이 AI/ML 모델 훈련을 위해 X 데이터를 저장 | | 금지(Grok 제외) |
| 앱이 30일 내 150만 개 초과의 게시물을 재배포 | | 재배포 제한 초과 |
| 앱이 X 성과를 경쟁사와 벤치마킹 | | 금지된 경쟁 분석 |
| 공개 대화 트렌드에 대한 학술 연구 | | 적절한 데이터 처리와 함께 유효 |
**비API 자동화(스크래핑, 브라우저 자동화)는 영구 정지로 이어집니다.** 항상 공식 X API를 사용하세요.
***
## 금지된 활동
이러한 활동은 앱 정지 또는 영구 차단으로 이어집니다. 예외는 없습니다.
| 카테고리 | 예시 |
| ------------- | ------------------------------------- |
| **스팸 & 조작** | 계정 간 동일한 콘텐츠, 가짜 참여, 트렌드 조작, 대량 게시 |
| **원치 않는 접촉** | 무작위 사용자에 대한 자동 답글, 대량 DM, 초대받지 않은 @멘션 |
| **기만적인 봇** | 사람 사칭, 봇 신원 숨김, 오해의 소지가 있는 링크/리다이렉트 |
| **참여 판매** | 좋아요, 팔로우, 리트윗 또는 조회수를 판매하는 앱 |
| **속도 제한 남용** | 제한 초과, 과도한 사용을 조장하는 앱 설계 |
| **비API 자동화** | 브라우저 스크립팅, 스크래핑, 공식 API 외의 모든 자동화 |
| **계정 농장** | 동일한 중복 목적을 위한 여러 계정 |
| **감시** | 동의 없이 사용자 프로파일링, 추적 또는 모니터링 |
| **무단 AI 훈련** | X 데이터로 ML 모델 훈련(Grok 제외) |
| **민감 데이터 추론** | 건강, 정치, 종교 또는 기타 민감한 속성 추론 |
| **과도한 재배포** | 30일 기간 동안 150만 개 초과 Post ID 공유 |
***
## 자동화 규칙
이 섹션은 사용자를 대신하여 게시, 답글 또는 상호 작용하는 **자동화 계정**(봇)에 특별히 적용됩니다. 분석 대시보드, 연구 도구 또는 기타 비자동화 앱을 구축하는 경우 이러한 라벨링 요구 사항은 적용되지 않지만 기술적 제한은 여전히 적용됩니다.
### 자동화 계정의 요구 사항
X API를 사용하는 모든 자동화 계정은 다음 요구 사항을 충족해야 합니다:
이 라벨은 봇 프로필의 이름/핸들 아래에 나타납니다. 투명성을 보장하기 위해 앱 설정에서 활성화하세요.
봇임을 명확히 밝히고 운영자가 누구인지 명시하세요. 예: *"@yourcompany가 운영하는 봇"* 또는 *"Example Inc.가 관리하는 자동화 계정"*.
책임 및 연락 목적으로 봇은 사람이 관리하는 계정과 연결되어야 합니다.
사용자가 "중지"라고 말하면 중지하세요. 일반적인 옵트아웃 문구에 대한 키워드 감지를 구현하세요.
스크래핑, 브라우저 자동화 또는 비공식 방법 금지. 위반 시 영구 정지됩니다.
속도 제한을 우회하거나 남용하지 마세요. 제한을 우아하게 처리하도록 앱을 설계하세요.
### 자동화 작업: 허용되는 것은?
| 작업 | 허용? | 규칙 |
| ------------ | :----------------------------------: | ------------------------------------------- |
| **트윗 게시** | | 원치 않는 @멘션 없음. 동일한 크로스 포스팅 없음. |
| **사용자에게 답글** | | 사용자가 먼저 참여한 경우에만. **상호 작용당 최대 답글 1개**. |
| **DM 전송** | | 사용자가 먼저 DM한 후에만. 쉬운 옵트아웃 필요. |
| **게시물 좋아요** | | 사용자가 직접 시작해야 함. 자동 좋아요, 대량 좋아요, 좋아요 판매는 금지. |
| **리포스트** | | 정보/엔터테인먼트 목적으로 OK. 대량 스팸 없음. |
| **인용 트윗** | | 리포스트와 동일한 규칙 — 스팸이나 조작 없음. |
| **팔로우/언팔로우** | | 대량, 공격적 또는 자동화된 팔로우 없음. |
| **리스트에 추가** | | 대량 또는 무차별적 추가 없음. |
| **북마크** | | 개인/자동화 사용에 적합. |
| **검색/읽기** | | 속도 제한 내 표준 사용. |
***
## 회색 영역 설명
많은 개발자가 경계 사례에 대해 질문합니다. 일반적인 회색 영역에 대한 가이드입니다.
**다음의 경우 허용:**
* 사용자가 명시적으로 요청(예: 추천을 요청하는 DM)
* 제휴/스폰서십 관계를 명확히 공개
* 링크가 오해의 소지가 없음(기만적 리다이렉트 없음)
**다음의 경우 금지:**
* 무작위 게시물에 제휴 링크로 자동 답글
* 요청하지 않은 사용자에게 DM
* 상업적 관계를 숨김
* 배포 전 **X의 사전 승인 필요**
* 모든 규칙을 여전히 준수해야 함(원치 않는 멘션 없음, 적절한 라벨 부착)
* 시작하기 전에 [Policy Support form](https://help.x.com/forms/platform)을 통해 X에 문의
* 승인을 받았더라도 사람을 사칭할 수 없음
승인 없이 AI 생성 답글을 배포하는 것은 콘텐츠 자체가 유용하더라도 위반입니다.
자동화된 DM으로는 **허용되지 않습니다** — 사용자가 팔로우했더라도 원치 않는 접촉으로 간주됩니다.
**대안:**
* 신규 팔로워를 환영하는 고정 트윗
* 소개 정보와 링크가 있는 bio
* 사용자가 먼저 DM할 경우에만 자동 답글
**다음의 경우 허용:**
* 각 계정이 **중복되지 않는** 목적을 수행(예: @EarthquakeJP, @EarthquakeCA)
* 콘텐츠가 의미 있게 다름(위치별, 언어별)
* 제한을 우회하거나 동일한 메시지를 증폭하는 데 사용되지 않음
**다음의 경우 금지:**
* 계정 간 동일/유사한 콘텐츠 게시
* 정지 또는 속도 제한을 회피하기 위해 생성
**다음의 경우 허용:**
* 사용자가 시작(멘션, DM 또는 명시적 옵트인)
* 명확한 옵트아웃 메커니즘 존재
* 응답이 유용하고 홍보성이 아님
* DM에 개인정보 처리방침 링크 포함
**다음의 경우 금지:**
* 공개적으로 불만을 제기한 사용자에게 접근(원치 않는)
* 응답이 주로 홍보성임
**주의해서 진행:**
* 응모 조건으로 팔로우/리트윗을 요구하면 참여 조작으로 간주될 수 있음
* [X의 콘테스트 가이드라인](https://help.x.com/en/rules-and-policies/x-contest-rules)을 준수해야 함
* 증폭을 위해 여러 계정을 사용하지 마세요
* 상품이 실제로 존재하고 전달되도록 하세요
특정 문구로 답글을 다는 등 참여 활동이 필요 없는 응모 방법을 고려하세요.
***
## 데이터 처리 및 표시 요구 사항
이러한 요구 사항은 개발자 계약에 따라 법적 구속력이 있습니다. 미준수 시 종료 및 법적 조치로 이어질 수 있습니다.
### 콘텐츠 삭제
요청 시 시스템에서 X 콘텐츠를 삭제해야 합니다:
| 트리거 | 기한 |
| --------------- | -------------------------------- |
| X가 삭제를 요청 | **24시간** |
| 사용자가 삭제를 요청 | **24시간** |
| X에서 콘텐츠가 정지/제거됨 | **24시간** |
| API 액세스가 종료됨 | **영업일 기준 10일** (모든 X 데이터 삭제해야 함) |
실시간 삭제 이벤트를 수신하고 자동으로 준수 상태를 유지하려면 [Compliance Firehose](https://docs.x.com/x-api/compliance/streams)를 사용하세요.
### Off-X 매칭
**Off-X 매칭**은 X 데이터(사용자명, 사용자 ID, 게시물)를 플랫폼 외부 식별자(고객 데이터베이스, 이메일 리스트, 디바이스 ID 등)와 연결하는 것을 의미합니다.
**명시적 옵트인 동의가 있을 때 허용:**
* 사용자가 자신의 X 계정을 서비스와 연결하는 데 명시적으로 동의
* 어떤 데이터가 매칭되며 그 이유에 대한 명확한 공개
**동의 없이 매칭할 수 있는 것은 다음만 가능:**
* 사용자가 직접 제공한 정보
* 공개적으로 사용 가능한 X 데이터(게시물, bio, 표시명, 사용자명)
* 전문 디렉토리 같은 공개 리소스
**사용자가 놀랄 만한 매칭은 절대 하지 마세요.**
### 민감 데이터
다음 카테고리의 X 사용자에 대한 정보를 **추론하거나, 유추하거나, 저장할 수 없습니다**:
| 카테고리 | 예시 |
| ------------- | ----------------- |
| **건강** | 의학적 상태, 임신, 장애 |
| **재정 상태** | 부정적 재정 상태, 신용 문제 |
| **정치** | 정당 소속, 정치적 신념, 투표 |
| **인종/민족** | 출신, 민족성 |
| **종교/철학** | 신념, 소속 |
| **성생활/성적 지향** | 성에 대한 모든 추론 |
| **노동조합** | 회원 가입 또는 소속 |
| **범죄** | 혐의가 있거나 실제 범죄 활동 |
**예외:** 개인 식별자(사용자 ID, 사용자명 또는 연결 가능한 데이터 없음)를 저장하지 않는 집계 분석은 적용 가능한 법률에 따라 연구 목적으로 허용될 수 있습니다.
### X 콘텐츠 표시
| 요구 사항 | 세부 정보 |
| ------------- | -------------------------------------------------------------------------------------------- |
| **출처 표시** | 적절한 X 브랜딩을 사용하세요. [Brand Guidelines](https://about.x.com/en/who-we-are/brand-toolkit)을 따르세요. |
| **변경 금지** | 표시 형식(크기 조정)에만 수정하세요. 콘텐츠를 편집하거나, 타임스탬프를 제거하거나, 메타데이터를 제거하지 마세요. |
| **iframe 금지** | iframe에서 X 콘텐츠를 표시하지 마세요. 공식 임베드를 사용하거나 직접 렌더링하세요. |
| **제거 존중** | X에서 삭제된 경우 24시간 이내에 콘텐츠를 제거하세요. |
***
## 기술적 제한
이러한 제한은 모든 개발자에게 적용됩니다. 초과 시 속도 제한 또는 정지로 이어질 수 있습니다.
| 제한 | 한도 |
| ---------------------- | -------------------------------------------------------------- |
| **Post ID 재배포** | 30일 기간당 단일 엔티티에 대해 최대 150만 Post ID |
| **하이드레이션된 콘텐츠 재배포** | 수신자당 일일 최대 50,000개의 하이드레이션된 게시물 또는 사용자 |
| **속도 제한** | 엔드포인트 및 티어별로 다름 — [API 문서 참조](/x-api/fundamentals/rate-limits) |
| **AI/ML 훈련** | 금지(Grok 제외) |
| **비API 액세스** | 금지 — 스크래핑 및 브라우저 자동화 = 영구 차단 |
| **경쟁사 벤치마킹** | 금지 — X 성과를 경쟁사와 비교할 수 없음 |
| **동일한 사용 사례에 대한 여러 앱** | 금지 — 제한을 우회하기 위해 중복 앱을 만들지 마세요 |
### 특수 사용 사례
| 사용 사례 | 요구 사항 |
| ------------------------------ | --------------------------------- |
| **정부 사용** | Enterprise 티어 필요 |
| **상업적 사용** | 적절한 유료 티어 필요; 무료 티어는 비상업적 전용 |
| **학술 연구** | 다른 재배포 제한이 있을 수 있음; 자세한 내용은 X에 문의 |
| **EU Digital Services Act 연구** | 특정 비상업적 연구 조항 사용 가능 |
***
## 보안 및 준수
개발자로서의 의무 사항:
* X 데이터를 보호하기 위해 **업계 표준 보안** 관행 사용
* API 자격 증명 또는 토큰을 절대 공유하지 마세요
* 자격 증명을 안전하게 저장하세요(환경 변수, 비밀 관리자 — 코드에 저장하지 않음)
* 앱에 적절한 인증을 구현하세요
X 데이터와 관련된 보안 침해가 발생한 경우:
* **X에 즉시 알림**
* 침해를 완화하기 위한 조치 수행
* X의 조사에 협조
* X에서 받은 비공개 정보는 기밀로 취급
* API 속도 제한, X 내부 데이터 또는 비공개 기능을 공개하지 마세요
* 경쟁 목적으로 기밀 정보를 사용하지 마세요
* X는 **연 1회까지** 준수 여부를 감사할 수 있음
* 합리적인 액세스 및 문서를 제공해야 함
* X 데이터 사용 방법에 대한 기록 유지
***
## 요약: 해야 할 것과 하지 말아야 할 것
**자동화 계정의 경우:**
* "자동화" 프로필 라벨 활성화
* bio에 운영자 공개
* 사용자가 상호 작용을 시작할 때까지 대기
* 쉬운 옵트아웃 제공
* AI 생성 답글에 대한 승인 받기
**모든 앱의 경우:**
* 공식 X API만 사용
* 속도 제한 및 재배포 제한 존중
* 요청 시 24시간 이내에 콘텐츠 삭제
* Off-X 매칭에 대한 옵트인 동의 받기
* X 콘텐츠를 표시할 때 적절한 출처 표시
* 자격 증명을 안전하게 보관하고 침해 시 X에 알림
* X 데이터 사용에 대한 기록 유지
**자동화 계정의 경우:**
* 자동화된 성격 숨기기
* 원치 않는 DM, 답글 또는 @멘션 보내기
* "중지" 요청 무시
* 계정 간 동일한 콘텐츠 게시
* 자동 좋아요, 대량 좋아요 또는 좋아요 판매(좋아요는 사용자가 시작해야 함)
**모든 앱의 경우:**
* 스크래핑 또는 브라우저 자동화 사용
* X 데이터로 AI/ML 모델 훈련(Grok 제외)
* 민감한 사용자 데이터 추론(건강, 정치, 종교 등)
* 동의 없이 X 데이터를 플랫폼 외부 ID에 매칭
* iframe에서 X 콘텐츠 표시
* 허용된 제한을 초과하여 재배포
* 동일한 사용 사례에 대해 여러 앱 만들기
* 감시 또는 사용자 추적에 X 데이터 사용
# 정책 및 계약
Source: https://docs.x.com/ko/developer-terms
X 개발자 정책, 계약 및 표시 요건 — 개발자 계약, 개발자 정책, Ads API 계약, 제한된 사용 사례를 포함합니다.
## 개요
개발자의 X 자료 및 콘텐츠 사용은 당사의 개발자 정책과 계약의 적용을 받으며 이에 따라 규율됩니다.
# Ads API 계약
Source: https://docs.x.com/ko/developer-terms/ads-api-agreement
X Ads API 계약은 허용되는 통합, 제한 사항 및 광고 파트너의 의무를 포함하여 X 광고 엔드포인트의 사용을 규율합니다.
당사는 Ads API 계약을 업데이트했습니다. 아래 변경 사항은 2025년 2월 23일부터 시행됩니다.
## X Ads Products and Services Agreement
**시행일: 2025년 2월 23일**
본 X Ads Products and Services Agreement(이하 "**본 계약**")은 X에 제출된 "X Ads API Program" 신청서에 명시된 주체(또는 그 승인된 대리인)(이하 "**회사**")와, 회사가 유럽연합, EFTA 국가 또는 영국 이외의 지역(미국 소재 회사 포함)에 있는 경우 X Corp., 또는 회사가 유럽연합, EFTA 국가 또는 영국에 있는 경우 X Internet Unlimited Company가 자신 및 그 계열회사(아래 정의됨)를 대리하여(어느 경우에나 "**X**") 체결하며, 회사의 Ad Products(아래 정의됨) 접근 및 이용을 규율합니다. 본 계약에서 "**계열회사(Affiliate)**"란 X를 직접 또는 간접적으로 지배하거나, X에 의해 지배되거나, X와 공통의 지배 하에 있는 다른 주체를 의미합니다.
본 계약의 조건 및 조항을 주의 깊게 읽어 주시기 바라며, 여기에는 이에 첨부된 모든 부속서 및 아래에 나타나거나 언급된 모든 링크된 조건이 포함되며, 이들은 본 계약의 일부를 구성합니다. "Yes, I Agree"로 표시된 상자를 체크하고 "SUBMIT"을 클릭함으로써(또는 예를 들어 "I Accept"와 같이 "Yes, I Agree"에 상응하는 문구를 사용함으로써) 또는 X MATERIALS를 사용함으로써, 회사는 본 계약의 조건을 읽었으며, 이를 준수하고 그에 구속되기로 동의함을 표명합니다. 회사가 본 계약에 구속되기로 동의하지 않는 경우, 회사는 X MATERIALS에 접근하거나 이를 사용할 수 없습니다. 본 계약은 다음 중 먼저 발생하는 날에 시행됩니다: (I) 회사가 "Yes, I Agree"를 체크하고 "SUBMIT"을 클릭하여 본 계약을 승인한 날짜, 또는 (II) 회사가 X MATERIALS에 최초로 접근한 날짜("**시행일**"). 다만, 회사의 X MATERIALS 접근 및 사용 신청이 X(단독의 절대적 재량으로)에 의해 승인되지 않은 경우, 본 계약은 무효이며 어떠한 효력도 갖지 않습니다. 귀하가 회사를 대표하는 개인인 경우, 귀하는 (A) 본 계약을 읽고 이해했으며, (B) 회사를 대신하여 본 계약을 승인할 적절한 권한을 보유하고, (C) 회사를 대신하여 본 계약의 조건에 동의함을 인정, 진술 및 보증합니다. 귀하가 회사를 구속할 법적 권한을 보유하지 않거나, 법적 연령에 도달하지 않았거나, 그 외의 사유로 X와 구속력 있는 계약을 체결할 수 없거나, 관련 법률에 따라 X MATERIALS의 사용 또는 수령이 금지된 경우, 귀하는 X MATERIALS를 사용할 수 없으며 본 계약을 승인할 수 없습니다.
### 1. 서문; 범위; 개별 제품 조건.
**1.1 서문.** X는 X의 광고 파트너에게 다양한 기능을 제공하는 제품 및 서비스 모음을 유지, 운영 및 제공합니다. 이러한 기능을 가능하게 하거나 이와 관련된 특정 제품, 서비스 및 프로그램(각각 "**개별 제품(Individual Product)**")은 다음과 같습니다: (i) X Ads API Program([Exhibit A](#Exhibit-A)에서 추가 설명); 및 (ii) X의 Custom Audiences Program([Exhibit B](#Exhibit-B)에서 추가 설명). 이러한 개별 제품을 통칭하여 본 계약에서 "**Ads Products**"라 합니다. 본 계약은 Ads Products 전체 및 각각의 개별 제품의 사용 및/또는 접근을 규율합니다. 또한 회사가 본 계약이 규율하는 Ads Product와 관련하여 X Marketing Partner("**TMP**") 프로그램에 참여하는 경우, [Exhibit C](#Exhibit-C)에 기재된 조건이 회사에 적용됩니다.
**1.2 범위.** 본 계약을 조건으로, 기간(Term) 동안 회사는 X가 회사에 접근 권한을 부여하거나 제공한 특정 개별 제품에 접근하고 이를 사용할 수 있습니다. 회사는 X가 접근 권한을 부여하거나 제공한 개별 제품의 전부 또는 일부를 사용할 의무가 없으며, X는 특정 개별 제품이나 Ads Products의 기능을 회사에 사용하도록 하거나 접근하도록 제공(또는 계속 제공)할 의무가 없습니다. X는 언제든지 단독 재량으로 특정 개별 제품 또는 그 기능의 사용 및/또는 접근을 허용하거나 거부할 수 있습니다. 회사가 Ads Products의 기능에 접근하거나 사용하는 범위 내에서, 본 계약의 조건이 그러한 접근 또는 사용을 규율합니다. 명확히 하기 위하여, 본 계약은 여기에 기재된 Ads Products의 회사 사용만을 규율합니다. X가 별도 계약 및/또는 별도 X 프로그램과 관련하여 회사에 (직접 또는 간접적으로) 제공한 데이터, 콘텐츠 또는 기타 자료에 대한 회사의 접근 및 사용은, X와 회사가 서면으로 달리 상호 합의하지 않는 한, 전적으로 그러한 별도 계약 및/또는 프로그램의 조건에 의해 규율되며 본 계약의 조건에 의해 규율되지 않습니다.
**1.3 개별 제품 조건.** 각 개별 제품은 본 계약의 조건에 추가하여 이를 제한하지 않는 특정 조건을 포함할 수 있으며, 회사가 해당 개별 제품에 접근하거나 이를 사용하는 범위 내에서 적용됩니다. 회사의 특정 개별 제품 및/또는 관련 X Materials(아래 정의)에 대한 접근은 회사가 개별 제품 조건 및 개별 제품에 대한 접근, 호출 및 사용에 관한 기술적 제한 사항을 승인하고 준수하는 것을 조건으로 합니다. 개별 제품 조건은 [Exhibit A](#Exhibit-A) 및 [Exhibit B](#Exhibit-B)에 첨부되어 있습니다. X는 아래 15.15조에 명시된 바와 같이, 단독 재량으로 이러한 개별 제품 정책 또는 조건을 수립하고 수정할 수 있습니다.
### 2. 정의.
**2.1** "**Campaign**"이란 데스크톱, 모바일 웹사이트, 또는 모바일 애플리케이션 광고 캠페인 또는 그 일부를 의미합니다.
**2.2** "**Client**"란 각 경우 X가 승인한, 하나(1) 이상의 Ads Products를 이용하는 X 광고주(회사의 고객이기도 함)를 의미합니다.
**2.3** "**Company Marks**"란 회사가 본 계약에 따라 X가 사용하도록 제공한(또는 그 밖의 방법으로 X의 사용을 위해 승인한) 회사명 및 모든 회사 로고, 상표 및/또는 서비스 마크를 의미합니다.
**2.4** "**Company Materials**"란 회사가 Ads Products를 통해 X에 제공하는 회사 데이터, 산출물 또는 사용자 콘텐츠를 의미합니다.
**2.5** "**Company Service**"란 X Materials 또는 그 일부를 표시하거나 사용하는 회사의 웹사이트, 애플리케이션 및 기타 제공물을 의미합니다.
**2.6** "**Data**"란 X가 회사에 제공하는 지표, 데이터 및 기타 정보 및/또는 콘텐츠를 의미하며, 상기의 분석 또는 사용에서 파생된 결과, 사용 통계, 데이터 또는 기타 정보(집계된 형태이든 그렇지 않든)를 포함합니다.
**2.7** "**End Users**"란 Client를 대신하여 Ads Products를 사용하는 Client의 직원 또는 승인된 대리인을 의미합니다.
**2.8** "**Marks**"란 상황에 따라(문맥에 따라) X Marks 및/또는 Company Marks를 의미합니다.
**2.9** "**Materials**"란 상황에 따라(문맥에 따라) X Materials 및/또는 Company Materials를 의미합니다.
**2.10** "**Personal Data**"란 데이터 그 자체 또는 데이터가 데이터 관리자의 소유이거나 소유하게 될 가능성이 있는 기타 정보와 결합하여 식별될 수 있는 살아있는 개인과 관련된 데이터를 의미합니다.
**2.11** "**X Ads**"란 X Network에 광고를 게재하는 것을 포함하여 X 광고 제품 및 서비스를 의미합니다.
**2.12** "**X Code**"란 X 서버를 (최소한) 호출하는, X가 개발하여 회사에 제공하는 컴퓨터 코드를 의미합니다.
**2.13** "**X Marks**"란 X가 본 계약에 따라 회사가 사용하도록 제공한(또는 그 밖의 방법으로 회사의 사용을 위해 승인한) X의 명칭 및 모든 X 로고, 상표 및/또는 서비스 마크를 의미합니다.
**2.14** "**X Materials**"란 X가 생성한 X 데이터, 산출물 또는 사용자 콘텐츠(그 파생물 포함), 그리고 X가 생성, 수집 또는 개발하거나 본 계약에 따라 회사에 제공 또는 제공 가능하게 한 X 데이터, 산출물 또는 사용자 콘텐츠(그 파생물 포함)를 의미하며, 회사의 X와의 파트너십에서 파생, 이에 기반하거나 이에서 발생하는 모든 데이터, 또는 디바이스 수준의 데이터, 또는 회사 혹은 X가 승인한 제3자가 회사의 X 광고 캠페인에서 또는 이와 관련하여 수집, 추론, 파생 또는 획득하는 전환, 참여, 추적 또는 타게팅 데이터를 포함합니다. 명확히 하고 제한 없이, "X Materials"에는 X Ads API([Exhibit A](#Exhibit-A)에서 정의), X Code, Data, Ads Products, 그리고 Custom Audience(아래 정의)를 생성하는 데 사용된 모든 X 사용자 ID가 포함됩니다.
**2.15** "**X Network**"란 X가 광고를 배포할 수 있는 모든 형태의 미디어, 애플리케이션 및 디바이스를 포함하여, 현재 알려져 있거나 향후 개발될 모든 매체를 통한 광고 채널의 네트워크를 의미합니다.
**2.16** "**X Marketing Partners Program**"이란 [Exhibit C](#Exhibit-C)에 자세히 설명된 X가 제공하는 파트너십 및 브랜드 프로그램을 의미합니다.
**2.17** "**X Service**"란 다음을 의미합니다: (i) X가 운영하는 실시간 콘텐츠 및 정보 서비스, (ii) 그러한 서비스를 가능하게 하는 기술 및 시스템으로, 총체적으로 X가 현재 X의 웹사이트에서 제공하는 소비자 및 광고 제품과 서비스, 그리고 X가 소유, 운영 및/또는 통제하는 모바일 애플리케이션과 소셜 플러그인 및 API를 포함하며, 이에는 Measurement Code, 모든 HTML 태그 또는 기타 코드, 인터넷 포털, 대시보드, 시스템 및 분석 도구 및 관련 서비스가 포함되나 이에 한정되지 않고, (iii) X 및 그 계열회사가 제공하는 그 밖의 모든 제품 또는 서비스로, (제한 없이 예로서) X Audience Platform 및 Data & Enterprise Solutions를 포함합니다.
### 3. X Ads/캠페인 관리; 책임 부담.
**3.1 X Ads/캠페인 관리.** 회사는 회사의 단독 재량으로 및/또는 회사의 Client의 지시에 따라, X Network에서 X Ads를 최적화, 수정, 관리, 개시 또는 조작하거나, 그 밖에 광고 관리 및 타게팅 결정(이하 "**Campaign Management**")을 할 수 있게 하는 하나 이상의 개별 제품에 접근할 수 있습니다. 회사가 그러한 개별 제품에 접근하거나 이를 사용하는 경우: (a) 회사는 X Network에 게시하려는 광고 자료를 즉시 제공해야 합니다; 그리고 (b) 회사는 X Network 또는 제3자를 통해 제공되는지 여부와 관계없이 해당 개별 제품을 통해 이용 가능한 모든 콘텐츠 또는 자산에 회사 및/또는 Client의 광고 자료를 배치하도록 X에 승인합니다. 회사는 해당 Client를 대신하여 그러한 광고 자료를 사용하기 위해 해당 Client로부터 필요한 라이선스 및 승인을 획득합니다. 회사는 Campaign Management를 허용하는 개별 제품을 사용해야 하는 것은 아니지만, 그러한 제품, 서비스 또는 기능을 사용하는 경우, 회사는 이로써 회사의 Campaign Management에서 발생하거나 이와 관련된 모든 위험을 부담하고, 모든 책임과 의무를 수락합니다. 여기에는 다음이 포함되나 이에 한정되지 않습니다: (i) 오디언스 생성 및 선택, 데이터 입력 오류, 전술 선택, 관련 인벤토리, 데이터 및 기타 제3자 비용; (ii) 회사가 제공한 광고가 시청자를 유도하는 자산(예: 랜딩 페이지) 및 이로부터의 리디렉션; (iii) 랜딩 페이지에 광고된 서비스 및 제품; 그리고 (iv) X에 제공된 광고 자료, 기술 및/또는 크리에이티브를 제한 없이 포함한 관련 Company Materials. 회사는 X가 회사의 Campaign Management와 관련하여 어떠한 책임이나 의무도 부담하지 않음을 인정하고 이에 동의합니다. 전술한 내용의 일반성을 제한하지 않으면서, X는 회사의 인력에게 Campaign Management 및 Ads Products 기능에 대한 교육을 제공할 책임이 없으며, 회사가 이에 대한 단독 책임을 집니다.
**3.2 Client의 본 조건에의 구속; 책임 부담.** 회사가 Client 또는 기타 제3자를 대신하여 Ads Products(또는 Campaign Management를 포함한 그 일부)에 접근하거나 이를 사용하는 경우, 회사는 다음을 보증합니다: (i) 회사는 그러한 Client 또는 기타 제3자를 대신하여 행위할 권한이 있으며, 회사가 이루어진 모든 X Ads 구매를 규율할 해당 X Master Services Agreement("**MSA**")를 포함한 적용 가능한 Our Policies(아래 6조에서 정의)와, 해당 Ads Products(또는 그 일부)에 대한 접근 및 사용에 적용되는 본 계약의 조건에 그러한 Client 또는 기타 제3자를 구속시켰다; 그리고 (ii) 회사는 그들의 준수에 대해 책임을 지고 그들의 위반에 대해 책임을 집니다.
### 4. 개인정보.
**4.1 직접 데이터 수집.** 회사는 다음을 진술하고 보증합니다: (i) 회사가 사용자로부터 직접 데이터를 수집하는 경우(Company Service를 통하거나 그 안에서 수집하는 것을 포함하나 이에 한정되지 않음), 회사는 그러한 사용자에게 법적으로 충분한 통지(제한 없이, 사용자로부터 수집되거나 X에 제공되는 데이터가 있는 모든 웹사이트, 모바일 애플리케이션 및 기타 서비스에서 관련 법률 및 규정을 준수하는 법적으로 충분한 개인정보 처리방침을 눈에 띄게 게시하고, 관심 기반 광고 목적으로 관련 웹사이트, 모바일 애플리케이션 및 기타 서비스에서의 사용자 활동(예: 검색 또는 쇼핑)에 대한 정보를 제3자가 수집한다는 사실을 공개하며, 사용자에게 관심 기반 광고를 옵트아웃할 수 있는 법적으로 충분한 지침을 제공하는 것을 포함)를 제공했습니다; (ii) 회사는 그러한 데이터 수집과 관련하여 회사의 쿠키 및/또는 추적 픽셀 사용에 관해 그러한 사용자로부터 법적으로 요구되는 정보에 입각한 동의를 모두 획득했습니다; 그리고 (iii) Company Materials는 관심 기반 광고 수신을 옵트아웃한 사용자 또는 정보주체에 관한 어떠한 데이터도 포함하거나 관련되지 않으며, 회사가 X에 제공, 접근 가능하게 하거나 가져온 오디언스 데이터도 그러한 사용자에 관한 데이터를 포함하거나 관련되지 않습니다.
**4.2 Personal Data.** 회사는 X Materials를 Personal Data 또는 직접 혹은 간접적으로 Personal Data와 연관된 식별자와 직접 또는 간접적으로 연결하거나 결합하지 않을 것이며, 그러한 시도도 하지 않을 것임을 진술하고 보증합니다. 또한 회사는 X Materials가 (직접적으로든 추론에 의해서든) Personal Data와 연결되는 것을 방지하기 위해 합리적인 안전 장치를 마련합니다.
**4.3 개인정보 준수.** 회사는 다음을 진술하고 보증합니다: (i) 회사는 범죄 혐의 또는 실제 발생, 건강, 부정적인 재무 상태 또는 상황, 정치적 소속 또는 신념, 인종 또는 민족 기원, 종교 또는 철학적 소속 또는 신념, 성생활, 노동조합 가입과 같은 민감 정보 또는 X의 광고 정책([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies))에 의해 제공이 금지된 제품, 메시지 또는 서비스가 제공되는 웹사이트, 모바일 애플리케이션 또는 기타 서비스에서 수집된 Company Materials를 X에 제공하지 않을 것이며, (ii) (1) 만 13세 미만의 아동에 관한 Company Materials를 X에 제공하지 않을 것이며, (2) 현재 16 CFR 312에 명시된 아동 온라인 사생활 보호법(Children's Online Privacy Protection Act)에서 정의된 아동을 대상으로 한 웹사이트, 모바일 애플리케이션 또는 온라인 서비스에서 얻은 Company Materials 또는 기타 데이터를 X에 전송하지 않을 것입니다. 회사는 [https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa)에 위치한 X Data Processing Addendum의 조건을 항상 준수할 것임을 인정하고 이에 동의합니다.
**4.4 제3자 데이터.** 회사는 본 계약에 따라 X에 대한 회사의 수행 의무를 지원하기 위해 사용자에 관한 데이터를 하나 이상의 제3자(데이터 파트너 및/또는 광고주(Client 포함)를 포함하나 이에 한정되지 않음)로부터 간접적으로 획득하는 경우, 그러한 각 제3자를 본 계약에 포함된 요구 사항(제한 없이 본 4조를 포함)에 계약적으로 구속시켰음을 진술하고 보증합니다.
### 5. 소유권; 라이선스; 제한 및 금지 사항.
**5.1 소유권.** 회사와 X 사이에서, 회사는 Company Materials, Company Marks 및 Company Service에 대한 모든 지역의 모든 권리, 자격 및 이익을 보유하며, 그 안에 포함된 X Materials, X Marks 및 X Service(및 상기의 모든 파생 저작물 또는 개선물)는 제외됩니다. 여기에는 그 안의 모든 지적 재산권이 포함되나 이에 한정되지 않습니다. 여기에 명시적으로 부여되지 않은 권리는 유보됩니다. 회사와 X 사이에서, X는 X Materials, X Marks 및 X Service에 대한 모든 지역의 모든 권리, 자격 및 이익, 그리고 (i) X Materials, (ii) X Marks, (iii) X Service에 기반하거나 이와 관련되거나 이로부터 발생하거나 관련된 모든 향후 개선물, 개발물, 강화물, 파생 저작물 및 관련 권리를 소유합니다. 여기에는 본 계약의 조건에 따라 Company Materials 또는 X Service에서의 회사의 광고 활동과 관련된 데이터에서 파생된 데이터, 통찰력, 정보 또는 학습 내용을 사용하거나 참조하여 그러한 개선물, 개발물, 강화물 또는 파생 저작물이 생성되는 경우가 포함되며, 그 안의 모든 지적 재산권이 포함되나 이에 한정되지 않습니다.
**5.2 회사에 대한 라이선스.** 기간(Wind-Down Period 포함) 동안, 회사가 Ad Products(또는 그 일부)를 사용하거나 이에 접근하는 범위 내에서, X는 이로써 회사에 X가 본 계약에 따라 회사에 제공할 수 있는 X Materials 및 X Marks를 유지 및 사용하기 위한 제한적이고, 로열티가 없으며, 비독점적이고, 재실시할 수 없으며, 양도할 수 없는 권리 및 라이선스를 부여합니다. 이는 X가 회사에 제공하거나 접근 가능하게 하는 Ads Products(또는 개별 제품)를 사용하고 본 계약에 따른 회사의 권리를 행사하고 의무를 이행하기 위해 필요한 경우에만, 각 경우 본 계약의 조건(X Materials 사용에 대한 제한 및/또는 한계를 포함하여 제한 없이)에 따라 부여됩니다. 회사는 X Marks의 사용이 항상 X Trademark Guidelines(아래 6조에서 정의)를 준수할 것임에 동의합니다.
**5.3 X에 대한 라이선스.** 기간(Wind-Down Period 포함) 동안, 회사가 Ad Products(또는 그 일부)를 사용하거나 이에 접근하는 경우, 회사는 X에 회사 지시(X Network에서 접근 가능한 광고 인벤토리의 구매 및/또는 광고 배치를 포함하나 이에 한정되지 않음)를 이행하고, Ad Products(또는 개별 제품)를 운영하며, 본 계약에 따른 X의 권리를 행사하고 의무를 이행하기 위해 필요한 경우, 각 경우 본 계약의 조건에 따라, Company Materials 및 Company Marks를 사용, 복사, 표시, 유지, 이전, 수정, 복제 및 전송할 로열티가 없고, 비독점적이며, 재실시 가능하고, 양도할 수 없는 권리 및 라이선스를 부여합니다.
**5.4 제한 및 금지 사항.**
5.4.1 X Materials는 회사에 제공되고, Company Materials는 X에 제공되는데, 이는 오로지 Ads Products의 사용 및/또는 제공 및 본 계약에 따라 명시적으로 허용된 기타 목적을 위해서만 제공됩니다.
5.4.2 본 계약에서 명시적으로 허용되거나 X와 회사가 사전에 서면으로 상호 합의하지 않는 한, 회사는 X Materials 또는 X Materials에서 파생된 정보, 데이터 또는 통찰력을 내부 또는 외부 목적(광고 타게팅, 광고 최적화, 리마케팅, 행동 타게팅, 리타게팅, 리디렉션 또는 사용자 또는 디바이스 세그먼트의 그룹핑을 어떤 방식으로든 생성 또는 확대, 또는 모바일 디바이스 식별자 또는 최종 사용자, 컴퓨터, 브라우저 또는 디바이스에 연결된 기타 고유 식별자와 관련된 최종 사용자 프로필 생성 또는 추가, 또는 광고 네트워크 또는 교환, 데이터 브로커 또는 기타 광고 또는 수익화 서비스를 통해 사용자를 광고로 리디렉션하는 것을 포함하나 이에 한정되지 않음)으로 이용, 복제, 복사, 수정, 파생 및/또는 재사용하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다. 또한 회사는 사용자를 어떤 식으로든 식별하거나 재식별하기 위해 X Materials를 사용하지 않을 것입니다(X Materials 또는 이에서 파생된 데이터를 제3자 소스에서 파생된 데이터와 결합하는 것을 포함).
5.4.3 회사는 X의 명시적인 서면 허가 없이 X Materials(제한 없이 컴퓨터 코드, 픽셀, 태그 또는 X가 회사에 제공한 기타 디지털 제품을 포함)를 다른 제품이나 서비스에 통합(본 계약의 이행에 필요하고 본 계약의 조건에 의해 허용되는 경우 제외), 번역, 수정, 리버스 엔지니어링 또는 리버스 컴파일, 분해, 파생 저작물 생성 또는 그 밖에 X Materials의 소스 코드, 기초 아이디어 또는 알고리즘을 발견하려 시도하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.4 회사는 X Materials의 기능 또는 기능성을 방해, 수정, 중단 또는 비활성화하지 않을 것이며(기능성을 제한하거나 제어하는 데 사용되는 메커니즘, 또는 X Materials의 소프트웨어 보호 또는 모니터링 메커니즘을 무력화, 회피, 우회, 제거, 비활성화하거나 그 밖에 우회하는 것을 포함하나 이에 한정되지 않음), 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.5 회사는 여기에 명시적으로 허용된 경우를 제외하고 X Materials의 전부 또는 일부를 제3자에게 판매, 임대, 리스, 서브라이선스, 배포, 재배포, 신디케이션, 파생 저작물 생성, 양도 또는 그 밖의 방식으로 이전하거나 접근권을 제공하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.6 회사는 X Materials 안이나 위에 있는 소유권 고지 또는 마크를 제거하거나 변경하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.7 회사는 서비스 뷰로, 렌탈 또는 관리 서비스 방식으로 X Materials의 사용을 제공하거나, 다른 개인 또는 주체가 X Materials에 대한 링크를 만들거나 다른 서버, 무선 또는 인터넷 기반 디바이스에서 X Materials를 "프레임" 또는 "미러링"하도록 허용하거나, 해당하는 경우 그 밖에 제3자에게 X Materials에 대한 토큰, 키, 비밀번호 또는 기타 로그인 자격 증명을 제공하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.8 회사는 불법적이거나, 무단이거나 기타 부적절한 목적으로 X Materials를 사용하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.9 회사는 여기에 명시적으로 기재된 경우 또는 X가 사전에 서면(이메일 허용)으로 허용한 경우를 제외하고, X Materials(Data를 포함하나 이에 한정되지 않음)를 어떠한 제3자(구두 또는 서면 여부와 관계없이)와도 공유하지 않을 것이며, 여기에는 회사의 클라이언트나 사업 파트너 또는 Ads Products와 무관한 회사 인력이 포함됩니다. 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.10 회사는 여기에 명시적으로 상세히 기재된 경우 또는 X가 사전에 서면으로 승인한 경우를 제외하고, X Materials를 별도 계약에 따라 X로부터 받은 Company Materials, 데이터, 콘텐츠 또는 기타 자료, 또는 다른 제3자 자료 또는 광고 캠페인 전반과 혼합하거나 그 밖의 방식으로 결합하여 표시하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.11 회사는 X의 사전 서면 동의 없이 Company Service 및/또는 X Materials를 광고 네트워크의 일부로 제공하거나 제공할 수 없으며, 어떠한 제3자(Client 포함하나 이에 한정되지 않음)에 의해 또는 그러한 제3자에게 X Materials의 프로그래밍 방식 내보내기 또는 그 밖의 기계 소비를 가능하게 하지 않을 것이며, 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
5.4.12 회사는 X Network에 접근하는 사용자에게 오해의 소지가 있거나 기만적일 수 있는 방식으로 Ads Products에 참여하도록 사용자를 장려하거나 요구하지 않을 것이며, 이러한 방식에는 인센티브, 포인트, 보상, 현금, 상품 또는 기타 금전적 가치가 있는 것을 제공하거나, 악의적이거나 사기성이 있는 기타 방법이 포함될 수 있습니다. 다른 당사자(Client 포함)에게도 그러한 행위를 허용하지 않을 것입니다.
### 6. 편입된 조건.
특정 개별 제품 및/또는 관련 X Materials에 대한 회사의 접근은 회사가 회사가 접근하거나 사용하는 개별 제품 및 X Materials에 적용되는 범위에서 다음의 정책(통칭 "**X Policies**")을 승인하고 준수하는 것을 조건으로 합니다:
**6.1** 개인정보 처리방침([https://x.com/privacy](https://x.com/privacy))
**6.2** 서비스 약관([https://x.com/tos](https://x.com/tos))
**6.3** 해당 X Master Services Agreement([https://legal.x.com/ads-terms/us.html](https://legal.x.com/ads-terms/us.html)) ([https://legal.x.com/ads-terms/international.html](https://legal.x.com/ads-terms/international.html)) 또는 삽입 주문(insertion order)에 언급된 기타 X Master Services Agreement.
**6.4** 광고 정책 가이드라인([https://business.x.com/en/help/ads-policies](https://business.x.com/en/help/ads-policies)), 전환 추적 및 Custom Audiences에 관한 정책 포함([https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences))
**6.5** 개발자 계약 및 정책([https://docs.x.com/developer-terms/agreement](/developer-terms/agreement))
**6.6** X 상표 및 브랜드 가이드라인([https://about.x.com/who-we-are/brand-toolkit](https://about.x.com/who-we-are/brand-toolkit))
회사는 개별 정책이 적용되는 개별 제품에 접근하거나 이를 사용하는 범위에서 X Policies에 동의합니다. 회사는 X Policies가 X의 단독 재량으로 수시로 X에 의해 수정될 수 있음을 승인하고 동의합니다. 회사에 영향을 미치는 X Policies의 중대한 수정이 있는 경우, X는 회사에 그러한 변경 사항을 통지합니다(이메일 또는 X Service에 게시하는 방식 등). 그러한 업데이트 또는 수정 이후 회사가 계속 X Materials 및 X Marks에 접근하거나 이를 사용하는 것은 업데이트 및 수정에 대한 구속력 있는 동의를 구성합니다.
### 7. 기간; 해지 권한; 중지 권한.
**7.1 기간.** 본 계약은 시행일에 개시되며 1년("**최초 기간**") 동안 유효하고, 이후 자동으로 1년의 추가 기간("**갱신 기간**")으로 연장됩니다. 다만, 어느 일방이 최초 기간 만료 최소 30일 전에 갱신 거절 서면 통지를 하거나 아래 7.2조에 따라 본 계약을 해지하는 경우는 예외입니다. 최초 기간과 모든 갱신 기간을 총칭하여 "**기간(Term)**"이라 합니다.
**7.2 해지; 중지.** 최초 기간 완료 및 갱신 기간 개시 후에는, 어느 일방도 상대방에 대한 사전 30일 통지로 편의를 위해 본 계약을 해지할 수 있습니다. X는 회사가 다음 각 호에 해당하는 경우 회사에 대한 서면 통지로 본 계약을 즉시 해지할 수 있습니다: (a) 자발적이든 비자발적이든 및/또는 법률의 작용에 의해(제한 없이 합병, 인수 또는 자산 매각과 관련하여, 회사가 존속 또는 소멸 주체인지 여부와 관계없이) 제3자에 의해 전부 또는 일부가 합병되거나 인수되는 경우; 또는 (b) 재산에 대한 재산관리인 또는 유사한 당사자가 선임되거나, 지급불능이 되거나, 어떤 방식으로든 지급불능을 인정하거나, 사업을 중단하거나, 채권자를 위해 양도하거나, 파산 신청을 하는 경우. 본 계약 또는 법률 또는 형평법상 이용 가능한 다른 구제 수단을 제한하지 않으면서, X는 단독 재량으로 다음과 같이 판단하거나 결정하는 경우 언제든지 통지 없이 회사의 Ads Products, 특정 개별 제품 및/또는 X Materials(또는 그 일부)에 대한 접근 또는 사용을 즉시 중지하거나, 본 계약에 따라 회사에게 부여된 라이선스 또는 본 계약 전체를 해지할 수 있습니다: (i) 회사가 Our Policies를 위반하거나, 본 계약의 조건을 위반했거나 위반하려 하거나 준수하지 않는 경우, 및/또는 (ii) 회사의 Ads Products, 특정 개별 제품 및/또는 X Materials에 대한 계속적 접근이 X 및/또는 X의 Client에게 책임을 초래하거나 X 또는 X의 Client의 서비스, 사업 또는 명성에 해를 끼치는 경우.
**7.3 해지의 효과.** 본 계약의 만료 또는 해지 시: (a) 여기에 부여된 모든 권리 및 라이선스는 즉시 종료되며 회사는 X Materials에 대한 접근 및 사용을 즉시 중단해야 합니다; (b) 그러한 만료 또는 해지 후 30일 이내에, 회사는 Company Service 또는 그 밖에 회사의 소유 또는 통제 하에 있는 모든 형태 및 유형의 매체에서 X Materials의 전부(모든 사본 및 일부 포함)를 제거, 삭제 및 안전하게 소거합니다; 그리고 (c) 그러한 만료 또는 해지 후 30일 이내에, 회사는 회사의 소유 또는 통제 하에 있는 모든 기밀 정보(아래 9조에서 정의)의 사본을 삭제하고 안전하게 소거합니다. X는 본 계약 해지의 결과로 인한 어떠한 비용, 지출 또는 손해에 대해서도 책임을 지지 않습니다.
**7.4 Wind Down Period.** 전술한 내용에도 불구하고, 어느 일방이 본 7조에 따라 본 계약을 해지하는 경우, 본 계약의 조건 및 각 당사자의 권리와 의무는, X의 단독 결정에 따라(그리고 그러한 결정에 대한 회사에 대한 X의 서면 통지 시), 그러한 해지 시점에 진행 중인 Client 광고 캠페인(X 및/또는 해당 Client가 광고 캠페인을 실행하기로 선택한 상황이 포함되며, 해지 시점에 그러한 광고 캠페인이 실제로 개시되지 않은 경우 포함하나 이에 한정되지 않음)에 대해서만 Wind-Down Period(아래 정의) 동안 계속 적용됩니다. 여기에서 사용된 "**Wind-Down Period**"란 기간의 해지 시 개시되어 다음 중 먼저 도래하는 시점까지 계속되는 기간을 의미합니다: (i) 그러한 해지일로부터 90일; 또는 (ii) 그러한 해지일 현재 (위에서 설명한 대로) 진행 중이었던 모든 Client 광고 캠페인의 완료.
**7.5 존속.** 본 계약의 만료 또는 해지 후에도 그 성질상 존속해야 하는 조건은 존속하며, 여기에는 3조부터 15조가 포함되나 이에 한정되지 않습니다.
### 8. 보안; 보안 침해; 규제 통지; 데이터 삭제; 감사.
**8.1 보안.** 회사는 본 계약에 따른 이행과 관련하여 X Materials에 포함된 데이터 유형의 전송 및 저장을 위한 업계 표준 보안 조치와 최소한 동일하게 엄격한 데이터 전송 및 저장을 위한 관리적, 기술적 및 물리적 보안 조치를 포함한 업계 표준 보안 조치를 사용합니다. 회사는 또한 본 계약에 따라 회사의 권리를 행사하고/하거나 회사의 의무를 이행하기 위해 X Materials에 접근해야 하는 개별 회사 인력으로만 X Materials 및 기밀 정보에 대한 접근을 제한하기 위해, 회사가 동일하거나 유사한 성격의 회사 자체 데이터를 전송하고 보호하는 것과 관련하여 사용하는 것과 결코 낮지 않은 수준의 주의를 기울여, 합리적인 기술적 및 조직적 보안 조치(최소한 비밀번호 보호 및 접근 프로토콜 제한 포함)를 사용합니다.
**8.2 보안 침해.** 회사는 X Materials 및/또는 본 계약과 관련되거나 이에 기반하거나 이에서 발생하는 데이터의 노출을 초래했거나, 초래했을 수 있거나, 초래할 가능성이 있는 보안 침해 또는 기타 부적절한 접근을 인지한 후 24시간 이내에 X에 서면(이메일 포함 가능)으로 통지합니다. 회사는 모든 조사에서 X와 협의하고 협력하며, 필요한 통지를 제공하고/제공하거나 X가 합리적으로 요청하는 정보를 제공합니다.
**8.3 규제 문의.** 회사는 보안 침해(또는 유사한 사고), 회사의 소비자 데이터 오남용 주장, 또는 본 계약과 직접 또는 간접적으로 합리적으로 관련된 회사의 운영의 기타 측면에 관한 정부 또는 규제 기관의 문의를 통지받은 후 24시간 이내에 X에 서면(이메일 포함 가능)으로 통지합니다.
**8.4 데이터 삭제.** 회사는 본 계약에 따른 회사의 권리 행사 및/또는 의무 이행을 위해 X Materials를 보유할 정당한 사업상 필요가 더 이상 없는 경우(해당 Client가 Ads Products 사용을 중단하거나 그 밖에 Company Services 사용을 중단하는 경우를 포함하나 이에 한정되지 않음), 자사의 시스템에서 X Materials의 전부를 삭제하고 안전하게 소거하며, 어떠한 경우에도 다음 중 먼저 도래하는 시점보다 늦지 않게: (a) 회사가 해당 Data를 최초로 받은 날로부터 90일, 또는 (b) 본 계약의 만료 또는 해지일 후 30일. 또한 언제든지 회사는 X의 서면 요청(이메일로 전달 가능) 즉시, X가 삭제 및 안전한 소거가 필요하거나 바람직하다고 판단하는(X의 단독 및 절대 재량으로) X Materials를 삭제하고 안전하게 소거할 것에 동의합니다.
**8.5 감사.** 사전 서면 통지(10일 이상)를 통해, 기간 중 각 역년(calendar year) 동안 연 2회를 초과하지 않고, 본 계약이 해지 또는 만료된 날 이후 6개월 기간 동안 1회, X의 비용으로, X는 회사가 본 계약에 따라 의무를 수행하고 권리를 행사하는 데 사용하는 프로세스, 방법론, 관행 및 시스템을 감사하기 위해 회사 시설에 대한 접근을 제공받습니다. 명확히 하기 위하여, 회사는 (i) X가 자신을 대신하여 그러한 감사를 수행하기 위해 제3자 감사인을 고용할 수 있으며, (ii) 여기에 반하는 어떤 규정에도 불구하고, X는 그러한 감사를 촉진하기 위해 필요한 범위에서만 회사에 관한 관련 기밀 정보(본 계약의 조건 포함하나 이에 한정되지 않음)를 그러한 제3자 감사인과 공유할 수 있음을 인정하고 동의합니다.
### 9. 기밀 정보.
각 당사자는 "기밀" 또는 "독점 정보"로 지정되었거나, 정보가 공개되는 기밀성을 합리적인 사람이 이해할 수 있는 방식으로 공개하는 당사자에 의해 공개된 모든 사업, 기술 및 재무 정보("**기밀 정보(Confidential Information)**")에 동의합니다. 명확히 하기 위하여, X가 본 계약에 따라 회사에 제공하는 모든 독점 정보에는 X의 기술, 디자인, 기법, 연구, 노하우, 사양, 제품 계획, 가격, 고객 정보, 사용자 데이터, 현재 또는 미래의 전략적 정보, 현재 또는 미래의 사업 계획, 정책 또는 관행, 직원 정보, 기타 사업 및 기술 정보(가동 시간, 신뢰성, 트래픽 및 성장 지표, 네트워크 품질 및 X Service의 기타 사용 통계에 관한 결과, 분석 또는 데이터로서, 집계 형태이든 그렇지 않든, 회사의 X Materials 또는 X Service 사용 및/또는 기술 문서, 개발자 뉴스레터 및/또는 온라인 포털 또는 포럼에 대한 접근에서 파생된 것)에 관한 정보(유형 또는 무형)가 포함되나 이에 한정되지 않으며, 이는 X 기밀 정보이며 X의 독점 정보입니다. 전술한 내용을 제한하지 않으면서, 본 계약의 조건, X Materials, 제품 요건 및 X가 본 계약에 따라 회사에 제공한 기타 문서, 온보딩 프로세스 또는 기타 자료는 X 기밀 정보로 간주됩니다. 여기에 명시적으로 허용된 경우를 제외하고, 수신 당사자는 공개 당사자의 기밀 정보를 비밀로 유지하고 이를 사용하거나 공개하지 않을 것입니다(본 계약에 따른 해당 당사자의 의무 수행과 관련된 경우 제외). 수신 당사자는 다음과 같은 정보에 대해서는 본 조에 따른 의무가 없습니다: 수신 당사자가 서면 또는 증언을 통해 그러한 정보가 (i) 수신 당사자 또는 그 직원이나 대리인의 잘못 없이 이미 공개적으로 이용 가능하거나 그렇게 된 경우; (ii) 그러한 정보를 합법적으로 소유한 제3자로부터 받았고, 수신 당사자가 그러한 정보를 공개하는 데 있어 그러한 제3자에 대한 어떠한 공개 제한도 알지 못하는 경우; (iii) 제한 없이 공개 당사자에 의해 제3자에게 공개된 경우; (iv) 상대방 당사자에 의한 공개 이전에 수신 당사자가 제한 없이 정당하게 소유하고 있었던 경우; 또는 (v) 그러한 정보에 의존하지 않고 수신 당사자의 직원 또는 컨설턴트가 독자적으로 개발한 경우. 수신 당사자는 법률 또는 법원 명령에 의해 요구되는 공개를 할 수 있으며, 다만 수신 당사자는 그러한 명령의 발행에 대해 공개 당사자에게 통지하고 공개 당사자가 절차에 참여할 수 있도록 허용해야 합니다.
### 10. 진술 및 보증.
회사는 다음을 진술하고 보증합니다: (i) 회사는 본 계약을 체결하는 데 필요한 모든 법적 및 법인 권한을 보유합니다; (ii) 회사는 본 계약을 합법적이고 유효하며 구속력 있는 의무로 만들기 위해 필요한 모든 조치를 취했습니다; (iii) 회사는 본 계약에 따른 의무 이행을 방해하거나 방해할 제3자와의 어떠한 계약이나 합의도 없습니다; (iv) 회사는 본 계약에 따라 의무를 이행하고 부여된 모든 권리 및 라이선스를 부여하는 데 필요한 모든 허가, 동의, 권리, 승인 및 라이선스를 획득했고 유지할 것이며, 여기에는 X Service 또는 그 밖에 X가 이용 가능하거나 접근 가능한 광고 인벤토리에 광고를 배치하고 Company Service를 제공하기 위해 Company Materials 사용에 대한 라이선스를 X에 부여하는 데 필요한 모든 권리가 포함되나 이에 한정되지 않습니다; (v) Company Service 및 Company Materials는 어떠한 제3자 권리(지적 재산권, 개인정보권 또는 퍼블리시티권 포함)도 침해하거나 오용하거나 그 밖에 위반하지 않으며, 그렇게 하지 않을 것입니다; 그리고 (vi) 본 계약에 따른 회사의 사업 및 수행(Company Service의 제공 포함)은 모든 관련 외국, 연방, 주 및 지방 법률 및 정부 규칙 및 규정을 준수하고 준수할 것입니다. 회사는 또한 다음을 진술하고 보증합니다: (a) 회사는 Company Service, Company Materials 또는 본 계약과 관련된 기타 산출물 또는 데이터 보안, 데이터 사용 또는 개인정보에 관한 회사의 관행에 관한 실제, 계류 중 또는 위협 중인 청구, 소송, 조치 또는 고발에 대해 알고 있는 바가 없습니다; 그리고 (b) 회사가 Client를 대신하여 Ads Products(또는 그 일부)에 접근하거나 사용하는 경우, 회사는 그러한 제3자를 대신하여 그러한 Company Materials를 사용하고, Company Materials에서 X에 제공될 수 있는 그러한 제3자 자료에 대한 권리를 전달하며, 그러한 제3자를 본 계약의 조건에 구속시킬 대리인으로서의 권한을 그러한 제3자에 대해 보유합니다.
### 11. 피드백. 베타 서비스.
X가 (단독 및 절대 재량으로) 비공개, 미출시, 개발 중이거나 "알파" 또는 "베타"로 지정된 기능 및 기능성(통칭 "**Beta Services**")에 대한 접근을 회사에 제공하는 경우, 회사는 Beta Services가 X에 의해 지원되지 않으며, Beta Services(또는 그 일부)가 언제든지 공개적으로 출시되거나 이용할 수 없게 될 수 있음(각 경우 X의 단독 및 절대 재량으로)을 인정하고 동의합니다. Beta Services는 법률이 허용하는 최대 범위에서 "있는 그대로(AS IS)" 제공되며, 회사의 그러한 Beta Services 사용은 회사의 위험과 동의로 이루어집니다. 모든 Beta Services는 X 기밀 정보로 간주됩니다. 회사는 Beta Service 참여가 X가 일부 기존 및/또는 잠재 프로그램, 제품 및/또는 도구를 연구, 분석 및 검증하는 데 도움이 될 것이며, 회사가 그러한 프로그램, 제품 및/또는 도구를 평가하고 개선하는 것을 지원하기 위해 X에 의견, 피드백 또는 기타 정보("**Feedback**")를 제공하는 경우, X 및 그 지정자는 Feedback(파생 저작물 포함)을 회사 또는 제3자에 대한 어떠한 의무나 보상 없이 모든 상업적 및 비상업적 목적으로 자유롭게 복사, 수정, 파생 저작물 생성, 공개적으로 표시, 공개, 배포, 라이선스 및 서브라이선스, 통합 및 그 밖에 사용할 수 있음에 동의합니다. 명확히 하기 위하여, Feedback에는 회사명이 포함되지 않으며 X는 회사의 Beta Services 성과 결과를 공개적으로 공개하지 않을 것입니다. Feedback에는 또한 X Materials, Ads Products 및/또는 회사의 그 평가 및 사용에 관한 회사 의견이 포함됩니다. 회사는 본 계약의 어떠한 내용도 X가 회사, Client 또는 End Users의 제품 또는 서비스와 경쟁할 수 있는 제품이나 서비스를 개발하는 것을 방해하지 않는다는 데 동의합니다.
### 12. 보증의 부인.
여기에 제공된 X MATERIALS, ADS PRODUCTS 및 기타 X 제품 및 서비스(BETA SERVICES를 포함하나 이에 한정되지 않음) 및 X MARKS는 어떠한 종류의 보증 없이 "있는 그대로(AS IS)" 및 "이용 가능한 대로(AS AVAILABLE)" 제공됩니다. X는 명시적, 묵시적, 법정 또는 그 밖의 모든 보증을 부인하며, 여기에는 상품성, 비침해성, 특정 목적에의 적합성 및 거래 과정 또는 상거래 관행에서 발생하는 모든 보증 또는 조건이 포함되나 이에 한정되지 않습니다. X는 여기에 제공된 X MATERIALS, ADS PRODUCTS 및 기타 X 제품 및 서비스(BETA SERVICES를 포함하나 이에 한정되지 않음) 또는 X MARKS가 회사의 요구 사항을 충족하거나 그러한 X MATERIALS, 기타 X 제품 및 서비스 및/또는 X MARKS의 사용이 오류가 없거나, 중단되지 않거나, 바이러스가 없거나, 안전할 것임을 보증하지 않습니다. 이 보증의 부인은 일부 관할권에서 유효하지 않을 수 있으며, 회사는 포기하거나 부인할 수 없는 법률에 따른 보증 권리를 가질 수 있습니다. 그러한 보증은 본 계약 시행일로부터 30일 동안만 확장됩니다(그러한 법률이 달리 정하지 않는 한).
### 13. 면책.
회사는 다음 사항에 기반한 주장의 결과로 제3자에 의해 X에 대해 제기된 청구, 소송 또는 조치를 자체 비용으로 방어합니다: (i) Company Materials, Company Service, Company Marks, X의 Company Materials 또는 Company Marks 사용 또는 Company Materials 및/또는 Company Service를 생성하는 데 사용된 기술이 제3자의 권리(지적 재산권, 개인정보권 또는 퍼블리시티권을 포함하나 이에 한정되지 않음)를 침해한다는 주장; (ii) 회사가 회사의 데이터 보안, 데이터 사용 및 개인정보 의무를 포함한 여기에 명시된 의무, 진술 또는 보증을 위반했다는 주장; 또는 (iii) 본 계약에 명시된 조건, 조항 및 제한을 위반한 회사의 X Materials 및/또는 X Marks의 무단 사용. 회사는 그러한 청구로 인한 손실, 손해, 책임, 벌금, 비용 및 지출에 대해 X를 면책하고 무해하게 유지합니다. 회사는 X에 대한 청구를 방어할 책임이 있으며, X는 자체 선택 변호인과 참여할 권리가 있고, X에 대한 모든 청구로 인한 모든 판결, 합의, 손해, 손실, 책임, 비용 및 지출(합리적인 변호사 수수료 포함)에 대해 지불할 책임이 있습니다. 다만, 회사는 그러한 합의가 X를 어떤 의무 또는 책임에서 해제하는지 여부와 관계없이 X의 사전 명시적 서면 동의 없이 청구와 관련된 어떠한 합의에도 동의하지 않을 것입니다. X는 회사에 면책 의무를 즉시 통지합니다(단, 그러지 못한 경우 회사가 그 실패로 인한 중대한 편견을 입증할 수 있는 범위에서만 회사의 의무가 면제됩니다).
### 14. 책임의 제한.
어떠한 경우에도 X는 본 계약과 관련하여 또는 여기에 제공된 X MATERIALS, X MARKS 또는 X 제품 및/또는 서비스(ADS PRODUCTS를 포함하나 이에 한정되지 않음)의 회사 또는 CLIENT 또는 END USER 사용으로 인해 발생하는 특별, 부수적, 예시적, 징벌적 또는 결과적 손해, 또는 수익 손실, 이익 손실, 상품 또는 서비스 교체 비용, 기술 손실, 영업권, 서비스 권리, 데이터 손실 또는 중단 또는 서비스 사용 손실에 대해 회사 또는 CLIENT 또는 END USER에게 책임을 지지 않으며, 그러한 책임이 계약, 보증, 불법 행위(과실 포함), 엄격 책임 또는 그 밖에 기반한 청구에서 발생하는지 여부와, X가 그러한 손실 또는 손해의 가능성에 대해 통지받았는지 여부와 관계없이 적용됩니다. 관련 법률이 여기에 대한 어떠한 책임 제한도 금지하는 범위 내에서, 당사자는 그러한 제한이 자동으로 수정되지만 그러한 제한이 관련 법률을 준수하도록 하는 범위에서만 수정된다는 데 동의합니다. 당사자는 여기에 명시된 책임 제한이 위험의 합의된 배분이며 제한된 구제 수단의 본질적 목적의 실패에도 불구하고 적용될 것임에 동의합니다. 어떠한 경우에도, 본 계약에 따른 X의 총 책임은 미화 50달러(U.S. \$50)를 초과하지 않습니다.
### 15. 기타.
**15.1 홍보.** 회사는 X의 사전 서면 동의(이메일로 제공 가능) 없이 본 계약, 여기에서 검토된 활동 또는 회사와 X 간의 관계에 관한 언론 보도자료, 블로그 게시물 발행 또는 그 밖의 공개 발표나 공개를 할 수 없습니다.
**15.2 사용자 보호.** 회사는 다음을 하지 않을 것입니다 (a) 정부 기관, 법 집행 기관 또는 기타 조직이 X Service 또는 X Materials에 대한 감시를 수행하거나 X의 사용자 또는 그들의 게시물에 대한 정보를 획득하는 것으로서, 소환장, 법원 명령 또는 기타 유효한 법적 절차가 필요하거나 그렇지 않으면 X 사용자의 합리적인 개인정보 기대에 부합하지 않을 가능성이 있는 것을 알면서 허용하거나 지원합니다; 또는 (b) 세계인권선언([https://www.un.org/en/universal-declaration-human-rights/index.html](http://www.un.org/en/universal-declaration-human-rights/index.html))(제12조, 제18조 또는 제19조 포함하나 이에 한정되지 않음)을 위반하기 위해 그러한 데이터를 사용할 것이라고 회사가 합리적으로 믿는 개인 또는 주체에게 X Materials를 표시, 배포 또는 그 밖에 이용 가능하게 합니다. X 사용자에 관한 정보를 찾는 법 집행 인력은 [https://help.x.com/rules-and-policies/x-law-enforcement-support](https://help.x.com/rules-and-policies/x-law-enforcement-support)에 있는 X의 법 집행 가이드라인에 안내됩니다.
**15.3 정부 사용.** X Materials는 48 C.F.R. 2.101에 정의된 "상업적 항목(commercial items)"이 될 수 있으며, 48 C.F.R. 12.212에서 사용되는 용어인 "상업적 컴퓨터 소프트웨어(commercial computer software)" 및 "상업적 컴퓨터 소프트웨어 문서(commercial computer software documentation)"로 구성됩니다. 정부 기관의 X Materials 사용, 수정, 파생, 재생산, 발매, 수행, 표시, 공개 또는 배포는 본 계약의 조건에 명시적으로 허용된 경우를 제외하고 금지됩니다. 또한 미국 정부 기관의 어떠한 사용도 48 C.F.R. 12.212 및 48 C.F.R. 227.7202-1 내지 227.7202-4에 따라야 합니다. 계약자/제조자는 X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA입니다.
**15.4 법률 준수; 수출/수입.** 각 당사자는 모든 관련 외국, 연방, 주 및 지방 법률, 규칙 및 규정을 준수합니다. 회사는 Our Policies(여기에서 정의) 또는 관련 법률을 위반하여 X Services 또는 X Data를 수출하거나 재수출하지 않습니다. X Materials는 미국 수출법의 적용을 받을 수 있으며 배송되거나 사용되는 국가의 수입 및 사용 법률의 적용을 받을 수 있습니다. 회사는 이러한 법률을 준수하기로 동의합니다. 이러한 법률에 따라, X Materials는 관련 정부 당국의 라이선스나 승인 없이 미국 정부가 금수 조치한 국가를 포함한 이러한 법률에 의해 제한된 국가나 외국인에게, 또는 미국 재무부 해외자산통제국(U.S. Office of Foreign Assets Control)이 금지한 개인이나 주체를 포함한 제한된 또는 거부된 최종 사용자에게, 또는 제한된 최종 사용을 위해, 국경을 넘어 판매, 임대, 다운로드, 이동, 수출, 재수출 또는 이전될 수 없습니다.
**15.5 수정.** X는 X의 개발자 사이트([https://developer.x.com](https://developer.x.com))(수시로 개정될 수 있음), 해당 X 정책이 게시된 URL에 변경 사항을 게시하거나 회사에 그 밖의 방식으로 통지함으로써(이메일을 통한 통지 포함), X의 단독 재량으로 수시로 Our Policies, 분석 데이터 표시 요건([Exhibit A-2](#Exhibit-A-2)로 첨부됨), "X Marketing Partner" 프로그램 관련 조건([Exhibit C](#Exhibit-C)로 첨부됨) 및 X Materials와 관련된 기타 기술 문서 및 기타 가이드라인 또는 정책을 업데이트하거나 수정할 수 있습니다. 어떠한 변경이 회사에 수용 불가능한 경우, 회사의 유일한 구제 수단은 X Materials 및 X Marks의 모든 사용을 중단하는 것입니다.
**15.6 통지.** 6조 및 15.5조에 달리 명시된 경우를 제외하고, 본 계약에 의해 요구되거나 허용되는 통지는 서면으로 하며 다음과 같이 전달되고 표시된 대로 통지된 것으로 간주됩니다: (a) 직접 배달로 배달된 경우 개인 배달; (b) 서면 수령 확인 시 익일 배송; (c) 수령 확인 시 반송 영수증 요청된 인증 또는 등기 우편; 또는 (d) 수신자가 관련 이메일을 받았음을 인정하는 경우 전자 우편. 통지는 아래에 명시된 주소 또는 어느 당사자가 서면으로 지정할 수 있는 기타 주소로 전송됩니다. 회사가 X에 보내는 위반 통지는 익일 배송 또는 인증 또는 등기 우편으로만 전송해야 합니다. 회사에 대한 통지는 X에 기록된 회사 주소로 전송됩니다. X Corp.에 대한 통지는 다음으로 전달됩니다: X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA, Attn: Legal Department, 필수 사본을 다음으로: Head of Ads API 및 [legalnotices@x.com](mailto:legalnotices@x.com). X Internet Unlimited Company에 대한 통지는 다음으로 전달됩니다: Legal Department, X Internet Unlimited Company, One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland.
**15.7 양도.** 회사는 X의 명시적인 서면 동의를 제외하고, 자발적, 비자발적 및/또는 법률의 작용에 의해(제한 없이 합병, 인수 또는 자산 매각과 관련하여, 회사가 존속 또는 소멸 주체인지 여부와 관계없이) 본 계약 또는 여기에 부여된 권리 또는 의무의 전부 또는 일부를 제3자에게 양도할 수 없으며, 본 항을 위반한 양도 시도는 무효이며, X는 본 계약을 즉시 해지할 수 있습니다. 본 계약은 각 당사자의 허용된 승계자 및 양수인의 이익을 위해 구속하고 상속됩니다.
**15.8 하도급 없음.** 회사는 X가 사전에 서면(이메일로 제공 가능)으로 승인하지 않는 한, 본 계약에 따른 회사의 의무나 직무를 수행하거나 이행하기 위해 제3자를 사용할 수 없습니다.
**15.9 파트너십 없음.** 본 계약은 어떠한 파트너십, 대리 또는 합작 투자도 창설하거나 함축하지 않습니다. 본 계약에 따른 어떤 약정 또는 권리에 대한 어느 당사자의 포기는 그러한 당사자가 정당하게 승인한 서면으로 기록되지 않는 한 유효하지 않습니다.
**15.10 제3자 수익자 없음.** 본 계약에는 제3자 수익자가 없습니다.
**15.11 가분성.** 본 계약의 어느 부분이 관할 법원에 의해 무효 또는 집행 불가능한 것으로 결정되는 경우, 그 조항은 최대한 허용되는 범위에서 집행되며 본 계약의 나머지 조항은 완전한 효력을 유지합니다.
**15.12 포기.** 어느 당사자가 본 계약의 어느 조항에 대한 상대방의 위반을 포기하는 것은 그 당사자에 의한 다른 또는 후속 위반의 포기로 작동하거나 해석되지 않습니다. 본 계약에 따른 어떤 약정 또는 권리에 대한 X의 포기는 X가 정당하게 승인한 서면으로 기록되지 않는 한 유효하지 않습니다.
**15.13 집단 소송 포기.** 법률이 허용하는 범위에서, 귀하는 또한 어떠한 명목상의 집단 소송, 집단 행동 또는 대표 행동 소송에서 원고 또는 집단 구성원으로 참여할 권리를 포기합니다.
**15.14 준거법 및 관할.** X Corp.가 본 계약의 계약 주체인 경우, 본 계약의 조건 및 이와 관련되거나 회사와 X 사이의 어떠한 분쟁도 저촉법/법률 선택 원칙을 고려하지 않고 텍사스 주법에 의해 규율됩니다. 국제 물품 매매 계약에 관한 유엔 협약(United Nations Convention on Contracts for the International Sale of Goods)은 본 계약에 적용되지 않습니다. 본 계약 또는 그 위반, 해지, 집행, 해석 또는 유효성(중재하기로 한 본 계약의 범위 또는 적용 가능성의 결정 포함)에서 발생하거나 이와 관련된 분쟁, 청구 또는 논쟁이 발생하는 경우, 회사는 X에 분쟁을 통지하고, X와 회사가 비공식적으로 분쟁을 해결하려고 시도할 수 있는 10영업일의 해결 기간을 제공하는 데 동의합니다. 10영업일 해결 기간 후에 X와 회사가 분쟁을 해결할 수 없는 경우, 회사는 본 계약에서 발생하는 분쟁이나 청구를 미국 텍사스 북부 지구 지방법원 또는 미국 텍사스 주 태런트 카운티에 소재한 주 법원에 제기하는 데 동의하며, 귀하는 그러한 법정에서의 대인 관할권에 동의하고 불편한 법정에 대한 이의를 포기합니다. 전술한 내용을 침해하지 않고, 귀하는 X가 단독 재량으로 귀하에 대해 우리가 가지고 있는 청구, 소송 원인 또는 분쟁을 청구에 대한 관할권과 재판적을 갖는 귀하가 거주하는 국가의 관할 법원에 제기할 수 있음에 동의합니다.
귀하가 미국의 연방, 주 또는 지방 정부 기관으로서 공식 자격으로 행위하고 위의 준거법, 관할 또는 재판적 조항을 법적으로 수락할 수 없는 경우, 그러한 조항은 귀하에게 적용되지 않습니다. 그러한 미국 연방 정부 기관의 경우, 본 계약 및 이와 관련된 모든 조치는 미국 법률(저촉법 참조 없이)에 의해 규율되며, 연방법이 없고 연방법에 따라 허용되는 범위에서, 텍사스 주법(법률 선택 제외)에 의해 규율됩니다.
X Internet Unlimited Company가 본 계약의 계약 주체인 경우, 본 계약의 조건 및 이와 관련되거나 회사와 X 사이의 어떠한 분쟁도 저촉법/법률 선택 원칙을 고려하지 않고 아일랜드 법률에 의해 규율됩니다. 당사자는 국제 물품 매매 계약에 관한 유엔 협약 또는 통일 컴퓨터 정보 거래법(Uniform Computer Information Transaction Act, UCITA)이 당사자가 사업을 하거나 법인화된 주와 관계없이 본 계약에 적용되지 않는다는 데 동의합니다. 본 계약 또는 그 위반, 해지, 집행, 해석 또는 유효성에서 발생하거나 이와 관련된 어떠한 분쟁, 청구 또는 논쟁도 저촉법 규정을 고려하지 않고 아일랜드의 관할 법원에만 배타적으로 제기되며 아일랜드 법률에 의해 규율되고, 이는 귀하와 우리 간의 반대되는 어떤 합의에도 불구하고 적용됩니다. 전술한 내용을 침해하지 않고, 귀하는 X가 단독 재량으로 귀하에 대해 우리가 가지고 있는 청구, 소송 원인 또는 분쟁을 청구에 대한 관할권과 재판적을 갖는 귀하가 거주하는 국가의 관할 법원에 제기할 수 있음에 동의합니다.
귀하는 X에 대해 청구를 제기할 수 있는 기간이 1년입니다. 귀하는 본 계약에서 발생하거나 이와 관련된 X에 대한 어떠한 청구도 분쟁을 일으키는 사건 또는 사실의 발생일로부터 1년 이내에 제기해야 합니다. 다만, 관련 법률이 해당 청구에 대한 통상적인 시효 기간이 합의에 의해 단축될 수 없다고 규정하는 경우는 예외입니다. 이 기간 내에 청구를 제기하지 않으면, 귀하는 그러한 사건 또는 사실에 기반한 어떤 종류나 성격의 청구 또는 소송 원인을 추구할 권리를 영원히 포기하며, 그러한 청구 또는 소송 원인은 영구적으로 금지되고, X는 그러한 청구에 관해 어떠한 책임도 지지 않습니다.
**15.15 금지 명령 구제.** 각 당사자는 X의 지적 재산권(X Materials 포함하나 이에 한정되지 않음) 및/또는 X의 기밀 정보를 보호하는 본 계약의 조항 위반 또는 위반 위협의 경우 금전적 손해가 부적절한 구제 수단이 될 것이며, 그러한 위반 또는 위협의 경우 X는 X가 자격이 있는 다른 구제 수단 외에도 X의 모든 권리를 보존하는 데 적절한 특정 이행을 위해, 보증금 게시 필요 없이, 그러한 예비 또는 금지 명령 구제(상대방 당사자가 그러한 조항을 위반하는 행위를 취하는 것을 금지하는 명령 포함)에 대한 자격이 있다는 데 동의합니다.
**15.16 업데이트.** X는 단독 재량으로 수시로 본 계약의 조건 및 여기에 언급된 정책을 업데이트할 수 있으며 회사에 이메일 통지 또는 아래 식별된 URL에 게시 통지를 제공합니다. 그러한 통지는 그러한 업데이트의 시행일을 표시합니다. 본 계약의 조건은 [https://docs.x.com/developer-terms/ads-api-agreement](/developer-terms/ads-api-agreement)에서 회사가 언제든지 볼 수 있도록 제공됩니다. 해당 통지에 제공된 시행일 이후 회사의 개별 제품 계속 사용은 그러한 업데이트에 대한 회사의 수락을 나타냅니다.
**15.17 완전 계약.** 본 계약(여기에 첨부된 부속서 포함)은 본 주제와 관련된 당사자 간의 완전한 계약을 구성하며 그러한 주제에 관한 모든 사전 또는 동시대의 제안, 이해, 커뮤니케이션 및 계약(구두 또는 서면)을 대체하고 갈음합니다. 본 계약에 대한 어떠한 수정도 서면으로 이루어져야 하며 당사자를 구속할 권한이 있는 각 당사자의 대표자에 의해 서명되어야 합니다.
## Exhibit A: 개별 제품 조건/X Ads API
본 개별 제품 조건에서 정의되지 않은 대문자 용어는 본 계약의 본문에 명시된 의미를 갖습니다. 회사가 "X Ads API Program"에 참여하는 범위에서 본 Exhibit A(Exhibit A-1 및 Exhibit A-2 포함)의 다음 조건이 적용됩니다:
### 1. X Ads API 서문; 접근.
**1.1 서문.** X 광고 애플리케이션 프로그래밍 인터페이스(API) 및 이와 함께 제공되는 문서, 코드 및 관련 자료(통칭 "**X Ads API**")로서, 회사에게 X Ads의 Campaign Management를 수행할 수 있게 하는 "읽기/쓰기(read/write)" 접근 및/또는 X Ads Campaign의 성과에 관한 특정 보고 Data에 대한 "읽기(read)" 접근을 제공합니다.
**1.2 API 접근.** X는 (단독 및 절대 재량으로) 회사에 "읽기" 또는 "읽기/쓰기" X Ads API 접근 권한을 부여할지 여부를 결정합니다. X는 X Ads API 접근 권한을 부여하기 위한 검토 프로세스를 구현할 수 있지만 그럴 의무는 없습니다.
### 2. Ads API 라이선스.
X가 회사에 X Ads API 접근 권한을 제공하기로 결정하고 회사가 본 계약의 조건을 계속 준수하는 것을 조건으로, X는 회사에 기간(Term) 동안 다음을 위한 제한적이고, 비독점적이며, 양도할 수 없고, 재실시할 수 없으며, 취소 가능한 라이선스를 부여합니다: (a) Client의 End Users에게 그러한 Client의 X Ads Campaigns에 관한 Data에 대한 접근을 제공하기 위한 목적으로 Company Service를 구현하기 위해 X Ads API를 사용(그리고 회사가 "읽기/쓰기" API 접근권을 갖는 경우, Company Service를 통해 X Ads의 Campaign Management를 가능하게 하기 위해); (b) 그러한 Client의 X Ads Campaigns를 최적화하는 목적으로만 Client의 End Users에게 Analytics Data Display Requirements(본 Exhibit A의 3조에 아래에서 정의됨)에 따라 Company Service 내에서만 집계된 형식으로 Data를 표시; (c) Data를 Company Service 내에 표시할 수 있도록 형식화하는 데 필요한 경우에만 Data를 수정; (d) Company Service가 X가 서면으로 승인하고 Analytics Data Display Requirements를 준수하는 형식으로만, 그리고 X가 서면으로 승인한 내보내기 메커니즘을 통해서만 Data를 내보낼 수 있게 함; 그리고 (e) X Ads API 및/또는 Data와 관련하여 사용할 수 있도록 X가 제공하는 X Marks를 사용하고 표시하는 것을 X를 Data의 출처로 기재하거나 본 계약에 따라 명시적으로 허용되는 방식으로만 (각 경우 X Trademark Guidelines에 따라).
### 3. 표시 요건, 통합 및 기타 요건.
회사의 X Ads API 및 Data의 구현 및 사용은 항상 다음을 준수해야 합니다: (a) Exhibit A-1로 첨부된 제품 요건("**Product Requirements**"); (b) Exhibit A-2로 첨부된 표시 요건("**Analytics Data Display Requirements**"); (c) X가 회사에 제공했거나 제공할 X Ads API에 대한 모든 기술 문서(엔드포인트 사양 또는 요건을 포함하나 이에 한정되지 않음); (d) X가 X Ads API 및 Data와 관련하여 지정한 온보딩 프로세스; (e) Our Policies; 그리고 (f) X가 회사에 제공할 수 있는 X Ads API 및 Data에 적용되는 기타 가이드라인 및 정책.
### 4. 준수.
회사는 X가 회사에 제공하거나 전달한 모든 지침(X Ads API에 대한 접근, 호출 및 사용에 대한 제한, 토큰, 속도 제한, 키, 비밀번호 또는 X Ads API에 대한 기타 로그인 자격 증명과 관련된 추가 제한 또는 금지 사항을 포함하나 이에 한정되지 않음)을 준수합니다. 그러한 지침은 X의 단독 및 절대 재량으로 결정됩니다. 회사는 Company Service를 검사하고 접근하기 위한 X의 요청을 준수하며, 여기에는 X Ads API 구현과 관련된 Company Service 코드를 X에 제공하여 Company Service 내의 X Ads API 통합 및 Data 표시가 Product Requirements 및 Analytics Data Display Requirements, X 품질 관리 및/또는 본 계약의 기타 조건을 준수하는지 확인하는 것이 포함되나 이에 한정되지 않습니다. X는 X Services를 개선하기 위해 회사의 X Ads API 사용을 모니터링할 수 있습니다.
### 5. X Ads 인벤토리 할당의 통제.
명확히 하고 본 계약의 다른 조건 또는 조항의 일반성을 제한하지 않으면서, 본 계약의 어떠한 내용도 회사 또는 Company Service가 X Ads API를 통해 특정 인벤토리 또는 X Ads 범주에 접근할 수 있음을 나타내거나 함축하려는 의도가 아니며, X는 (단독 및 절대 재량으로) 회사 또는 Company Service가 접근할 수 있는 X Ads 인벤토리의 할당을 수시로 제한 없이 제한하기로 선택할 수 있습니다(예: 판매 채널, 직접 대 비직접 클라이언트 관계, 에이전시 관계 등에 관한 X의 전략적 결정으로 인한, 제한 없이).
### 6. X Ads 기능, API 호출 및 기능성의 통제.
명확히 하고 본 계약의 다른 조건 또는 조항의 일반성을 제한하지 않으면서, 본 계약의 어떠한 내용도 회사 또는 Company Service가 X Ads API를 통해 특정 X Ads 기능, API 호출 또는 기능성에 접근할 수 있음을 나타내거나 함축하려는 의도가 아니며, X는 (단독 및 절대 재량으로) 회사 또는 Company Service가 접근할 수 있는 X Ads 기능, API 호출 및/또는 기능성을 수시로 제한 없이 제한하기로 선택할 수 있습니다(어떠한 이유든 이유 없이).
### 7. 지역 데이터.
회사는 X Ads API를 사용하거나 이에 접근하여 Data 또는 그 밖에 포함된 장소 또는 기타 지리적 위치 정보를 집계, 캐시 또는 저장하지 않을 것이며(다른 사람이 그렇게 하도록 허용하지 않을 것입니다).
### 8. 삭제.
X가 X Ads API를 통해 또는 그 밖에 요청하는 경우, 회사는 즉시: (a) X가 삭제되었거나 만료되었다고 보고하는 Data를 Company Service에서 삭제; (b) X가 변경된 공유 옵션의 대상이라고 보고하는 Data에 대한 회사의 취급 변경; 그리고 (c) X가 수정되었다고 보고하는 Data를 Company Service에서 수정합니다. 회사는 Company Service에 의해 X Service로 전송되는 X Ads의 품질에 대해 책임을 집니다. X는 회사 또는 Client의 반대할 만한 사용에 대해 X Ads API에 대한 접근을 취소하고/하거나 해당하는 경우 X Service에서 특정 X Ads를 제거할 권리를 유보합니다.
### 9. 업데이트.
회사는 X가 수시로 X의 단독 및 절대 재량으로 X Ads API를 업데이트하거나 수정할 수 있음을 인정합니다(각 경우 "**Update**"). X와 회사가 사전에 서면(이메일로 충분)으로 상호 합의하지 않는 한, 회사는 X Ads API의 가장 최신 버전을 구현하고 사용해야 하며, X가 회사에 Update를 통지한 날로부터 30일 이내에 회사의 단독 비용과 지출로 그러한 Update의 결과로 요구되는 Company Service의 변경 사항을 만들어야 합니다. 회사는 해당하는 경우 Update를 가능하게 하기 위해 X가 제공한 모든 도구(있는 경우)를 구현합니다. Update는 Company Service가 X Ads API에 접근하거나 이와 통신하거나 Data를 표시하는 방식에 부정적인 영향을 미칠 수 있습니다. 그러한 Update 이후 회사가 X Ads API에 계속 접근하거나 이를 사용하는 것은 Update에 대한 구속력 있는 수락을 구성합니다.
### 10. 지원.
회사는 Company Service 사용(Ads Product와 관련된 문제 포함)에 관해 Client 및 그 End Users에게 모든 지원 및 기술 지원을 제공할 책임이 있습니다. X는 회사 또는 Client 또는 그 End Users에게 직접 지원 또는 기술 지원을 제공할 의무가 없으며, 회사는 Client 또는 그 End Users에게 X가 그러한 지원을 제공하기 위해 이용 가능하다고 표현하지 않을 것입니다.
## Exhibit A-1: 제품 요건
Company Service는 마케터가 X Ads 캠페인을 보다 효율적으로 최적화하고, X의 실시간 대화를 활용하며, 사용자 경험을 개선하는 X Ads를 개발할 수 있게 해야 합니다.
따라서 Company Service는 항상 다음의 요건을 충족해야 합니다:
### 1. 제품 가격. 수익화 없음.
Company Service에 대한 유료 접근은 지출의 고정 또는 가변 비율 수수료 구조로 가격이 책정되어야 합니다. 회사는 Company Service에 대한 회사의 표준 요금을 초과하여 Company Service를 통한 X Ads 및/또는 Data에 대한 접근에 대해 Client에게 프리미엄을 부과하지 않을 것입니다.
### 2. 투명성.
**2.1 지출.**
2.1.1 회사가 Client 및 그 End Users에게 제공하는 모든 가격 보고서는 (i) X의 기본 지표(예: 해당하는 경우, CPE/CPF)로 X Ads 지출 및 (ii) Company Service 사용에 대해 부과된 수수료를 명확하게 명시하고 항목별로 기재해야 합니다. 또한 회사는 항상 마지막 클릭 어트리뷰션 지표(예: CPC) 또는 기타 보고 지표(예: CPM)에 인접하여 CPE 또는 CPF 지표(또는 기타 관련 X 기본 지표)를 포함해야 합니다.
2.1.2 Company Service는 회사가 X Ads API를 통해 제공되는 모든 지표에 대해 보고할 수 있는 기능을 포함하는 셀프 서비스 보고 대시보드를 포함할 것입니다.
**2.2 Data.** 회사는: (i) X Integration(본 Exhibit A-1의 6.3조에서 아래에 정의됨)과 관련하여 당시 유효한 Analytics Data Display Requirements에 따라 Company Service 내의 최신 Data를 유지하기 위해 상업적으로 합리적인 노력을 기울일 것이며; (ii) Client의 X Ads Campaigns 및/또는 관련 분석 데이터에 관한 정보에 내재된 중대한 지연을 Client 및 그 End Users에게 명확하게 공개할 것입니다.
### 3. 계정.
각 End User는 Company Service에 접근하기 위한 별도의 계정(고유 사용자 이름 및 비밀번호 포함)을 받아야 합니다.
### 4. Company Service.
특정 Client용 Company Service의 각 맞춤화 버전(특정 Client용 화이트라벨 버전의 Company Service를 포함하나 이에 한정되지 않음)은 X가 사전에 서면(이러한 목적을 위해 이메일로 충분)으로 승인해야 합니다.
### 5. Client 및 계정 관리.
**5.1** Client에는 X Ads Campaigns를 Company Service에서 신속하고 쉽게 분리하고 X Ads 계정에 대한 배타적, 직접적 통제를 되찾을 수 있는 능력이 제공되어야 합니다.
**5.2** Client와 그 End Users만이 Company Service를 통해 그러한 Client의 계정 데이터 또는 기능을 볼 수 있도록 허용되어야 합니다.
### 6. 기타 요건.
**6.1** X 기능을 복제하는 Company Service 기능성은 관련 X Trademark Guidelines에 따라 X의 명명 규칙 및 기능 이름을 활용할 것입니다.
**6.2** 당사자가 사전에 서면으로 상호 합의하지 않는 한, 회사는 Company Service의 사용자 인터페이스에 구현된 그러한 자료의 집계된 파생물을 제외하고 Client 및 그 End Users 또는 기타 제3자에게 Data에 대한 접근을 제공하지 않을 것입니다.
**6.3** 회사는 X Ads API 구현 및 Company Service 내의 Data 통합 및 표시(통칭 "**X Integration**")가 본 조에서 설명된 프로세스를 통해 X에 의해 사전에 승인될 때까지 X Materials를 제3자(Client 또는 그 End Users 포함)에게 상업화, 마케팅 또는 접근을 제공할 수 없습니다. 회사는 X가 X Integration을 검토할 수 있도록 X에게 Company Service에 대한 접근을 제공할 것입니다. X는 X Integration의 승인 또는 거절(X의 단독 재량으로) 여부를 서면(이메일로 충분)으로 회사에 알립니다. 기간 동안, 회사는 X Integration에 영향을 미치는 Company Service의 변경 사항을 X에 제출할 것이며, X는 단독 재량으로 서면(이메일로 충분)으로 이를 승인하거나 거절할 권리를 갖습니다.
## Exhibit A-2: 분석 데이터 표시 요건
이 Analytics Data Display Requirements는 회사가 Company Service 내에서 Data를 표시할 수 있는 방법을 규율합니다. 회사는 항상 이 Analytics Data Display Requirements를 준수하기로 동의합니다.
### 정의된 지표
Data를 표시하는 Company Service에 표시된 모든 캠페인은 다양한 캠페인 목표(각각 "**Campaign Objective**")와 관련된 특정 X 정의 지표를 포함해야 하며, 이러한 지표는 다음의 엔드포인트 및 공식을 기반으로 회사가 계산해야 합니다: [https://docs.x.com/x-ads-api/analytics#metrics-by-objective](https://docs.x.com/x-ads-api/analytics#metrics-by-objective)(또는 X가 수시로 선택할 수 있는 기타 후속 URL).
### 표시 가이드라인
**1.** 주어진 Campaign Objective에 대한 해당 정의된 지표(본 Exhibit A-2의 정의된 지표 섹션에서 위에서 설명함)는 Company Service 내에서 캠페인이 표시될 때마다 표시되어야 합니다.
**2.** Company Service가 유기적 게시물 분석 데이터를 표시하는 경우, 회사는 회사의 유기적 게시물 분석 데이터 구현, 사용 및 표시와 관련하여 [https://docs.x.com/developer-terms/agreement](/developer-terms/agreement)에 위치한 X Developer Agreement & Policy를 준수해야 합니다.
**3.** Company Service가 Data와 나란히 제3자 네트워크에서 실행되거나 제3자 게시자에 의해 실행된 캠페인에 대한 지표(즉, "크로스 채널 지표")를 표시하는 경우, 다음 요건 및 제한이 적용됩니다:
**3.1** Company Service에서 Data와 나란히 표시되는 크로스 채널 지표는 그러한 캠페인에 대한 해당 X 정의 Campaign Objective 지표와 같은 캠페인 목표 지표 범주만을 포함할 수 있습니다(본 Exhibit A-2의 정의된 지표 섹션에서 위에서 설명한 바와 같음).
예시로만 - 광고주가 제3자 네트워크에서 앱 설치 캠페인을 실행하는 경우, 앱 설치 Campaign Objective에 대한 해당 X 정의 지표와 같은 범주의 크로스 채널 지표만 Data와 나란히 표시할 수 있습니다.
**3.2** 크로스 채널 지표를 표시하기 위한 데이터 집계는 집계된 지표가 (모든 제3자 네트워크/게시자에 걸쳐) 해당 X 정의 Campaign Objective 지표와 동일한 캠페인 목표와 관련된 지표 범주에 대해 참조될 수 있는 경우가 아니면 허용되지 않습니다(본 Exhibit A-2의 정의된 지표 섹션에서 위에서 설명한 바와 같음). 예시로만 - 네트워크 A, 네트워크 B 및 네트워크 C에 대한 총 참여를 집계하는 것은 모든 채널에 걸친 참여율이 동일한 공식을 사용하여 계산되지 않는 경우 허용되지 않을 것입니다.
**4.** Company Service가 X 이외의 제3자로부터 소스가 된 지표 범주("**제3자 소스 지표**")를 표시하는 경우, 다음 요건 및 제한이 적용됩니다:
**4.1** 위 3조에서 명시된 크로스 채널 지표 표시에 적용되는 동일한 요건 및 제한이 제3자 소스 지표 표시에 적용됩니다.
**4.2.** Company Service에서 캠페인에 대해 Data와 나란히 표시되는 제3자 소스 지표는 그러한 캠페인에 대한 해당 X 정의 Campaign Objective 지표와 같은 캠페인 목표 지표 범주여야 합니다(본 Exhibit A-2의 정의된 지표 섹션에서 위에서 설명한 바와 같음). 예시로만:
* 회사가 제3자 소스에서 링크 클릭 및 클릭률 지표를 표시하는 경우, 회사는 제3자 소스 링크 클릭 및 클릭률 지표와 나란히 X의 클릭 및 클릭률 지표를 표시할 것입니다.
* 회사 또는 그 Client가 Promoted 게시물에서 웹사이트 클릭을 추적하기 위해 제3자 추적 솔루션을 사용하고 그러한 데이터가 Company Service에 표시되는 경우, 회사는 그러한 제3자 소스 데이터와 나란히 X의 링크 클릭, 클릭률, 링크 클릭당 비용 및 CPA를 표시해야 합니다(이용 가능한 경우).
**4.3** 본 Exhibit A-2의 4.2조에도 불구하고, 제3자 소스 지표가 X Conversion Tracking Partner(아래 정의)가 제공하는 제3자 추적 솔루션에서 나온 경우, X는 X Ads API를 통해 전달되는 Data만(X Conversion Tracking Partner가 전달하는 해당 데이터가 아님) Company Service에 표시되어야 한다고 요구합니다. 다만, X가 (각 경우) 사전에 서면으로 달리 합의하지 않는 한 그렇습니다. 명확히 하기 위하여, 회사는 X Ads API를 통해 전달된 Data와 나란히 또는 그 대신에 X Conversion Tracking Partner에서 소스가 된 데이터를 표시하지 않을 것입니다. 본 Exhibit A-2에서 사용된 "**X Conversion Tracking Partner**"는 X의 단독 및 절대 재량으로 X에 의해 지정된 승인된 X 전환 추적 파트너를 의미합니다.
## Exhibit B: 개별 제품 조건/Custom Audiences
본 개별 제품 조건에서 정의되지 않은 대문자 용어는 본 계약의 본문에 명시된 의미를 갖습니다. 회사가 X Custom Audiences Program을 사용하거나 이에 접근하는 범위에서 본 Exhibit B의 다음 조건이 적용됩니다:
### 1. Custom Audiences.
**1.1 서문.** X Custom Audiences Program은 X Service에서 광고 캠페인의 타게팅을 위해 특정 사용자 세그먼트(각각 "**Custom Audience**")의 가져오기 및 생성을 허용합니다. 당사자들은 X Custom Audiences Program을 이용하기 위해 회사, 그 Client 또는 X가 승인한 제3자 서비스("**Data Partner**")가 X 사용자와 매칭을 완료하고 Custom Audiences를 생성할 수 있도록 해시된 사용자 또는 디바이스 집합(이메일, 쿠키, 디바이스 ID, 추적 픽셀 등을 포함할 수 있음)을 X에 제공해야 함을 인정합니다. 특정 클라이언트를 대신하여 생성된 Custom Audiences는 각 그러한 Client의 X Ads 계정에 저장되어 회사 또는 Client가 X Service에서 광고를 타게팅하거나, 해당하는 경우 리타게팅하는 데 사용됩니다.
**1.2 데이터 사용 및 옵트아웃.** Custom Audiences Program과 관련하여 사용된 데이터에 관해, [https://privacy.x.com/en/for-our-partners/global-dpa](https://privacy.x.com/en/for-our-partners/global-dpa)에 있는 Data Protection Addendum에 명시된 의무 외에도, 회사는 다음에 동의하며 해당하는 경우 Data Partner(들)이 다음에 동의하도록 보장합니다: (i) 회사 또는 그러한 Data Partner(해당하는 경우)는 그러한 데이터 사용을 위한 모든 필요한 권리, 동의, 포기, 라이선스를 확보했으며, (ii) 회사 또는 그러한 Data Partner(해당하는 경우)는 데이터가 수집되는 사용자에게 사용자의 관심사에 대한 광고 타게팅을 위해 회사가 X에 제공하는 데이터의 수집, 사용 및 공유를 완전히 공개하는 법적으로 충분한 통지, 그리고 사용자가 여기([https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads](https://help.x.com/safety-and-security/privacy-controls-for-tailored-ads))에 설명된 방법을 통해 X의 관심 기반 광고를 옵트아웃할 수 있는 방법에 대한 법적으로 충분한 지침을 제공했습니다. 회사가 Custom Audiences Program과 관련하여 그리고/또는 Custom Audience를 생성하는 데 사용하는 데이터에는 회사, 그 Data Partner 또는 회사를 대신하여 제3자가 자신의 데이터를 사용하는 것을 옵트아웃한 사용자의 데이터가 포함되지 않을 것입니다. 회사가 X에 제공된 오디언스에 그러한 사용자가 포함된 후 사용자 옵트아웃을 받은 경우, 회사는 즉시, 그러나 24시간마다 한 번 이하의 빈도로, 그러한 사용자를 그러한 사용자가 포함되었던 Custom Audience에서 제거해야 합니다. 회사는 X가 선택하고 Data Partner가 수락 가능한 형식(해당하는/해당하는 경우)으로 데이터를 제공할 것입니다. 본 계약의 조건 외에도, 회사의 X Custom Audiences 프로그램 사용은 [X Master Services Agreement](https://legal.x.com/ads-terms.html) 및 Custom Audiences Program T\&Cs 및 관련 정책(X의 전환 추적 및 Custom Audiences 정책 포함)의 조건에 따라 규율됩니다. 이는 [https://legal.x.com/ads-terms.html](https://legal.x.com/ads-terms.html) 및 [https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences](https://business.x.com/en/help/ads-policies/campaign-considerations/policies-for-conversion-tracking-and-custom-audiences)에 있습니다.
**1.3 추가 프로그램 요건.** 회사의 X Custom Audience Program 접근 및 사용은 추가로 X가 회사에 제공한 기술 지침 및 프로그램 정책("**Program Integration Spec**")의 준수를 조건으로 합니다. 회사와 X는 회사가 X에 Custom Audiences를 가져오거나 업로드할 프로세스에 상호 합의할 것입니다.
### 2. 공유 가능한 오디언스.
위의 1.1조에 명시된 어떠한 반대에도 불구하고, 회사에 대한 서비스로서, 회사의 요청과 회사의 단독 재량으로, X는 회사를 위해 생성된 Custom Audiences를 그룹화된 X 광고주 계정 및/또는 X @handles 사이에서 및/또는 X Service의 제3자와 그 밖에 "공유"할 수 있도록 회사에 허용할 수 있습니다. 여기에서 사용된 오디언스 "공유"는 회사가 X에게, 제한 없이, 그룹화된 X 광고주 계정 및/또는 X @handles 및/또는 제3자가 "공유된" Custom Audience에 대해 광고 캠페인에 접근하고, 사용하고, 타게팅할 수 있도록 지시하는 것을 의미합니다. 회사는 회사가 X에 부여한 지시에 따라 그러한 오디언스 데이터를 공유하는 데 필요한 모든 권리 및 권한을 보유하고 있음을 진술하고 보증합니다. 회사가 오디언스 데이터를 제공하고 있고/있거나 제3자(Client 포함하나 이에 한정되지 않음)를 대신하여 Custom Audiences를 관리하는 경우, 회사는 그러한 당사자의 대리인으로서 제3자를 대신하여 그러한 데이터를 사용하고, X에 여기에 설명된 권리를 부여하며, 그러한 제3자를 본 계약의 조건에 구속시킬 권한을 갖고 있음을 진술하고 보증합니다. 전술한 내용에도 불구하고, 본 조의 어떠한 내용도 X가 여기에 설명된 Custom Audiences "공유"를 가능하게 하는 기능성(또는 그 일부)을 회사 또는 기타 제3자(Client 포함하나 이에 한정되지 않음)에게 언제든지 이용 가능하게 만들도록 요구하지 않습니다.
## Exhibit C: 개별 제품 조건/X Marketing Partner (TMP) 프로그램
본 개별 제품 조건에서 정의되지 않은 대문자 용어는 본 계약의 본문에 명시된 의미를 갖습니다. 회사가 "X Marketing Partner program"(이하 "**TMP**")에 참여하는 범위에서 본 Exhibit C(Exhibit C-1 포함)의 다음 조건이 적용됩니다:
### 1. X Marketing Partner 프로그램.
X가 회사의 "Advanced" 분류 상태 신청을 승인하고, 회사가 기간 내내 그러한 분류 상태를 유지하는 경우, X는 언제든지 X의 단독 및 절대 재량으로 회사를 TMP(또는 X가 수시로 선택할 수 있는 기타 후속 프로그램 이름)의 일부로 자격을 부여하기로 선택할 수 있습니다. 명확히 하기 위하여, X는 회사가 "Advanced" 분류 상태를 달성했거나 유지하는지 여부와 관계없이, 회사를 TMP에 참여시키기 위해 선택할 필요가 없습니다. 또한 X는 언제든지 X의 단독 및 절대 재량으로, 어떤 이유로든 회사에 대한 통지로 회사의 TMP 참여를 종료하거나 중지하기로 선택할 수 있으며, 이 경우 TMP 참여와 관련된 어떤 혜택도 받을 수 있는 회사의 자격이 즉시 종료됩니다(그러한 선택에 대한 X의 추가 통지 없이). X Marks 사용을 규율하는 X Trademark Guidelines 외에도, 회사는 TMP 참여와 관련하여 X가 제공한 Badges(Exhibit C-1에서 정의)의 사용을 규율하는 Exhibit C-1에 명시된 조건도 준수해야 합니다. 모든 Badges(Exhibit C-1에서 정의)는 본 계약에 따른 X Marks로 간주됩니다.
### 2. TMP 외의 Badge 사용 금지.
명확히 하기 위하여, 회사가 현재 X(단독 및 절대 재량으로)에 의해 TMP 회원으로 자격이 부여되지 않은 경우, (i) 회사는 Badges(Exhibit C-1에서 정의) 사용을 포함하여 TMP 참여와 관련된 혜택을 받을 자격이 없으며, (ii) 회사가 TMP에 참여하거나 이와 관련이 있음을 암시하는 것이 금지됩니다.
## Exhibit C-1: X Marketing Partner 프로그램 조건
아래에 명시된 X Marketing Partner 프로그램 조건(참고로 여기에 포함되는 아래에 나타나거나 언급된 링크된 조건 포함, 통칭 "**TMP Partner Terms**")은 "X Marketing Partner" 프로그램에의 참여를 규율합니다. 회사가 X의 단독 및 절대 재량으로 "X Marketing Partner" 프로그램에 참여할 자격이 있는 범위에서, 회사는 회사의 "X Marketing Partner" 프로그램 참여 동안 항상 TMP Partner Terms의 조건을 준수하기로 동의합니다. 이 TMP Partner Terms는 본 계약의 대상이며 본 계약에 의해 규율됩니다. 본 Exhibit C-1에서 사용되고 TMP Partner Terms에서 달리 정의되지 않은 대문자 용어는 본 계약에서 부여된 의미를 갖습니다.
### 1. TMP 프로그램.
X가 회사에게 X가 회사를 "X Marketing Partner"로 자격을 부여했다고 통지하면, Partner는 [https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners)에 설명된 "X Marketing Partner" 프로그램의 회원이 될 것이며, X가 TMP와 관련하여 이용 가능하게 하는 TMP 뱃지 및 기타 관련 마크(통칭 "**Badges**")에 대한 접근을 부여받을 것이며, 사용은 본 계약의 조건에 따라 이루어집니다.
### 2. X로부터의 라이선스.
이 TMP Partner Terms의 조건에 따라, 그리고 회사가 본 계약을 계속 준수하는 것을 조건으로, X는 이로써 회사에게, 회사가 수락하는, TMP에서 "X Marketing Partner"로서의 회사의 자격을 홍보하고 이와 함께만 Badges를 복사하고 표시할 수 있는 비독점적이고, 로열티가 없으며, 양도할 수 없고, 재실시할 수 없으며, 취소 가능한 라이선스를 부여합니다.
### 3. 제한 사항.
본 계약의 엄격한 준수는 항상 요구되며, 본 계약을 위반한 Badges 사용은 회사의 Badges 사용과 관련된 어떠한 라이선스도 자동으로 종료시킬 것입니다.
**3.1** 회사는 Badges의 비율, 색상 또는 글꼴을 변경하거나 Badges에 요소를 추가하거나 제거하는 것을 포함하되 이에 한정되지 않는 어떠한 방식으로도 Badges를 변경할 수 없습니다.
**3.2** 회사는 X의 후원이나 지지에 대한 거짓된 감각을 함축하는 어떠한 방식으로도 Badges를 사용할 수 없습니다.
**3.3** 회사는 X, 그 제품 또는 서비스를 폄하하거나 X의 단독 재량으로 Badges에 대한 X의 영업권을 감소시키거나 훼손할 수 있는 방식으로 Badges를 사용할 수 없습니다.
**3.4** 회사는 X 또는 회사의 TMP 참여와 관련된 회사의 제품 및/또는 서비스 이외의 다른 제품이나 서비스를 지칭하기 위해 Badges를 사용할 수 없습니다.
**3.5** Badges는 각 마크의 양쪽 사이에 합리적인 간격을 두고, 다른 시각적, 그래픽 또는 텍스트 요소와 함께 단독으로 나타나야 합니다.
**3.6** Badges는 Badges 전체의 가독성 또는 표시를 방해하는 어떠한 방식으로도 제시되거나 배치되어서는 안 됩니다.
**3.7** 회사는 모든 Badges를 [https://business.x.com/en/advertising/partners](https://business.x.com/en/advertising/partners)(또는 X가 수시로 선택할 수 있는 기타 후속 URL)에 링크하거나, Badges를 표시하는 자료에 다음 귀속을 표시해야 합니다: "'X Marketing Partner' 프로그램 뱃지, X 및 X 로고는 X Corp. 또는 그 계열회사의 상표입니다."
### 4. 프로그램 요건.
Badges 사용은 항상 [X Trademark Guidelines](https://about.x.com/who-we-are/brand-toolkit) 및 TMP 참여와 관련하여 X가 회사에 전달한 기타 요건(통칭 "**TMP Program Requirements**")의 대상이며 이에 의해 규율됩니다(제한 없이). 회사는 참고로 여기에 포함되고 X에 대한 요청 시 하드카피로 이용 가능한 TMP Program Requirements에 동의합니다. TMP Program Requirements는 여기에 부여된 Badges에 대한 라이선스를 확장하거나 연장하지 않습니다. 회사는 X가 명시적으로 승인한 목적을 위해서만 Badges를 사용할 수 있으며, 회사의 사용은 (i) 이 TMP Partner Terms 및 (ii) TMP Program Requirements의 가장 최신 버전을 준수해야 합니다. 이 TMP Partner Terms와 TMP Partner Requirements 간에 충돌이나 불일치가 있는 범위에서, 이 TMP Partner Terms가 우선합니다.
### 5. X에 대한 라이선스.
회사는 이로써 X에게 다음을 위한 완전 지불된, 비독점적, 전 세계적, 재실시 가능한 라이선스를 부여합니다: (i) TMP와 관련하여 사용하기 위해 회사의 상표를 사용하고 표시하고, (ii) X의 비상업적, 내부 평가, 테스트 및 감사를 위해 TMP와 관련된 회사의 제품 및/또는 서비스를 사용하고, (iii) X가 TMP에서 "X Marketing Partner"로서의 회사의 자격을 강조할 수 있도록 사례 연구 또는 기타 자료를 개발하고 게시하며(TMP와 관련된 회사의 제품 및/또는 서비스를 포함하나 이에 한정되지 않음), (iv) TMP에서 "X Marketing Partner"로서의 회사의 자격과 관련된 TMP와 관련된 마케팅 자료를 제작합니다(TMP와 관련된 회사의 제품 및/또는 서비스를 포함하나 이에 한정되지 않음).
### 6. 프로그램 자격.
**6.1 프로그램 자격.** X는 수시로 TMP에서 회사의 회원 자격을 검토하고, X의 단독 및 절대 재량으로 특정 역량 및/또는 TMP 전체에서 회사를 재자격 부여하거나 자격 박탈할 권리를 유보합니다.
**6.2 회사 제품 또는 서비스의 변경.** 회사가 TMP와 관련된 회사의 제품 및/또는 서비스에 중대한 변경을 계획하는 경우, 회사는 그러한 변경 사항 출시 전에 회사의 업데이트된 제품 또는 서비스를 검토하여 TMP 자격이 계속 유효한지 판단하기 위해 최소 30일의 역일을 X에 제공할 것입니다. Badges의 추가 사용 전에 X에 의해 업데이트된 제품 또는 서비스에 대한 재자격이 부여되어야 합니다. X는 새로운 역량에서의 자격에 대한 회사의 요청에 응답하기 위해 상업적으로 합리적인 노력을 기울일 것입니다. 회사가 자발적이든 비자발적이든 그리고/또는 법률의 작용에 의해(제한 없이 합병, 인수 또는 자산 매각과 관련하여, 양도 당사자가 존속 또는 소멸 주체인지 여부와 관계없이) 제3자에 의해 전부 또는 일부가 합병, 인수 또는 그 밖의 지배권 변경을 겪는 경우, 회사는 Badges의 추가 사용 전에 재자격을 위해 TMP와 관련된 회사의 모든 제품 및/또는 서비스를 X에 제출해야 합니다.
### 7. 중지 및 종료.
X는 언제든지, 어떤 이유로든, 회사에 대한 통지를 제공함으로써, 단독 재량으로, 이 TMP Partner Terms, 여기에 회사에 부여된 권리 및/또는 회사의 TMP 참여를 즉시 종료하거나 중지할 수 있습니다. 회사는 X에 90 역일 통지를 제공함으로써 회사의 TMP 참여를 종료할 수 있습니다. 이 TMP Terms의 종료 및/또는 회사의 TMP 참여 종료 시, 여기에 부여된 모든 라이선스는 즉시 만료되며, 회사는 모든 Badges 사용을 중단해야 합니다. 어느 당사자도 본 계약에 따라 허용된 이 TMP Partner Terms의 종료로만 발생한 손해에 대해 상대방에게 책임을 지지 않습니다.
### 8. 수정.
X는 언제든지 이 TMP Partner Terms 및/또는 Badges의 조건을 수정하고 Badges의 무단 또는 부적합 사용에 대해 적절한 조치를 취할 권리를 단독 재량으로 행사할 수 있음을 유보합니다. 회사가 Badges 사용에 대한 질문이 있는 경우 지원을 위해 [trademarks@x.com](mailto:trademarks@x.com)으로 연락하거나 다음으로 서면 문의: X Corp., Attention: Legal Department, 865 FM 1209, Building 2, Bastrop, TX 78602, USA.
# X 개발자 계약
Source: https://docs.x.com/ko/developer-terms/agreement
X 개발자 계약은 X API 및 개발자 플랫폼 사용에 대한 법적 조건을 명시하며, 라이선스, 제한 사항, 준수 의무를 다룹니다.
최종 업데이트: 2026년 4월 27일
"동의 및 구독"을 클릭하거나, 유료 서비스에 대한 반복 구독료를 계속 지불하거나, 그 밖의 방법으로 라이선스 자료에 접근하거나 이를 사용함으로써 귀하는 본 계약의 조건에 동의합니다. 구독은 아래에 설명된 대로 취소될 때까지 자동으로 갱신됩니다. 구독하려면 인증된 전화번호가 필요합니다. 다른 플랫폼을 통해 구독한 경우 해당 플랫폼을 통해 구독을 관리하세요.
본 X 개발자 계약("**계약**")은 귀하(본 계약에서 "**귀하**"라고 함)와 X 사이의 법적 구속력이 있는 계약이며, 라이선스 자료(아래 정의됨)에 대한 귀하의 접근 및 사용을 규율하며, 유료 서비스(아래 정의됨)도 포함합니다.
라이선스 자료(아래 정의됨)에 접근하거나 이를 사용하거나, 본 계약 조건 또는 유료 서비스에 대한 반복 구독 결제를 수락하는 버튼을 클릭함으로써, 귀하는 본 계약 조건에 구속되는 데 동의합니다. 본 계약 조건을 이해하지 못하거나 그 어떤 부분도 수락하지 않는 경우, 귀하는 어떠한 라이선스 자료도 사용하거나 접근할 수 없습니다. X와 구속력 있는 계약을 체결할 법적 연령에 도달하지 못했거나, 관련 법률에 따라 라이선스 자료의 사용 또는 수령이 금지된 경우 라이선스 자료를 사용하거나 본 계약을 수락할 수 없습니다. 유료 서비스를 구매하고 사용하려면 (i) 만 18세 이상이거나 귀하가 거주하는 관할 지역의 법률에 따라 결정된 성년 연령에 도달해야 하거나 (ii) 유료 서비스를 구매하고 사용하기 위한 부모 또는 보호자의 명시적 동의가 있어야 합니다. 귀하가 부모 또는 법적 보호자로서 자녀(또는 귀하가 보호자인 자녀)에게 유료 서비스를 구매하거나 사용하도록 허용하는 경우, 귀하는 본 계약의 조건이 귀하에게 적용되며, 본 계약을 준수하고, 자녀의 유료 서비스 활동 및 자녀도 본 계약의 조건을 준수하도록 하는 데 대한 책임이 있다는 데 동의합니다. 어떠한 경우에도 [**X 서비스 약관**](https://x.com/tos)의 "서비스를 이용할 수 있는 사람" 섹션에 명시된 바와 같이, X 서비스 약관에 정의된 "서비스"를 이용하려면 만 13세 이상이어야 합니다. 회사, 조직, 정부 또는 기타 법인을 대신하여 본 계약을 수락하거나 라이선스 자료를 사용하는 경우, 귀하는 그러한 회사, 조직, 정부 또는 기타 법인을 본 계약에 구속시킬 권한이 있음을 진술하고 보증하며, 이 경우 본 계약에서 사용된 "귀하" 및 "귀하의"라는 단어는 그러한 법인을 지칭합니다. 본 계약 조건에 동의하지 않는 경우 귀하는(귀하의 어떠한 직원도) 라이선스 자료에 접근하거나 이를 사용할 수 없습니다.\*\*\*\*
**I. 정의.**
본 계약에서 다음 정의가 적용됩니다:
1. "**Developer Site**"는 [**https://developer.x.com/**](https://developer.x.com/)에 위치한 X의 개발자 사이트를 의미합니다.
2. "**Direct Message**"는 X의 다이렉트 메시지 기능을 사용하여 한 사용자가 하나 이상의 특정 사용자에게 X 애플리케이션에서 보내는 비공개 메시지를 의미합니다.
3. "**지식재산권**"은 전 세계의 모든 저작권, 저작인격권, 특허권, 상표권 및 기타 지식재산권 또는 이와 유사한 권리(등록 여부에 관계없이)를 의미합니다.
4. "**라이선스 자료**"는 개별적으로 또는 집합적으로 X API 및 X 콘텐츠를 의미합니다.
5. "**유료 서비스**"는 관련 기능 및 본 계약에 적용되는 반복 요금 지불의 대가로 접근하는 라이선스 자료의 기능 또는 특징을 의미합니다. 본 계약에서 달리 명시하지 않는 한 "라이선스 자료"에 대한 모든 언급은 유료 서비스를 포함하는 것으로 간주됩니다.
6. "**Payment Portal**"은 귀하의 라이선스 자료 이용에 대한 옵트인, 유료 서비스 구독 관리, 유료 서비스 결제 수단 관리 및 계정 정보 업데이트를 위해 귀하에게 제공되는 온라인 포털을 의미합니다.
7. "**Services**"는 X 콘텐츠를 표시하거나 라이선스 자료를 사용하는 귀하의 서비스, 웹사이트, 애플리케이션 및 기타 제공물(연구 포함)을 의미합니다.
8. "**Post**"는 X 애플리케이션을 통해 배포되는 짧은 형식의 텍스트 및 멀티미디어 기반 메시지를 의미합니다.
9. "**X**"는 (a) 귀하의 주된 사업장이 유럽 연합, EFTA 국가 및 영국 외부에 있는 경우 X Corp. (865 FM 1209, Building 2, Bastrop, TX 78602, USA)를, 또는 (b) 귀하의 주된 사업장이 유럽 연합, EFTA 국가 또는 영국에 있는 경우 X Internet Unlimited Company (One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland)를 의미합니다.
10. "**X API**"는 Developer Site를 통해 X가 제공하는 X 애플리케이션 프로그래밍 인터페이스(각각 **"API"**), 소프트웨어 개발 키트(각각 **"SDK"**), 관련 도구, 문서, 데이터, 기술, 코드 및 기타 자료를 의미합니다.
11. "**X 애플리케이션**"은 X의 실시간 정보 서비스, 일반적으로 "X"라고 불리며, 현재 X가 웹사이트 및 X 소유, 운영 또는 통제 모바일 애플리케이션, 소셜 플러그인, 애플리케이션 프로그래밍 인터페이스에서 제공하는 서비스를 의미합니다.
12. "**X 콘텐츠**"는 게시물, 각 게시물에 대해 생성된 고유 식별 번호, X 최종 사용자 프로필 정보, 그리고 X API 또는 X가 승인한 기타 수단을 통해 귀하에게 제공되는 기타 데이터 및 정보, 그리고 이들의 사본 및 파생물을 의미합니다.
13. "**X Marks**"는 본 계약에 따라서만 사용하도록 X가 Developer Site 등을 통해 귀하에게 제공하는 X 이름, 상표 및 로고를 의미합니다.
14. "**Users**"는 귀하의 서비스 방문자, 사용자 또는 고객을 의미합니다.
**II. X API 및 X 콘텐츠.**
**A. X의 라이선스.** 본 계약 조건 및 해당 통합 개발자 약관(아래 정의됨)을 준수하는 것을 조건으로, X는 이에 따라 귀하에게 다음 목적으로만 사용할 수 있는 비독점적, 로열티 없는, 양도할 수 없는, 재라이선스할 수 없는, 취소 가능한 라이선스를 부여합니다:
1. X가 명시적으로 승인한 대로 X API를 사용하여 X 콘텐츠를 귀하의 서비스에 통합하거나 X 콘텐츠를 분석하는 것;
2. 본 계약이 허용하는 범위 내에서 합리적인 양의 X 콘텐츠를 복사하고, 이를 귀하의 서비스에서 그리고 이를 통해 사용자에게 표시하는 것;
3. 귀하의 서비스에 표시하기 위한 형식 지정 목적으로만 X 콘텐츠를 수정하는 것; 그리고
4. 본 계약에 명시된 대로 X 콘텐츠의 출처로 X 애플리케이션을 표시하기 위해 X Marks를 사용하고 표시하는 것.
**B. X에 대한 라이선스.** 귀하는 이에 따라 X에게 [**임베디드 게시물**](https://developer.x.com/docs/twitter-for-websites/embedded-tweets/overview) 또는 [**임베디드 타임라인**](https://developer.x.com/docs/twitter-for-websites/timelines/overview)을 사용하여 X 콘텐츠를 표시하는 모든 웹페이지 또는 애플리케이션에 웹 스파이더 및/또는 크롤러를 포함한 모든 수단으로 접근, 색인화, 캐싱할 수 있는 비독점적, 로열티 없는, 양도할 수 없는, 재라이선스할 수 없는 취소 가능한 라이선스를 부여합니다.
**C. 통합 약관.** 라이선스 자료에 대한 귀하의 접근 및 사용은 또한 다음의 추가 약관 및 정책(집합적으로 "**통합 개발자 약관**")의 적용을 받으며, 귀하는 이를 준수해야 합니다:
1. [**X 개발자 정책**](/developer-terms/policy);
2. [\*\* API 제한된 사용 규칙\*\*](/developer-terms/restricted-use-cases);
3. [**X 규칙**](https://help.x.com/rules-and-policies/x-rules);
4. X 콘텐츠의 표시와 관련하여 [**표시 요건**](https://developer.x.com/developer-terms/display-requirements.html);
5. X Marks의 사용 및 표시와 관련하여 [**X 브랜드 가이드라인**](https://about.x.com/who-we-are/brand-toolkit); 그리고
6. 귀하 계정에서 자동화된 조치를 취하는 것과 관련하여 [**자동화 규칙**](https://help.x.com/rules-and-policies/x-automation).
**III. 사용 제한.**
**A. 리버스 엔지니어링 및 기타 제한.** 귀하는 다음을 하지 않으며 시도하지 않습니다(그리고 타인이 하도록 허용하지 않습니다): (a) X API를 리버스 엔지니어링, 디컴파일, 디스어셈블 또는 번역하거나 X API 또는 그 일부에 있거나 그 기반이 되는 소스 코드, 영업 비밀 또는 노하우를 도출하려고 시도하는 것; (b) X API의 기능이나 특징 또는 X API의 모니터링 메커니즘을 방해, 수정, 중단 또는 비활성화하는 것; (c) 라이선스 자료를 사용하거나 접근하여 X 애플리케이션에 대한 대체 또는 유사한 서비스나 제품을 만들거나 만들려고 시도하는 것; (d) 본 계약에서 명시적으로 허용하는 경우를 제외하고 라이선스 자료 전체 또는 일부를 제3자에게 판매, 임대, 리스, 재라이선스, 배포, 재배포, 신디케이션, 파생물 생성, 양도 또는 기타 방식으로 이전하거나 접근을 제공하는 것; (e) 서비스 뷰로, 렌탈 또는 관리 서비스 방식으로 X API 사용을 제공하거나, 다른 개인이나 단체가 X API에 대한 링크를 만들거나 다른 서버 또는 무선 또는 인터넷 기반 장치에서 X API를 "프레임"하거나 "미러링"하도록 허용하거나, X API에 대한 토큰, 키, 비밀번호 또는 기타 로그인 자격 증명을 제3자에게 제공하는 것; (f) 라이선스 자료를 불법적, 무단, 기타 부적절한 목적으로 사용하는 것; (g) 라이선스 자료를 사용하여 개별 X 사용자의 비공개 정보를 도출하거나 얻는 것; (h) X 애플리케이션, X API 또는 그 안에 포함된 X 콘텐츠의 무결성 또는 성능을 방해하거나 중단시키는 것; (i) X 콘텐츠의 소유권 표시나 마크를 제거하거나 변경하는 것; (j) X 애플리케이션, X API, X 콘텐츠 또는 관련 시스템이나 네트워크에 무단 접근을 시도하는 것; (k) X API 또는 X 콘텐츠를 사용하여 파운데이션 모델 또는 프론티어 모델을 파인튜닝하거나 훈련시키는 것; 또는 (l) X 콘텐츠를 단독으로 또는 제3자 데이터와 결합하거나 이로부터 파생 분석을 사용하여 X 애플리케이션 외부에서 사용자를 대상으로 광고를 표시하는 것.
**B. 상업적 사용 제한.** 귀하의 서비스가 '비상업적'으로 지정된 경우, 귀하는 라이선스 자료를 상업적으로 사용(아래 정의됨)해서는 안 됩니다. 상업적 사용 제한은 공식적으로 등록된 비영리 단체나 NGO에는 적용되지 않을 수 있습니다. "**상업적 사용**"이란 (a) 사업체(즉, 제품이나 서비스를 통해 수익을 창출하는 것이 주된 목적인 단체)에 의한 또는 사업체를 위한 사용, 또는 (b) 수익화된 제품이나 서비스의 일부로서(예: 웹사이트 광고, 라이선싱 수수료, 인앱 프로모션, 스폰서십) 라이선스 자료를 사용하거나 X API에 접근하는 것을 의미합니다.
**C. 모니터링 또는 측정 금지.** 이와 상반되는 어떠한 규정에도 불구하고, 귀하는 다음 정보를 비상업적, 내부 목적(예: 서비스의 기능 개선)으로만 사용할 수 있습니다: (a) 활성 사용자 수 또는 X 애플리케이션 계정 수와 같은 X 애플리케이션 사용자 지표 집계; (b) X 애플리케이션의 응답성; (c) X API의 성능을 분석, 사용 또는 이에 관한 결과, 사용 통계, 데이터 또는 기타 정보(집계된 또는 기타). 그러한 모든 정보는 기밀 정보(아래 정의됨)입니다.
**D. Rate Limits.** 귀하는 X API의 접근, 호출 및 사용에 대한 제한("**Rate Limits**")을 초과하거나 우회하려고 시도하거나, 합리적인 요청량을 초과하거나 과도하거나 남용적인 사용에 해당하거나 본 계약을 준수하지 않는 방식으로 X API를 사용하지 않습니다. 귀하가 Rate Limits, X API 사용을 제한하기 위한 통제 수단 또는 본 계약 조건을 초과하거나 X가 우회하려고 시도했다고 합리적으로 판단하는 경우, 라이선스 자료 사용 능력이 일시적으로 정지되거나 영구적으로 차단될 수 있습니다. X는 라이선스 자료 및 X 애플리케이션 개선 및 귀하의 본 계약 및 통합 개발자 약관 준수 여부를 확인하기 위해 귀하의 X API 사용을 모니터링할 수 있습니다.
**E. 위치 데이터.** 귀하는 X 콘텐츠에 포함된 위치 데이터 및 기타 지리적 정보를 첨부된 X 콘텐츠와 함께 사용하는 경우를 제외하고, 집계, 캐시 또는 저장하지 않으며, 타인이 그렇게 하도록 허용하지 않습니다. 귀하는 위치 데이터 및 지리적 정보를 X 콘텐츠에 의해 태그된 위치를 식별하기 위해서만 사용할 수 있습니다.
**F. X Marks의 사용.** 귀하는 X Marks를 등록된 법인명, 로고, 서비스 또는 제품명에 포함시켜서는 안 됩니다. 귀하는 X Marks의 파생물을 만들거나 X와의 지지, 후원 또는 연관을 형성하거나 합리적으로 암시하는 방식으로 X Marks를 사용해서는 안 됩니다. X Marks의 모든 사용과 사용에서 발생하는 모든 영업권은 X의 이익으로 귀속됩니다. 귀하는 라이선스 자료의 소유권 표시나 X Marks를 제거하거나 변경하지 않습니다.
**G. 보안.** 귀하는 X API의 보안을 유지하고 X API에 대한 토큰, 키, 비밀번호 또는 기타 로그인 자격 증명을 제3자에게 제공하지 않습니다. 귀하는 바이러스, 웜 또는 기타 유해한 코드나 자료로 인한 접근을 포함하여 X API의 기능과 특징에 대한 무단 접근이나 사용을 방지하기 위해 업계 표준의 보안 조치를 사용합니다. 귀하는 X 콘텐츠를 유사한 데이터를 저장할 때 사용하는 것보다 낮지 않은 관리와 함께 그러한 데이터에 대해 업계 표준의 조직적 및 기술적 보호 장치를 사용하여 무단 접근으로부터 기밀로 안전하게 유지합니다. 귀하는 라이선스 자료와 관련된 보안 침해 또는 잠재적 취약성을 알게 되거나 의심하는 경우 즉시 X에 알리고, 조사에 협의 및 협력하며, 필요한 통지를 지원하고, X가 합리적으로 요청하는 모든 정보를 제공합니다. 귀하는 라이선스 자료에 대한 접근으로 인해 발생하는 그러한 침해나 잠재적 취약성을 신속하게 해결합니다.
**H. 디지털 서비스법.** 본 계약의 상반되는 어떠한 규정에도 불구하고, 귀하가 디지털 서비스법(규정 (EU) 2022/2065)("DSA") 제40조에 설명된 절차에 따라 라이선스 자료에 대한 접근을 제공받는 범위 내에서, 라이선스 자료에 대한 귀하의 접근 및 사용은 유럽 연합의 시스템적 위험의 탐지, 식별 및 이해에 기여하는 연구를 수행하는 것으로만 제한되며, X가 DSA에 따른 의무를 준수하기 위해 필요한 범위 내에서만 사용할 수 있습니다. 라이선스 자료의 그러한 사용은 본 계약 제III(B)조에 설명된 대로 비상업적입니다. 귀하는 X API를 통해 검색한 라이선스 자료(그 파생물 포함)를 승인된 애플리케이션 내에 명시된 사람 이외의 어떤 개인이나 단체에도 공개, 복제, 라이선스 또는 그 밖의 방식으로 배포할 수 없습니다. 단, (i) 제40조에 설명된 "심사된 연구자" 지위와 절차에 따라 DSA가 구체적으로 허용하는 디지털 서비스 조정관 또는 기타 당사자에게 정보가 공개되는 경우, 또는 (ii) 법에 의해 공개가 요구되는 경우는 예외입니다.
**I. 토큰.** X는 X 애플리케이션의 기능 또는 특징에 대한 접근 및 사용을 가능하게 하는 토큰을 포함하되 이에 국한되지 않는, 귀하에게 제공하는 토큰의 수를 제한할 수 있습니다.
**J. 접근 등급.** X는 라이선스 자료에 대한 다양한 접근 등급([developer.x.com](http://developer.x.com)에 설명됨)을 제공하며, 귀하는 귀하의 사용 사례에 가장 적합한 등급에 가입해야 합니다. X는 언제든지 귀하의 라이선스 자료 사용을 검토하고, Enterprise 접근 신청([developer.x.com](http://developer.x.com)에 설명됨)을 포함하되 이에 국한되지 않는 접근 등급의 변경을 요구할 수 있습니다.
**K. I-Framing 금지:** 귀하는 어떠한 상황에서도 iframe, 인라인 프레임 또는 기타 유사한 임베딩 메커니즘 내에서 귀하의 서비스나 다른 플랫폼에 라이선스 자료, X 콘텐츠, X API 또는 X 애플리케이션의 요소를 임베드, 표시 또는 그 외의 방식으로 통합해서는 안 됩니다. 이 금지는 절대적이며, 표시, 통합 또는 재배포 목적으로 X 콘텐츠를 프레이밍하려는 시도를 포함하지만 이에 국한되지 않습니다. 이 조항 위반은 제VII.I조에 명시된 대로 귀하의 개발자 계약 및 라이선스 자료(예: X API, X Data License, Developer Console)에 대한 접근의 즉각적인 종료로 이어질 수 있습니다.
**L. 셀프 서비스 사용.** Pay-Per-Use, Basic 및 Pro 요금제([developer.x.com](https://developer.x.com)에 설명됨)는 취미 개발자, 상업적 프로토타이핑, 초기 개발, 초기 단계 X 제품 통합 및 제한된 수의 최종 사용자를 지원하는 애플리케이션을 위해 설계되었습니다. 이 범위를 넘어 X API를 사용하는 경우 Enterprise 요금제([developer.x.com](https://developer.x.com)에 설명됨)에 신청(또는 이미 가입)해야 합니다.
**M. 상업적 사용:** 취미 프로젝트, 상업적 프로토타이핑, 초기 개발, 초기 단계 X 제품 통합, 제한된 수의 최종 사용자를 위한 애플리케이션의 범위를 넘어 X API를 사용하는 경우, Enterprise 요금제(developer.x.com에 설명됨)에 신청(또는 이미 가입)해야 합니다.
**IV. 업데이트 및 제거.**
**A. 업데이트.** X는 라이선스 자료의 기능이나 기능을 수시로 전체 또는 일부로 업데이트, 수정 또는 중단할 수 있습니다(각각 "**업데이트**"). 귀하는 라이선스 자료의 최신 버전을 구현 및 사용하고, 업데이트의 결과로 필요한 서비스 변경 사항을 귀하 단독의 비용으로 수행해야 합니다. 업데이트는 귀하 서비스가 X API에 접근하거나 통신하거나 X 콘텐츠를 표시하는 방식에 부정적인 영향을 미칠 수 있습니다. X는 업데이트로 인해 발생하는 어떠한 종류의 손해에도 책임을 지지 않습니다.
**B. 제거.** X 콘텐츠가 삭제되거나, 보호 상태를 획득하거나, 그 외의 방식으로 X 애플리케이션에서 정지, 보류, 수정 또는 제거되는 경우(위치 정보 제거 포함), 귀하는 X 또는 X 사용자의 X 콘텐츠에 관한 서면 요청 후 가능한 한 빨리, 그리고 어떠한 경우에도 이십사(24)시간 이내에 해당 X 콘텐츠를 삭제 또는 수정하기 위해 모든 합리적인 노력을 기울입니다. 단, 법률이나 규정에 의해 금지되고 X의 명시적 서면 허가가 있는 경우는 예외입니다.
**V. 소유권, 베타 및 피드백.**
**A. 소유권.** 본 계약에서 명시적으로 달리 명시된 범위를 제외하고, 어느 당사자도 상대방이 소유하거나 라이선스한 지식재산권에 대한 어떠한 권리, 소유권 또는 이익도 취득하지 않습니다. 라이선스 자료는 라이선스되는 것이며 판매되는 것이 아니며, X(또는 해당되는 경우 그 라이선서 또는 X 애플리케이션 사용자)는 본 계약에서 명시적으로 부여되지 않은 지식재산권을 포함한 모든 권리를 보유하고 유보합니다. 귀하는 X Marks에 대한 X의 소유권에 이의를 제기하거나 본 계약에서 부여된 라이선스의 유효성에 이의를 제기하거나 본 계약에서 구체적으로 승인된 경우를 제외하고 X Marks를 복사하거나 이용하는 것을 포함하되 이에 국한되지 않는, X의 소유권과 상충되는 어떠한 행위도 하지 않습니다. 귀하가 법의 작용에 의하거나 그 외의 방식으로 X Marks 또는 혼동을 일으킬 만큼 유사한 마크에 대한 권리를 취득하는 경우, 귀하는 X의 비용 없이 그러한 권리를 즉시 X에게 양도합니다.
**B. 베타.** X는 수시로 귀하에게 일반적으로 이용할 수 없는 알파, 베타, 연구 조사, 파일럿, 마케팅 서비스 또는 기타 프로그램에 대한 조기 접근을 제공할 수 있습니다(각각 "**베타**"). 베타는 기밀 정보로 간주됩니다. 귀하의 베타 참여는 귀하의 위험 부담으로 이루어지며, 추가 요건이 적용될 수 있고, X가 기존 또는 향후 프로그램, 제품 및/또는 도구를 조사, 분석 및 검증하는 데 도움이 될 수 있습니다.
**C. 피드백.** X는 귀하가 X, 라이선스 자료, 베타 또는 X의 기타 제품이나 서비스에 관하여 X에 제공한 모든 피드백, 코멘트 또는 제안("**피드백**")을 귀하나 제3자에 대한 어떠한 보상이나 의무 없이 자유롭게 사용할 수 있으며, 피드백은 기밀 정보로 간주됩니다. 귀하는 이에 따라 피드백에 대한 모든 권리, 소유권 및 이익을 X에게 취소 불가능하게 양도합니다.
**VI. 기밀 유지.**
귀하는 라이선스 자료와 관련된 비공개 정보, 소프트웨어 및 사양("**기밀 정보**")에 대한 접근을 제공받을 수 있습니다. 귀하는 본 계약에 따른 권리를 행사하는 데 필요한 경우에만 기밀 정보를 사용할 수 있습니다. 귀하는 X의 사전 서면 동의 없이 기밀 정보를 제3자에게 공개하지 않습니다. 귀하는 유사한 성격의 자신의 기밀 정보를 보호하는 데 사용할 방식과 동일한 방식으로, 그리고 어떠한 경우에도 합리적인 정도의 관리 미만으로는 기밀 정보를 무단 사용, 접근 또는 공개로부터 보호합니다.
**VII. 기간; 구독 수수료; 결제; 정지 및 해지.**
**A. 기간.** 본 계약의 기간은 (i) 귀하가 본 계약 조건을 수락한 날짜 또는 (ii) 라이선스 자료의 어느 것에든 접근하거나 사용하기 시작한 날짜 중 더 이른 날짜에 시작되며, 아래 설명된 대로 조기 종료되지 않는 한 귀하가 라이선스 자료에 대한 접근 및 사용을 중단할 때까지 계속됩니다.
**B. 구독 조건.** 라이선스 자료의 일부로 제공되는 유료 서비스는 Developer Site 및 Payment Portal에 설명된 대로 특정 기능, 혜택 또는 서비스에 대한 접근을 제공하는 반복 구독 서비스로 제공됩니다. 유료 서비스를 구매하는 경우, 귀하는 아래 명시된 결제 조건에 따라 매월 구독료를 선불로 지불함으로써 이를 수행합니다. Payment Portal을 통해 유료 서비스에 가입할 때, 귀하는 반복 결제를 승인하고 있으며, 해당 유료 서비스가 귀하 또는 X에 의해 취소되거나 본 계약이 그 외의 방식으로 해지될 때까지 귀하가 선택한 결제 수단으로 결제가 이루어질 것임에 명시적으로 동의합니다. 유료 서비스에 대한 귀하의 구독은 본 계약에 따라 취소될 때까지 매월 자동으로 갱신됩니다. 귀하의 결제 정보는 유료 서비스에 적용되는 각 구독 기간이 시작될 때 결제 처리자(아래 정의됨)에 의해 자동으로 처리됩니다. 결제 정보가 거부되면 해당 유료 서비스에 대한 새로운 결제 정보를 제공할 때까지 구독이 취소될 수 있습니다. 새로운 결제 정보를 제공하고 결제 계정이 성공적으로 청구되면, 새로운 구독 기간은 성공적인 청구가 이루어진 날짜가 아닌 원래의 갱신 날짜를 기준으로 합니다. 유료 서비스의 가격은 수시로 변경될 수 있습니다. X는 유료 서비스 가격의 중대한 변경에 대해 합리적인 사전 통지를 제공하며, 이 통지는 Developer Site를 통해 제공될 수 있습니다. 구독 수수료의 경우, 가격 변경은 가격 변경 날짜 이후 다음 구독 기간이 시작될 때 적용됩니다. 가격 변경에 동의하지 않는 경우, 귀하는 가격 변경이 시행되기 전에 해당 유료 서비스의 구독을 취소함으로써 변경을 거부할 권리가 있습니다.
**C. 결제 조건.** X는 유료 서비스, 기기, 운영 체제, 지리적 위치 또는 기타 요소에 따라 다를 수 있는 결제 옵션을 제공할 수 있으며, 이는 수시로 업데이트될 수 있습니다. 이러한 결제 옵션에는 제3자 결제 처리자("**결제 처리자**")를 사용하는 웹 결제가 포함될 수 있습니다. 유료 서비스에 접근할 때, 귀하는 다음에 동의합니다: (i) 해당 구독 기간 동안 반복적으로 관련 세금, 부가금, 신용카드 수수료, 은행 수수료, 외환 거래 수수료, 외환 수수료 및 통화 변동에 관한 추가 금액과 함께 유료 서비스에 표시된 가격을 지불하는 것; 그리고 (ii) 특정 결제 수단 사용과 관련하여 결제 처리자가 부과하는 관련 서비스 약관, 개인정보 처리방침 또는 기타 법적 계약 또는 제한 사항(추가 연령 제한 포함)을 준수하는 것. Developer Site에서 유료 서비스를 취소하지 않는 한, 구독 수수료는 해당 구독 기간의 갱신 기간이 시작될 때 자동으로 적용됩니다. 은행, 신용카드, 체크카드 및/또는 기타 결제 정보가 항상 최신이고 완전하며 정확하도록 유지하는 것은 귀하의 책임입니다. 결제 처리자를 통해 유료 서비스에 대한 결제를 하는 경우, X는 언제 결제가 이루어졌는지, 언제 구독이 만료되거나 자동 갱신되는지, 어떤 플랫폼에서 구매했는지 및 기타 정보와 같은 거래에 대한 정보를 받을 수 있습니다. X는 결제 처리자, 은행, 신용카드 회사 또는 결제 네트워크에 의한 오류나 지연에 대해 책임을 지지 않습니다. X에 대한 모든 결제는 본 계약에서 명시적으로 달리 규정되거나 법률에 의해 요구되는 경우를 제외하고 환불되지 않습니다.
**D. 세금 및 수수료.** 모든 수수료는 거래, 라이선스 자료의 제공 또는 X 콘텐츠의 제공에 대해 현재 시행 중이거나 향후 제정되거나 부과되는 모든 세금 및 유사한 수수료(판매세, 사용세 또는 부가가치세, 상품 및 서비스세, 소비세, 관세, 관세 또는 유사한 청구액 포함)를 제외합니다. 이러한 세금에는 VAT, GST, 판매세, 원천징수세 및 기타 관련 세금이 포함될 수 있지만 이에 국한되지 않으며, X의 순소득만을 기반으로 하는 세금은 제외됩니다. 귀하는 그러한 모든 세금, 관세 및 청구액과 그러한 금액의 지불로 인해 발생하는 관련 벌금 및 이자의 지불에 대해 책임이 있습니다. 또한 특정 관할지역에서 X가 부담하는 디지털 서비스세("DST") 또는 유사한 관할별 세금 또는 규제 수수료와 관련된 비용을 회수하기 위해 부가금이 청구될 수 있습니다. 이 부가금은 해당되는 경우 인보이스에 별도의 항목으로 표시되며, X가 단독 재량으로 결정하는 대로 관련 청구액의 백분율로 계산됩니다. X는 증가된 세금이나 수수료율 또는 관련 관리 비용에 대응하여 사전 통지 없이 언제든지 이 부가금을 조정할 수 있습니다. 귀하의 위치에 따라, X는 귀하의 유료 서비스 구매에서 발생하는 거래세와 관련된 정보를 수집하고 보고할 책임이 있을 수 있습니다. 귀하는 X가 세금 징수 및 보고 의무를 이행하기 위해 관련 세무 당국에 귀하의 계정 및 개인 정보를 제공하는 것을 허가합니다.
**E. 유료 서비스 구독 취소.** 유료 서비스에 대한 귀하의 구독은 현재 구독 기간 종료 최소 24시간 전에 구독을 취소하지 않는 한 매월 자동으로 갱신됩니다. 특정 기능, 혜택 및/또는 서비스가 수정되거나 중단되는 상황을 포함하여 부분 구독 기간에 대한 환불이나 크레딧은 없습니다. 구독 요금제는 선불이며, 환불되지 않으며(법률로 요구되지 않는 한), 여기에 있는 취소 절차에 따라 구독이 취소되지 않는 한 각 구독 기간이 끝날 때 자동으로 갱신됩니다. 귀하는 언제든지 Developer Site를 통해 유료 서비스 구독을 취소할 수 있으며, 그 후 현재 구독 기간이 끝날 때 유료 서비스(또는 그 어떤 기능이나 특성)에 더 이상 접근할 수 없게 됩니다. 유료 서비스를 취소하면 취소 시점부터 현재 구독 기간 종료 시까지 구독이 유지됩니다. 법률에 의해 요구되지 않는 한 현재 구독 기간의 남은 일수에 대한 환불이나 크레딧을 받지 않습니다. 유료 서비스에 대한 모든 결제는 최종적이며, 관련 법률에 의해 요구되는 경우를 제외하고 환불하거나 교환할 수 없습니다. X는 유료 서비스의 성격, 품질 또는 가치 또는 그 가용성이나 공급에 관해 어떠한 보증도 하지 않습니다. 미사용 또는 부분적으로 사용된 유료 서비스(예: 부분적으로 사용된 구독 기간)에 대해서는 환불이나 크레딧이 제공되지 않습니다. 아래 규정과 같이 법에 따라 철회할 권리가 있는 경우를 제외하고 **모든 거래는 최종적**입니다\*\*.\*\*
1. **EU 또는 영국 거주 사용자에 대한 철회권 및 환불.** 구독 방식으로 유료 서비스를 구매하는 경우, 귀하는 구독 방식으로 하기로 명시적으로 동의하며 구독이 구매 날짜에 즉시 시작될 것에 동의합니다. 귀하가 EU 회원국 또는 영국의 소비자인 경우, 어떠한 이유로든 구매 계약을 철회할 수 있는 14일이 있음에 동의합니다.
2. **대만 거주 사용자에 대한 철회권 없음.** 유료 서비스를 구매할 때 이는 구독 방식으로 이루어지며, 구독은 구매 날짜에 즉시 시작되고, 유료 서비스는 시작되면 완전히 이행됩니다. 대만의 소비자인 경우, 위의 제VII.E조에 따라 유료 서비스 구독을 취소할 수 있지만, 그 외에는 구독을 취소할 권리가 없으며 환불이 발급되지 않는다는 데 동의합니다.
**F. 유료 서비스는 X 계정 간에 양도할 수 없습니다.** 유료 서비스의 각 구매는 단일 X 계정에 적용되며, 이는 귀하의 구매가 유료 서비스를 구매할 때 사용하던 계정에만 적용되며 접근하거나 통제할 수 있는 다른 계정에는 적용되지 않음을 의미합니다. 여러 계정을 소유하거나 통제하고 각 계정에서 유료 서비스에 접근하려는 경우, 각 계정에서 유료 서비스를 개별적으로 구매해야 합니다. 귀하는 다른 사람이 귀하의 X 계정을 사용하여 그 사람이 주문하지 않은 라이선스 자료에 접근하도록 허용해서는 안 됩니다. 미국인이 미국 재무부 해외자산통제국이 관리하는 제재 또는 기타 적용 가능한 제재 당국에 의한 제재를 포함한 경제 제재에 따라 거래하는 것이 허용되지 않는 사람("**금지된 사람**")인 경우, 유료 서비스를 구매하거나 라이선스 자료를 사용해서는 안 됩니다. 여기에는 다음 국가 및 지역에 위치하거나, 시민이거나, 통상적으로 거주하는 사람이 포함되지만 이에 국한되지 않습니다: 쿠바, 이란, 우크라이나의 크림 지역, 북한 및 시리아. 귀하는 자신이 금지된 사람이 아님을 진술하고 보증합니다.
**G. 제한 및 의무.** 귀하는 귀하의 국가에서 라이선스 자료를 사용할 법적 자격이 있고 X가 해당 유료 서비스 또는 라이선스 자료에 대해 지원하는 국가에 거주하는 경우에만 유료 서비스를 구매하고 사용하거나 라이선스 자료를 사용할 수 있습니다. X는 재량에 따라 특정 국가에서 라이선스 자료에 접근하거나 유료 서비스를 구매할 수 있는 능력을 제한할 수 있습니다. X는 지원 국가 목록을 수시로 수정할 권리를 보유합니다. X는 자체 재량에 따라 유료 서비스 거래를 거부하거나 유료 서비스의 판매나 사용 또는 라이선스 자료의 사용을 취소하거나 중단할 권리를 보유합니다.
**H. 정지.** X는 (a) X가 (i) 귀하의 라이선스 자료 사용이 라이선스 자료에 손상이나 과도한 부담을 초래할 것이거나, (ii) 귀하가 본 계약을 위반했거나, (iii) 귀하가 X에 대한 위험이나 가능한 법적 노출을 초래하거나, (iv) X가 귀하에게 라이선스 자료를 제공하는 것이 더 이상 상업적으로 가능하지 않다고 합리적으로 판단하는 경우; (b) 장기간 비활동으로 인해; (c) 관할 법원, 규제 당국 또는 법 집행 기관이 그렇게 하도록 요청하거나 지시하는 경우; 또는 (d) 유료 서비스에 대한 결제 실패 시 통지 없이 즉시 라이선스 자료의 귀하의 사용 및 접근을 정지할 수 있습니다. X는 그러한 정지로 인해 발생하는 어떠한 종류의 손해에도 책임을 지지 않습니다.
**I. 해지.** X는 X의 단독 재량으로 어떠한 이유로든 본 계약을 해지할 수 있습니다. 그러한 조기 해지가 귀하의 본 계약 위반의 결과인 경우를 제외하고, X에 의한 그러한 조기 해지는 그 당시의 구독 기간이 끝날 때 유효합니다. 본 계약 조건을 위반하는 경우, X는 귀하에게 통지 즉시 본 계약을 해지할 수 있으며, 귀하는 어떤 유료 서비스에 대해서도 비례 환불을 받지 못합니다. 귀하는 Developer Site에서 유료 서비스 구독이나 라이선스 자료 사용을 취소할 수 있습니다. 본 계약 해지 시: (a) 본 계약에서 부여된 모든 라이선스는 즉시 만료되고 귀하는 어떠한 라이선스 자료도 사용을 중단해야 합니다; 그리고 (b) 귀하는 귀하의 소유에 있는 모든 형태 및 유형의 미디어 및 그 사본에 있는 모든 라이선스 자료를 영구적으로 삭제해야 합니다. X가 어떠한 이유로든 요청하는 경우, 귀하는 신속하게(그리고 어떠한 경우에도 그러한 요청의 십(10) 영업일 이내에) 본 조항의 위 부속조항 (b)의 준수 증거(예: 삭제 확인의 스크린샷)를 제공합니다. 본 계약의 당사자는 본 계약에 따라 허용된 대로 본 계약의 해지로 인해 발생하는 손해에 대해 서로에게 책임을 지지 않습니다.
**VIII. 준수 감사.**
X 또는 기밀 유지 의무를 지닌 상호 합의된 제3자 대리인은 귀하에게 합리적인 통지를 하고 정상 영업 시간 중 합리적인 시간에 본 계약의 이행과 관련된 귀하가 통제하거나 소유하는 모든 기록을 검사 및 감사할 권한을 가지며, 이는 본 계약 준수 및 감사에 선행하는 이(2)년 기간에 대해 X에 지불되는 수수료를 확인하기 위함입니다. X는 비준수에 대한 합리적인 원인이 있는 경우가 아닌 한 십이(12)개월마다 한 번 이상 감사 권한을 행사하지 않으며, 그러한 감사는 귀하의 사업 활동을 불합리하게 방해하지 않습니다. 귀하는 그러한 감사에 대해 전적으로 협조하고 지원하며, 귀하가 소유한 모든 라이선스 자료, 적용 가능한 계약 및 기록에 대한 접근을 제공합니다. 앞서 언급한 것의 일반성을 제한하지 않고, 감사의 일부로서 X는 요청할 수 있으며, 귀하는 승인된 대리인이 서명한 서면 보고서를 제공하여 라이선스 자료의 현재 배포를 나열하는 데 동의합니다. 귀하는 그러한 감사에 의해 밝혀진 미납액을 감사 완료 후 삼십(30) 영업일 이내에 X에 지불합니다. 또한, 그러한 감사에서 귀하의 미납액이 5퍼센트(5%) 이상으로 밝혀지면, 귀하는 그러한 감사의 합리적인 비용과 경비도 X에 상환합니다. 이 조항의 요구 사항은 본 계약 해지 후 1(1)년 동안 존속됩니다.
**IX. 면책 조항.**
관련 법률이 허용하는 최대 범위 내에서, 라이선스 자료는 모든 결함과 함께 "있는 그대로", "있는 위치에서" 귀하에게 제공되며, X는 상품성, 비침해, 특정 목적에의 적합성 및 본 계약, 거래 과정 또는 거래 관행으로부터 발생하는 어떠한 보증이나 조건을 포함하되 이에 국한되지 않는, 명시적, 묵시적, 법정적 또는 그 외의 모든 보증을 부인합니다. X는 라이선스 자료 또는 여기에 따라 제공되는 다른 X 제품이나 서비스가 귀하의 요구 사항을 충족할 것이거나 그러한 라이선스 자료 또는 다른 제품이나 서비스의 사용이 오류가 없거나, 중단이 없거나, 바이러스가 없거나, 안전할 것이라는 것을 보증하지 않습니다. 귀하는 라이선스 자료의 사용 및 귀하가 제공하는 콘텐츠에 대해 책임이 있습니다. 이 보증 부인은 일부 관할지역에서 유효하지 않을 수 있으며, 귀하는 포기하거나 부인할 수 없는 법률에 따른 보증 권리를 가질 수 있습니다.
**또한 귀하는 유료 서비스가 "있는 그대로" 및 "이용 가능한 대로"의 기준으로 귀하에게 제공된다는 것을 이해하고 동의합니다.**
**X. 면책.**
귀하는 X를 상대로 제기된 모든 소송, 청구, 소송(제품 책임 청구를 포함하되 이에 국한되지 않음)에 대해 X를 방어해야 하며, (a) 귀하의 본 계약과 일치하지 않는 방식의 라이선스 자료 사용 또는 (b) 귀하의 서비스의 수행, 홍보, 판매 또는 배포로부터 발생하는 범위 내에서 X를 모든 책임, 손해 및 비용(합리적인 변호사 비용을 포함하되 이에 국한되지 않음)으로부터 면책합니다. X가 본 조항에 따라 귀하로부터 면책 또는 방어를 구하는 경우, X는 면책 또는 방어를 구하는 X에 대해 제기된 청구에 대해 신속하게 서면으로 귀하에게 알립니다. X는 자신이 선택한 법률 자문과 함께 청구 방어에 대한 완전한 통제를 취할 수 있습니다. 귀하는 X의 사전 서면 동의 없이는 X의 권리에 영향을 미치거나, X의 잘못을 인정하거나, 어떠한 방식으로든 X를 구속하는 제3자 계약에 들어가지 않습니다. X가 그러한 청구의 방어에 대한 통제를 취하는 경우, X는 귀하의 사전 서면 승인 없이는 귀하로부터 지불을 요구하는 그러한 청구를 합의로 해결하지 않습니다.
**XI. 책임 제한.**
어떠한 경우에도 X는 본 계약과 관련하여 또는 이로부터 발생하는 간접적, 특별한, 우발적, 예시적, 징벌적 또는 결과적 손해 또는 사용, 데이터, 사업, 영업권 또는 이익의 손실이나 손상에 대해 귀하나 어떠한 사용자에게도 책임을 지지 않습니다. 어떠한 경우에도 본 계약에 따른 모든 청구에 대한 X의 총 책임은 오십 달러(\$50.00)를 초과하지 않습니다. 앞서 언급한 제한, 제외 및 부인은 그러한 책임이 계약, 보증, 불법행위, 엄격한 책임 또는 그 외의 것을 기반으로 하는 청구에서 발생하는지 여부와 X가 그러한 손실이나 손해의 가능성에 대해 통보받았는지 여부에 관계없이 적용됩니다. 관련 법률이 여기에 있는 책임에 대한 어떠한 제한을 금지하는 경우, 당사자들은 그 제한이 관련 법률에 부합하도록 수정된 것으로 간주됨에 동의합니다. 당사자들은 여기에 명시된 책임에 대한 제한이 위험의 합의된 할당이며, 그러한 제한이 어떠한 제한된 구제책의 본질적 목적의 실패에도 불구하고 적용됨에 동의합니다.
**XII. 계약 업데이트.**
X는 수시로 본 계약이나 통합 개발자 약관을 업데이트하거나 수정할 수 있습니다. 귀하는 업데이트를 위해 Developer Site를 정기적으로 확인해야 합니다. X는 이러한 약관에 대한 중대한 개정 사항을 이 사이트에 업데이트된 약관을 게시하거나, 서비스 알림을 통하거나, 기타 적절한 수단(예: 계정과 관련된 이메일 주소로 이메일을 통해)으로 알립니다. 변경 사항은 소급 적용되지 않으며, Developer Site에서 이용 가능한 본 계약의 가장 최신 버전이 라이선스 자료 및 관련 거래에 대한 귀하의 접근 및 사용을 규율합니다. 라이선스 자료에 대한 귀하의 계속되는 접근 또는 사용은 그러한 업데이트 및 수정에 대한 구속력 있는 수락을 구성합니다.
**XIII. 분쟁 해결 및 집단 소송 포기.**
**A. 이 섹션은 미국을 포함하여 유럽 연합, EFTA 국가 또는 영국 외부에 거주하는 경우에만 귀하에게 적용됩니다. 이 섹션을 주의 깊게 읽어주세요 – 이는 법정에서 소송을 제기할 권리를 포함하여 귀하의 법적 권리에 상당한 영향을 미칠 수 있습니다.**
1. **준거법 및 법정지 선택.** 텍사스 주법(그 준거법 규정 제외)이 본 계약과 귀하와 X 사이에 발생하는 어떠한 분쟁도 규율하며, 이는 당사자 간의 다른 계약이 반대되는 것이더라도 마찬가지입니다. 본 계약과 관련된 모든 분쟁, 라이선스 자료의 마케팅 및/또는 라이선스 자료 참여로부터 발생하거나 관련된 분쟁, 청구 또는 논쟁을 포함한 모든 분쟁은 텍사스 북부 지구의 미국 지방법원 또는 미국 텍사스주 태런트 카운티에 위치한 주 법원에서만 제기되며, 귀하는 그러한 법정에서의 개인 관할권에 동의하고 불편한 법정에 대한 어떠한 이의도 포기합니다. 앞서 언급한 것을 침해하지 않고, 귀하는 X가 단독 재량으로 청구에 대한 관할권과 법정지가 있는 귀하가 거주하는 국가의 어떠한 관할 법원에서든 귀하에 대한 어떠한 청구, 소송 원인 또는 분쟁을 제기할 수 있음에 동의합니다.
귀하가 공식 자격으로 라이선스 자료를 사용하는 미국의 연방, 주 또는 지방 정부 기관이고 위의 지배 법률, 관할권 또는 법정지 조항을 법적으로 수락할 수 없는 경우, 그러한 조항은 귀하에게 적용되지 않습니다. 그러한 미국 연방 정부 기관에 대해서는, 본 계약 및 이와 관련된 어떠한 조치도 미합중국 법률(법률의 상충에 대한 언급 없이)에 의해 규율되며, 연방 법률이 없거나 연방 법률이 허용하는 범위 내에서 텍사스 주법(법률 선택 제외)에 의해 규율됩니다.
2. **X에 대한 청구를 제기할 수 있는 기간은 1년입니다.** 관련 법률이 해당 청구에 대한 통상적인 시효 기간이 계약에 의해 단축될 수 없다고 규정하지 않는 한, 귀하는 분쟁을 야기하는 사건이나 사실 발생일로부터 일(1)년 이내에 본 계약으로부터 또는 이와 관련하여 발생하는 X에 대한 청구를 제기해야 합니다. 이 기간 내에 청구를 제기하지 않으면, 귀하는 그러한 사건이나 사실에 기반한 모든 종류나 성격의 청구나 소송 원인을 추구할 권리를 영원히 포기하며, 그러한 청구나 소송 원인은 영구적으로 금지되고 X는 그러한 청구에 대해 어떠한 책임도 지지 않습니다.
3. **집단 소송 포기.** 법률이 허용하는 범위 내에서, 귀하는 또한 어떠한 주장된 집단 소송, 집합 소송 또는 대표 소송 절차에서 원고 또는 집단 구성원으로 참여할 권리를 포기합니다.
4. **이 섹션의 변경.** 이 분쟁 해결 섹션은 X가 제공하는 서비스 또는 통신의 취소 또는 구독 해지를 포함하여 귀하와 X 사이의 관계 종료 후에도 존속합니다.
5. **금지 명령 구제.** 앞서 언급한 것에도 불구하고, 귀하는 X의 지식재산이나 기밀 정보를 보호하는 본 계약의 위반이나 위반 위협의 경우 금전적 손해가 X에게 부적절한 구제가 될 수 있으며, 그러한 위반이나 위협의 경우 X가 자신에게 주어진 다른 구제책 외에도 담보 게시의 필요 없이 예비적 또는 금지 명령 구제(귀하가 그러한 조항 위반 행위를 취하는 것을 금지하는 명령 포함) 및 적절하다면 특정 이행에 대한 권리를 가짐에 동의합니다. 당사자들은 국제 물품 매매 계약에 관한 유엔 협약이나 통일 컴퓨터 정보 거래법 모두 당사자들이 사업을 하거나 설립된 주에 관계없이 본 계약에 적용되지 않음에 동의합니다. 본 계약에 따른 어떠한 약속이나 권리에 대한 X의 포기도 X에 의해 승인된 서면으로 기록되지 않는 한 유효하지 않습니다.
**B. 이 섹션은 유럽 연합, EFTA 국가 또는 영국에 거주하는 경우에만 귀하에게 적용됩니다. 이 섹션을 주의 깊게 읽어주세요 – 이는 법정에서 소송을 제기할 권리를 포함하여 귀하의 법적 권리에 상당한 영향을 미칠 수 있습니다.**
1. **준거법 및 법정지 선택.** 법률이 허용하는 범위 내에서, 본 계약과 관련된 모든 분쟁, 라이선스 자료의 마케팅 및/또는 라이선스 자료 참여로부터 발생하거나 관련된 분쟁, 청구 또는 논쟁을 포함한 모든 분쟁은 준거법 규정을 고려하지 않고 아일랜드의 관할 법원에서만 제기되며 아일랜드 법률에 의해 규율됩니다, 이는 당사자 간의 반대 계약에도 불구하고 마찬가지입니다. 앞서 언급한 것을 침해하지 않고, 귀하는 X가 단독 재량으로 청구에 대한 관할권과 법정지가 있는 귀하가 거주하는 국가의 어떠한 관할 법원에서든 귀하에 대한 어떠한 청구, 소송 원인 또는 분쟁을 제기할 수 있음에 동의합니다.
2. **X에 대한 청구를 제기할 수 있는 기간은 1년입니다.** 관련 법률이 해당 청구에 대한 통상적인 시효 기간이 계약에 의해 단축될 수 없다고 규정하지 않는 한, 귀하는 분쟁을 야기하는 사건이나 사실 발생일로부터 일(1)년 이내에 본 계약으로부터 또는 이와 관련하여 발생하는 X에 대한 청구를 제기해야 합니다. 이 기간 내에 청구를 제기하지 않으면, 귀하는 그러한 사건이나 사실에 기반한 모든 종류나 성격의 청구나 소송 원인을 추구할 권리를 영원히 포기하며, 그러한 청구나 소송 원인은 영구적으로 금지되고 X는 그러한 청구에 대해 어떠한 책임도 지지 않습니다.
3. **집단 소송 포기.** 법률이 허용하는 범위 내에서, 귀하는 또한 어떠한 주장된 집단 소송, 집합 소송 또는 대표 소송 절차에서 원고 또는 집단 구성원으로 참여할 권리를 포기합니다.
4. **이 섹션의 변경.** 이 분쟁 해결 섹션은 X가 제공하는 서비스 또는 통신의 취소 또는 구독 해지를 포함하여 귀하와 X 사이의 관계 종료 후에도 존속합니다.
5. **금지 명령 구제.** 앞서 언급한 것에도 불구하고, 귀하는 X의 지식재산이나 기밀 정보를 보호하는 본 계약의 위반이나 위반 위협의 경우 금전적 손해가 X에게 부적절한 구제가 될 수 있으며, 그러한 위반이나 위협의 경우 X가 자신에게 주어진 다른 구제책(금전적 손해 포함) 외에도 담보 게시의 필요 없이 예비적 또는 금지 명령 구제(귀하가 그러한 조항 위반 행위를 취하는 것을 금지하는 명령 포함) 및 적절하다면 특정 이행에 대한 권리를 가짐에 동의합니다. 당사자들은 국제 물품 매매 계약에 관한 유엔 협약이나 통일 컴퓨터 정보 거래법 모두 당사자들이 사업을 하거나 설립된 주에 관계없이 본 계약에 적용되지 않음에 동의합니다. 본 계약에 따른 어떠한 약속이나 권리에 대한 X의 포기도 X에 의해 승인된 서면으로 기록되지 않는 한 유효하지 않습니다.
**XIV. 기타.**
**A. 양도.** 귀하는 X의 사전 서면 동의 없이는 자발적으로든 법의 작용으로든, 계약, 합병(귀하가 존속 또는 소멸 법인인지 여부와 관계없이), 주식 또는 자산 매매, 통합, 해산, 정부 조치를 통해서든 그 외의 방식으로든, 여기에 부여된 권리나 의무의 어떠한 것도 전체 또는 일부로 양도해서는 안 됩니다. X는 미국 외부에 거주하는 X 사용자의 정보에 대해 책임을 지는 아일랜드 회사 X Internet Unlimited Company를 위한 수정 사항 및 동의에 서명할 권한이 있습니다. 이 섹션 위반의 어떠한 양도 시도도 무효이며 X는 본 계약을 해지할 수 있습니다.
**B. 사용자 보호.** X에 의해 서면으로 명시적으로 승인되지 않는 한, 귀하는 다음 목적으로 X 콘텐츠 또는 X 콘텐츠에서 파생된 정보를 사용하거나 알면서 표시, 배포하거나 그 외의 방식으로 이용 가능하게 만들지 않습니다: (a) X 사용자 또는 X 콘텐츠 조사 또는 추적을 포함하되 이에 국한되지 않는 감시 또는 정보 수집 수행 또는 제공; (b) 불법적이거나 차별적인 목적으로 또는 X 사용자의 합리적인 개인정보 보호 기대와 일치하지 않는 방식으로 분석 또는 연구 수행 또는 제공; (c) 민감한 이벤트(항의, 집회 또는 커뮤니티 조직 회의를 포함하되 이에 국한되지 않음) 모니터링; 또는 (d) 건강(예: 임신), 부정적인 재정 상태 또는 상황, 정치적 소속 또는 신념, 인종 또는 민족 출신, 종교적 또는 철학적 소속 또는 신념, 성생활 또는 성적 지향, 노동조합 가입, 범죄의 혐의 또는 실제 행위와 관련된 X 콘텐츠 또는 법률에 의해 금지된 기타 민감한 범주의 개인 정보를 포함한 민감한 개인 정보에 기반한 개인 대상화, 세분화 또는 프로파일링.
**C. 정부 사용.** 귀하가 X 콘텐츠를 정부 관련 기관이거나 정부 관련 기관을 대리하여 행동하는 사용자(각각 "**정부 최종 사용자**")에게 표시, 배포 또는 그 외의 방식으로 이용 가능하게 하는 경우; (a) 귀하는 Enterprise 요금제([developer.x.com](https://developer.x.com)에 설명됨)에 신청(또는 이미 가입)해야 합니다; (b) 귀하는 사용 사례를 X에 검토를 위해 제출할 때 그러한 모든 정부 최종 사용자를 식별해야 합니다; 그리고 (c) 그 후 서비스가 X 콘텐츠를 정부 최종 사용자에게 표시, 배포 또는 그 외의 방식으로 이용 가능하게 하거나 새로운 사용 사례를 위해 이용 가능하게 하기 전에, 어떠한 새로운 정부 최종 사용자나 기존 정부 최종 사용자와의 새로운 사용 사례에 대해 X에 서면으로 통지해야 합니다. X는 귀하가 X 콘텐츠를 어떠한 정부 최종 사용자에게 이용 가능하게 만드는 것을 금지할 수 있습니다. 귀하는 감시 수행 또는 정보 수집을 주요 기능이나 임무로 포함하는 어떠한 정부 최종 사용자에게도 X 콘텐츠 또는 X 콘텐츠에서 파생된 정보를 사용하거나 알면서 표시, 배포하거나 그 외의 방식으로 이용 가능하게 만들지 않습니다. 법 집행 기관이 진행 중인 조사 목적으로 X 또는 그 사용자에 대한 정보를 요청하는 경우, [**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support)에 위치한 X의 법 집행 가이드라인을 참조하도록 안내할 수 있습니다. X API 및 X 콘텐츠는 48 C.F.R. 2.101에 정의된 대로 "상업 항목"이며, 48 C.F.R. 12.212에서 사용되는 "상업 컴퓨터 소프트웨어" 및 "상업 컴퓨터 소프트웨어 문서"로 구성됩니다. 어떠한 정부 기관에 의한 X API 또는 X 콘텐츠의 사용, 수정, 파생, 복제, 공개, 성능, 표시, 공개 또는 배포는 본 계약의 조건에서 명시적으로 허용되는 경우를 제외하고 금지됩니다. 또한, 미국 정부 기관에 의한 어떠한 사용도 48 C.F.R. 12.212 및 48 C.F.R. 227.7202-1부터 227.7202-4까지에 따라야 합니다. 귀하가 미국 주 또는 지방 정부 기관의 직원 또는 대표로서 공식 자격으로 X API 또는 X 콘텐츠를 사용하고 여기에 있는 면책, 관할권, 법정지 또는 기타 조항을 법적으로 수락할 수 없는 경우, 그러한 조항은 법률이 요구하는 범위 내에서 그러한 기관에 적용되지 않습니다. 계약자/제조업체는 X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA입니다.
**D. 법률 준수; 수출 및 수입.** 각 당사자는 뇌물수수 및/또는 부패와 관련된 모든 법률을 포함하되 이에 국한되지 않는 모든 적용 가능한 외국, 연방, 주 및 지방 법률, 규칙 및 규정을 준수합니다. 라이선스 자료는 미국 수출법의 적용을 받으며 배송되거나 사용되는 국가의 수입 및 사용법의 적용을 받을 수 있습니다. 귀하는 이러한 법률을 준수해야 합니다. 이러한 법률에 따라, 라이선스 자료는 관련 정부 당국의 라이선스 또는 승인 없이, 미국 정부에 의해 금수 조치된 국가(현재 쿠바, 이란, 북한, 북부 수단 및 시리아)를 포함하여 이러한 법률에 의해 제한된 어떠한 국가나 외국 국적자에게, 미국 해외자산통제국에 의해 금지된 개인이나 단체를 포함하되 이에 국한되지 않는 제한되거나 거부된 최종 사용자에게, 또는 어떠한 제한된 최종 용도로도 판매, 임대, 다운로드, 이동, 수출, 재수출 또는 국경을 넘어 이전될 수 없습니다. 귀하는 서비스에 필요한 모든 권리와 라이선스를 유지합니다.
**E. 데이터 보호 부칙.** 각 당사자는 [**https://gdpr.x.com/en/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html)에 위치한 X 컨트롤러 대 컨트롤러 데이터 보호 부칙을 준수하며, 이는 X에 의해 수시로 업데이트될 수 있습니다.
**F. 존속.** 본 계약의 제III조(사용 제한), 제V조(소유권 및 피드백), 제VI조(기밀 유지), 제VII(I)조(해지), 제VIII조(준수 감사), 제IX조(보증 면책), 제X조(면책), 제XI조(책임 제한), 제XIII조(분쟁 해결 및 집단 소송 포기); 그리고 제XIV조(기타)는 본 계약의 해지 후에도 존속합니다.
**G. 완전 합의.** 본 계약은 본 계약의 주제와 관련된 당사자들의 완전한 이해를 구성하며 서면이든 구두이든 주제와 관련된 당사자 간의 모든 다른 계약을 대체합니다. 본 계약의 어떠한 조항이 법원에 의해 집행할 수 없는 것으로 판단되는 경우, 본 계약의 나머지 조항은 유효한 상태로 유지됩니다. 본 계약에 따른 어떠한 포기도 서면으로 작성되고 포기를 부여하는 당사자에 의해 서명되지 않는 한 유효하지 않습니다. 한 번 부여된 포기는 다른 경우에 포기로 작용하지 않습니다. 본 계약은 어떠한 파트너십, 대리 관계 또는 합작 사업도 만들거나 암시하지 않습니다.
# 표시 요건: 게시물
Source: https://docs.x.com/ko/developer-terms/display-requirements
브랜딩, 출처 표시, 게시물의 구성, 상호작용성 및 렌더링할 메타데이터를 포함하여 앱에서 X 게시물을 표시하기 위한 요건입니다.
## 일반 원칙 및 게시물 구성
게시물은 저희의 가장 눈에 띄는 브랜드 요소 중 하나이므로 올바르게 표시하는 것이 중요합니다. 게시물, 타임라인 및 기타 X 콘텐츠를 표시할 때 아래의 표시 요건을 준수해야 합니다.
단순히 게시물을 표시하기 위해 이러한 가이드라인을 따르는 경우, 추가적인 표시 또는 상표 권한을 위해 X에 문의할 필요가 없을 수 있습니다. 그러나 X 검토를 위해 제안된 사용 및 컨텍스트를 제출하기를 원할 수 있습니다. (경우에 따라 X는 제3자/사용자 콘텐츠 사용에 대한 권한을 제공하지 않으므로 원본 콘텐츠 작성자의 허가가 여전히 필요할 수 있습니다.)
다음 일반 원칙은 모든 표시 매체에 적용됩니다. 매체별 요건이 적용되며 아래 섹션에 요약되어 있음에 유의하시기 바랍니다.
아래 이미지는 게시물의 모든 주요 구성 요소를 보여줍니다.
### 해야 할 일
* 실제 계정의 실제, 수정되지 않은 게시물을 표시하세요.
* X의 [서비스 약관](https://x.com/tos?lang=en), [X 브랜드 자산 및 가이드라인](https://about.x.com/en_us/company/brand-resources.html) 및 (해당되는 경우) [개발자 계약 및 개발자 정책](/developer-terms/agreement)을 준수하세요.
* X 로고를 표시하세요.
### 하지 말아야 할 일
* 사용자의 명시적인 허가 없이 X 콘텐츠를 사용하여 어떤 제품이나 서비스를 홍보하지 마세요(예: 광고에 X 콘텐츠를 표시하거나 그 외의 방식으로 어떤 제품이나 서비스의 지지를 암시하기 위해 X 콘텐츠를 표시).
* X 콘텐츠를 사용하여 X의 후원, 지지 또는 X와의 잘못된 연관성을 암시하지 마세요.
* 다른 소셜 플랫폼의 버튼이나 아이콘을 포함하지 마세요.
* 게시물 텍스트를 수정하지 마세요.
* 플랫폼에 존재하지 않는 게시물의 목업을 사용하지 마세요.
***
## 온라인 표시 / 모바일, 웹 및 그 이상
저희는 X의 편리함과 강력함을 모든 사람에게 제공하는 데 전념하고 있습니다. 모든 게시물이 최적으로 표시되도록 하기 위해 [임베디드 게시물 및/또는 임베디드 타임라인](https://publish.x.com) 사용을 강력히 권장합니다. 이러한 제품을 사용하여 X 콘텐츠를 게시하면 게시물과 타임라인이 자동으로 올바르게 렌더링되며, 사진, 비디오 재생, 편집된 게시물, OAuth 없이 최신 X 데이터 가져오기와 같은 고급 기능이 포함됩니다. 임베디드 기능을 사용할 수 없는 경우 게시물과 타임라인을 온라인으로 표시할 때 아래 요건을 따라야 합니다.
### 게시물 작성자
* 게시물 작성자의 프로필 사진, @사용자이름 및 표시 이름은 항상 표시되어야 하며 사용자의 X 프로필로 연결되어야 합니다.
* 게시물 작성자의 @사용자이름은 항상 "@" 기호와 함께 표시되어야 합니다.
* 게시물 작성자의 아바타는 작성자의 이름과 @사용자이름 왼쪽에 위치해야 합니다 — 오른쪽에서 왼쪽으로 읽는 언어의 게시물의 경우 작성자의 아바타는 작성자의 표시 이름과 @사용자이름 오른쪽에 위치해야 합니다.
### 게시물 텍스트
* 게시물 텍스트는 작성자의 표시 이름과 @사용자이름 아래 줄에 표시되어야 하며 변경되거나 수정될 수 없습니다.
* 터치 장치에서 게시물 텍스트와 게시물 작성자 주변의 공백은 게시물의 퍼머링크(permalink)로 연결되어야 합니다.
* 게시물 텍스트 내의 게시물 엔티티는 X에서 적절한 위치에 올바르게 연결되어야 합니다. 예를 들어:
* 사용자 @멘션은 언급된 사용자의 프로필로 연결되어야 합니다.
* 해시태그는 해시태그를 쿼리로 하는 X 검색으로 연결되어야 합니다.
* 게시물 텍스트의 링크는 URL 엔티티 API 응답의 display\_url 필드를 사용하여 표시되어야 하며, 원래의 t.co url 필드로 연결되어야 합니다.
### 타임스탬프
* 게시물 타임스탬프는 표시되어야 하며 게시물의 퍼머링크로 연결되어야 합니다.
### 게시물 액션
* 모든 게시물 액션 아이콘(답글, 리포스트, 좋아요 포함)은 사용자가 게시물과 상호작용할 수 있도록 항상 표시되어야 합니다. 이러한 액션은 [Web Intents](/x-for-websites/web-intents/overview) 또는 인증된 X API를 사용하여 구현되어야 합니다. 게시물 액션 대신, 타임스탬프 옆에 "View on X"가 표시되어 사용자를 게시물 퍼머링크로 연결할 수 있습니다.
* 다른 소셜 또는 제3자 액션은 게시물에 첨부될 수 없습니다(예: 구독, 댓글, 좋아요).
* 표시되는 게시물이 리포스트인 경우, 리포스트한 사용자의 표시 이름과 리포스트 아이콘이 게시물 텍스트 위 또는 아래에 표시되어야 합니다. 예: "Jane Doe가 리포스트". 표시 이름은 리포스트한 사용자의 프로필로 연결되어야 합니다.
* [답글 표시 가이드라인](/developer-terms/reply-requirements)을 따르세요.
### 게시물 편집
* X는 사람들이 원래 게시물을 게시한 후 처음 30분 동안 게시물을 최대 5회까지 편집할 수 있도록 허용합니다. [임베디드 게시물](/x-for-websites/embedded-posts/overview)을 사용할 때, 게시물이 임베드되기 전에 편집되었는지 후에 편집되었는지에 따라 표시가 약간 다르게 나타납니다.
* 게시물이 먼저 임베드되고 그 후에 편집된 경우, X 플랫폼에서 발생한 편집을 그대로 표시해야 합니다:
* 편집된 게시물의 이전 버전을 표시하는 경우, 타임스탬프 아래에 게시물의 새 버전이 있음을 표시하고, 그 메모 오른쪽에 게시물의 편집 기록을 확장하는 링크를 제공해야 합니다.
* 그런 다음 게시물의 전체 편집 기록을 표시해야 합니다.
게시물이 먼저 편집된 후 임베드된 경우, 타임스탬프에 게시물이 편집되었음을 표시해야 하며, 타임스탬프는 또한 X의 라이브 게시물로 연결되어야 합니다.
### 브랜딩
* 공식 X 로고는 개별 게시물의 오른쪽 상단 모서리에 항상 합리적으로 보이도록 표시되거나 타임라인에 직접 연결되어야 합니다(예: 타임라인 상단). 로고는 이미지의 "x"와 같은 높이여야 합니다. 브랜드 가이드라인 및 자산에 대해서는 X의 [브랜드 리소스 페이지](https://about.x.com/en_us/company/brand-resources.html)를 참조하세요.
### 모바일 딥 링크
* 네이티브 모바일 앱의 딥 링크는 네이티브 X 애플리케이션으로 연결되어야 합니다. 네이티브 X 애플리케이션이 기기에 설치되어 있지 않은 경우, 링크는 웹 브라우저를 통해 X.com으로 연결되어야 합니다.
### 타임라인
* 모든 타임라인은 사용자가 개별 게시물의 세부 정보를 볼 수 있도록 허용해야 합니다(예: 게시물 타임스탬프를 링크하거나 전체 게시물 영역을 링크하여).
게시물 근처에 광고를 계획하는 경우 [개발자 정책](/developer-terms/policy)을 준수하는지 확인하세요.
이러한 규칙 중 하나 이상을 준수할 수 없는 경우, X 콘텐츠를 표시하기 전에 [정책 지원 양식](https://help.x.com/forms/platform)을 통해 직접 저희에게 연락하세요. X 이름 및 상표 사용에 관한 질문이나 추가 정보는 [trademarks@x.com](mailto:trademarks@x.com)으로 문의하세요.
***
## 방송 표시 / 15분의 명성
저희는 방송 매체에서 X의 사용을 환영하고 장려합니다. 저희의 요건은 X 사용자가 콘텐츠에 대한 적절한 출처 표시를 받도록 하며, 시청자에게 최고의 경험을 제공하는 데 도움이 됩니다.
### 해야 할 일
* 사용자의 전체 이름, @사용자이름, 게시물 텍스트 및 프로필 사진을 표시하세요.
* 방송에 게시물이 나타나는 동안 X 로고를 게시물과 가까운 곳에 포함시키세요. X 로고는 콘텐츠 대비 위 이미지의 크기와 유사하게 크기를 조정하세요.
* 게시물의 전체 텍스트를 사용하세요.
* 이미지를 표시할 때 게시물 텍스트도 사용자의 표시 이름, @사용자이름 및 X 로고와 함께 포함되어야 합니다.
### 하지 말아야 할 일
* 사용자의 명시적인 허가 없이 광고에 X 콘텐츠를 표시하거나 어떤 제품이나 서비스의 지지를 암시하지 마세요.
* 게시물 콘텐츠나 사용자의 식별을 삭제, 가림 또는 변경하지 마세요(하이퍼링크 제거는 예외).
* 타임스탬프를 제외하지 마세요.
* [trademarks@X.com](mailto:trademarks@X.com)으로 저희에게 연락하여 사용에 대해 먼저 검토받지 않은 채 제작물의 제목에 X 마크를 전체 또는 일부로 사용하지 마세요.
***
## 구두 또는 보이스오버
### 게시물
게시물의 그래픽 표시 없이 방송에서 게시물을 읽는 경우, X 로고를 표시할 필요는 없지만 X에 대한 구두 출처 표시가 필요합니다. 편집 없이 원래 작성된 대로 게시물을 읽으세요.
### 사용자 이름
X 사용자 이름을 언급할 때 X에 대한 참조를 포함시키도록 하세요. 예: "X에서 우리를 팔로우하세요, at-username" 또는 "X에서 Lady Gaga를 팔로우할 수 있습니다, at-ladygaga"
### 해시태그
X 해시태그를 언급할 때 X에 대한 참조를 포함시키도록 하세요. 예: "X에서 'election2016' 해시태그를 사용하세요" 또는 "X에서 이 방송의 해시태그는 bbcaq입니다."
# 지역 정보 가이드라인
Source: https://docs.x.com/ko/developer-terms/geo-guidelines
X API의 지오태그된 게시물 및 위치 데이터를 처리하기 위한 가이드라인으로, 지역 정보 기능, 장소 객체, 사용자 개인정보 보호 고려 사항을 포함합니다.
최종 업데이트: 2014년 10월 22일.
## 소개
Posting With Location은 X API의 지오태깅 기능입니다. 이 기능은 게시물을 보다 맥락에 맞게 만들어 사용자에게 더 의미 있는 경험을 제공하는 데 도움이 됩니다. 예를 들어, "Fireworks!"라는 문구는 위치와 연결될 때 훨씬 더 의미 있어집니다. 예: 캘리포니아 샌프란시스코의 SoMa 지역에서 게시된 "Fireworks!". 우리는 이 기능을 활용한 훌륭한 경험을 만들기 위해 개발자 생태계와 협력하기를 기대합니다!
## 사용자의 개인정보 보호 및 위치 정보에 대한 사용자 통제
훌륭하고 안전한 경험을 보장하기 위해, 개발자는 사용자의 위치 정보를 다룰 때 개인정보 보호에 민감해야 하며, "Posting with Location" 경험에서 기본적인 일관성을 제공해야 합니다. 사용자 개인정보를 보호하고 사용자가 자신의 행동이 미치는 영향을 이해할 수 있도록 유의해야 할 주요 사항은 다음과 같습니다:
## 일반 가이드라인
* 사용자는 Posting With Location 기능을 사용하기 위해 옵트인해야 합니다(위치를 "켜기"로 전환).
* 사용자는 정확한 위치가 자신의 게시물과 함께 표시되도록 명시적으로 허용해야 합니다. 클라이언트의 위치 기능이 "고정형(sticky)"인 경우 — 즉, 위치가 한 번 켜지면 항상 게시물에 첨부되는 경우 — 장소 이름(place\_ids)만 표시하고, 사용자가 게시물별로 또는 특정 대체 설정으로 정확한 위도/경도에 추가로 옵트인할 수 있도록 하는 것을 고려할 수 있습니다.
* 게시물을 작성하기 위해 사용자의 위치 데이터에 접근할 때, 해당 정보는 사용자의 명시적 허가 없이 게시물과 별도로 저장되어서는 안 됩니다.
* 게시물과 관련하여 어떤 수준의 위치 정보가 표시될지 사용자에게 명확해야 합니다. 이를 위한 한 가지 방법은 게시물이 게시되기 전에 이 정보가 어떻게 표시될지를 지도로 보여주는 것입니다. 정확한 위도와 경도가 사용자가 클라이언트에 게시하는 정보의 일부(또는 유일한 정보)인 경우, 정확한 좌표가 게시된다는 사실을 사용자에게 명확히 해야 합니다.
* 사용자는 게시물을 작성할 때마다 위치를 켜거나 끌 수 있어야 합니다.
* X의 [개발자 정책](/developer-terms/policy.html)의 조항을 준수해야 합니다 — 여기에는 X API에서 얻은 위치 데이터 및 기타 지리 정보를 게시물의 일부로서 외에는 집계, 캐싱, 저장할 수 없으며, 이러한 위치 데이터 또는 지리 정보를 독립적으로 사용할 수 없다는 요건이 포함됩니다.
## 구체적인 예시
예 1: *명시적인 위도 및 경도의 추가 없음 (현재 X 웹 클라이언트 UI)*
1. 사용자가 게시물을 작성할 때 "위치 추가"에 대한 링크를 표시합니다;
2. 백그라운드에서 X의 [reverse\_geocode](https://developer.x.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode.html) API 호출을 사용하여 위도, 경도, 좌표의 정확도, 사용자가 선호하는 세분화 수준(기본값은 "neighborhood")을 전달합니다;
3. 기본 장소의 이름을 표시합니다(X는 이러한 이름을 이해하기 쉬운 순서로 정렬하려고 시도합니다 - 이 순서는 X 클라이언트가 수정할 필요 없이 그대로 목록을 표시할 수 있도록 되어 있습니다);
4. 사용자가 목록에서 다른 위치를 선택할 수 있도록 허용합니다(예: "SoMa, San Francisco"에서 "South Beach, San Francisco"로 변경).
5. 중요: 정확한 위치 정보를 표시하는 경우 사용자에게 투명하게 알리세요. 정확한 위치 정보가 표시된다는 것을 사용자가 알고 있는지 확인하세요.
6. 사용자가 게시물을 작성할 때마다 위치를 켜거나 끌 수 있도록 선택권을 제공합니다.
예 2: *기존의 지오태깅 구현*
여러 X 클라이언트 앱은 원본 지오태깅 기능(place\_ID를 제공하지 않고 위도/경도만 전송)을 구현하고 있습니다. API의 기본 동작은 이 동작을 그대로 따르며 — 즉, 개발자로서 오늘 존재하는 동작을 유지하기 위해 기존 앱을 변경할 필요가 없습니다. 실제로, 위도/경도 좌표를 X에 그대로 전달하면, X는 자동으로 해당 위도와 경도를 역지오코딩하여 데이터가 있는 지역에 대해서는 위도/경도 외에 place\_ID도 표시합니다.
사용자의 정확한 좌표가 X에서 사용되고 표시된다는 사실이 사용자에게 투명하게 전달되도록 하세요. 기존 앱에 대한 모범 사례는 사용자가 게시물별로 위치를 켜거나 끌 수 있도록 하는 것입니다. 또한, 사용자가 정확한 좌표 대신 place\_ID만 공유하도록 기본, "고정형" 설정을 사용하도록 활성화할 수도 있습니다.
## X의 사용자 위치 데이터 저장
X는 클라이언트가 전달한 데이터를 다음과 같이 저장합니다:
* X는 사용자가 팔로워에게 공개적으로 표시하기로 선택한 모든 데이터를 저장합니다. 이는 X가 게시물이 언제 작성되었는지를 나타내는 타임스탬프를 저장하는 방식과 유사합니다. 즉, 사용자가 자신의 정확한 좌표와 함께 게시한 경우, X는 게시물이 존재하는 동안 이 정확한 위치를 게시물과 함께 저장합니다. 사용자는 [여기](https://support.twitter.com/articles/122236-how-to-tweet-with-your-location)에 설명된 대로 설정 페이지에서 "내 위치 기록 지우기" 버튼을 클릭하여 게시물에서 위치 데이터를 지울 수 있습니다.
## 요약
게시물에 위치를 추가하면 사용자 관점에서 엄청난 양의 컨텍스트와 가치가 더해집니다. 그러나 클라이언트에서 위치를 구현할 때는 위치 중심 제품을 설계할 때 개인정보 보호와 사용자에 대한 투명성을 핵심 고려 사항으로 삼도록 신중해야 합니다.
개인정보 보호, 위치, 기타 지역 정보 기능에 대한 질문이나 의견이 있으면 [문의해 주세요.](https://support.twitter.com/forms/platform)
# X 개발자 정책
Source: https://docs.x.com/ko/developer-terms/policy
X 개발자 정책은 콘텐츠, 자동화, 개인정보 보호, 보안 및 금지된 행동에 관한 규칙을 포함하여 X API의 허용 가능한 사용을 개괄합니다.
## X + 개발자
X는 개발자를 사랑합니다. 저희는 이 커뮤니티가 X 데이터의 힘을 활용하여 만드는 도구와 서비스에 기쁘고 놀랍니다. 이 커뮤니티에 대한 저희의 헌신의 일환으로 개발자에게 개방적이고 공정하며, X 사용자에게 안전하고, X 플랫폼 전체에 유익한 데이터 접근을 제공하는 것을 목표로 합니다. 이러한 목표를 더욱 발전시키기 위해 저희는 사람들이 적절한 API 및 X 콘텐츠 사용에 대한 규칙과 기대사항을 이해하는 데 도움이 되는 가이드로서 개발자 정책을 만들었습니다.
이 개발자 정책("**정책**")은 X의 애플리케이션, 서비스, 웹사이트, 웹 페이지 및 콘텐츠 생태계와 상호작용하는 개발자를 위한 규칙과 가이드라인을 제공합니다. 이는 X API 및 X 콘텐츠에 대한 접근 및 사용을 규율하는 X와의 계약(개발자 계약 또는 X와의 기타 서면 계약의 일부로서)의 일부입니다. 정책 위반은 계약 위반으로 간주됩니다. 이 정책은 통지 없이 수시로 변경될 수 있습니다. 이 정책에서 사용되나 정의되지 않은 대문자로 시작하는 용어는 [개발자 계약](/developer-terms/agreement) 또는 Master License Agreement에서 각각에 부여된 의미를 갖습니다.
## 이 정책 사용하기
저희는 이 정책을 가능한 한 쉽게 따를 수 있도록 구조화했습니다. X API 및 X 콘텐츠를 사용할 때 다음 정책 섹션의 정보를 염두에 두시기 바랍니다:
1. **플랫폼 사용 가이드라인 준수** - X API 및 X 콘텐츠 접근이 승인되는 것은 첫 번째 단계일 뿐입니다. X 플랫폼의 계획된 사용에 대한 정책 준수를 보장하는 방법에 대한 질문이 있을 때마다 저희 플랫폼 사용 가이드라인이 첫 번째 참조 자료가 되어야 합니다.
2. **성공을 위한 준비** - 귀하는 모든 X 정책을 준수할 책임이 있습니다. X API 및 X 콘텐츠에 접근하기 전에 이 정책과 이 문서에서 링크하는 정책을 검토하고 이해하는 것이 중요합니다. 저희 정책을 검토하는 데 소요된 시간은 나중에 재작업하는 시간을 절약할 수 있습니다.
3. **개인정보 보호 및 통제는 필수적입니다** - X에서 사람들의 개인정보를 보호하고 방어하는 것은 회사의 핵심 DNA에 내재되어 있습니다. 이에 따라 저희는 사람들의 합리적인 개인정보 보호 기대와 일치하지 않는 어떠한 방식으로도 X 데이터를 사용하는 것을 금지합니다. X API를 기반으로 구축하거나 X 콘텐츠에 접근함으로써, 귀하는 이러한 약속을 보호하는 데 특별한 역할을 담당하며, 가장 중요하게는 사람들의 개인정보를 존중하고 그들의 데이터가 사용되는 방법에 대한 투명성과 통제권을 제공합니다.
이 세 가지 주요 섹션의 각각의 의미에 대한 자세한 내용을 아래에 제공했습니다. X API 및 X 콘텐츠의 귀하의 사용이 저희 정책과 일치하도록 신중하게 검토하시기 바랍니다.
이 정책(또는 다른 X 정책)을 위반한다고 판단되면, 저희는 X API 및 X 콘텐츠에 대한 귀하의 접근을 정지하거나 영구적으로 취소할 수 있습니다.
마지막으로, X는 X 애플리케이션 개선, 상업적 사용 검사 및 승인된 사용 사례 및 이 정책의 준수 확인을 위해 귀하의 X API 사용을 모니터링할 수 있음에 유의하시기 바랍니다.
읽어주셔서 감사드리며, 저희와 함께 구축해 주셔서 감사합니다! 여러분이 만드는 것을 기대하고 있습니다!
## 플랫폼 사용 가이드라인
X의 정책을 검토하고 API 접근을 올바른 방식으로 설정하는 데 주의를 기울이셨습니까? 귀하의 서비스가 X의 개인정보 보호 및 통제 가이드라인을 따르고 있습니까? 이 두 가지 질문에 예라고 답할 수 있다면, X API 및 X 콘텐츠 사용을 시작할 준비가 된 것입니다. X의 플랫폼 사용 가이드라인은 서비스 수명 주기 전반에 걸쳐 첫날부터 X 콘텐츠 사용이 준수되도록 하는 데 필요한 지원을 제공합니다. X 사용자와 X 플랫폼 전체에 안전하고 유익한 방식으로 통합이 작동하도록 이러한 규칙을 정기적으로 검토하는 것이 좋습니다.
## 스팸, 봇 및 자동화
**X API 및 개발자 제품을 사용하여 스팸을 생성하거나 어떠한 형태의 플랫폼 조작에 관여하는 것은 금지됩니다.** [플랫폼 조작 및 스팸](https://help.x.com/rules-and-policies/platform-manipulation)에 관한 X 규칙을 검토하고 귀하의 서비스가 저희 정책을 위반하지 않으며 사람들이 위반할 수 있도록 하지 않는지 확인해야 합니다.
[**게시물 게시, 계정 팔로우, Direct Message 보내기를 포함한 쓰기 작업을 수행하는 서비스는 자동화 규칙을 따라야 합니다.**](https://help.x.com/rules-and-policies/x-automation) 특히 다음을 준수해야 합니다:
* [자동화된 답글 또는 Direct Message](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444)를 사용자에게 보내기 전에 항상 명시적인 동의를 받으세요
* 귀하로부터 연락받는 것을 옵트아웃하는 요청을 즉시 존중하세요
* [대량 팔로우](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769)를 포함한 대량, 공격적 또는 스팸성 작업을 절대 수행하지 마세요
* [여러 계정](https://blog.twitter.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html)에 걸쳐 동일하거나 실질적으로 유사한 콘텐츠를 절대 게시하지 마세요
**API 기반 봇 계정을 운영하는 경우 해당 계정이 무엇이고 누가 책임지는지 명확하게 표시해야 합니다.** 귀하의 계정이 봇인지 아닌지에 대해 사람들을 오해시키거나 혼란스럽게 해서는 안 됩니다. 이를 수행하는 좋은 방법은 프로필 약력에 계정이 봇이라는 진술을 포함하는 것입니다.
## X 성능 벤치마킹
**X API를 사용하여 벤치마킹, 경쟁 또는 상업적 목적으로 X의 가용성, 성능, 기능 또는 사용량을 측정할 수 없습니다.** 예를 들어, X API를 다음 용도로 사용해서는 안 됩니다:
* 월간 활성 사용자(MA) 또는 일일 활성 사용자(DA) 총 수와 같은 X 지표 집계 계산
* 하루 게시된 게시물 총 수 또는 계정 참여 수와 같은 X 게시물 지표 집계 계산
* X의 응답성 측정 또는 분석
* 아래에서 허용된 경우를 제외하고 X의 스팸이나 보안 측정 또는 분석
**저희는 X에서 대화의 건강성을 개선하는 데 도움이 되는 연구를 지원합니다.** X의 명시적인 서면 허가 없이 X 정책을 위반하는 행동이나 콘텐츠를 측정, 분석 또는 식별하려는 X API 또는 X 콘텐츠를 사용하여 연구 또는 결과를 공개적으로 공개하거나 서비스를 개발, 생성 또는 제공할 수 없습니다.
**DSA 연구자:** 디지털 서비스법 제40조에 따른 접근과 관련하여 X에 연락해야 하는 경우 [**EU-Questions@X.com**](mailto:EU-Questions@X.com)으로 연락하세요. 연구자 접근을 신청하려면 [신청서](https://forms.gle/btDwenPF7M3hgSvw7)를 제출하세요.
## 게시물의 공개 표시
**공개적으로 또는 서비스를 사용하는 사람들에게 표시하는 모든 X 콘텐츠의 무결성을 유지해야 합니다.** [X for Websites](https://developer.x.com/docs/twitter-for-websites/overview)를 사용하여 콘텐츠를 표시하지 않는 경우, X API를 사용하여 표시할 수 있는 가장 최신 버전을 검색해야 합니다. 표시된 콘텐츠가 X API를 통해 더 이상 이용할 수 없게 되면, 합리적으로 가능한 한 빨리 또는 X, 해당 X 계정 소유자로부터 제거 요청을 받은 후 24시간 이내에, 또는 관련 법률에 의해 그 외의 방식으로 요구되는 대로 서비스에서 제거해야 합니다.
**오프라인으로 X 콘텐츠를 표시하는 경우 따라야 하는 특정 규칙이 있습니다.** 오프라인으로 게시물을 표시하는 경우 방송에서 게시물 사용을 위한 [가이드라인](https://developer.x.com/developer-terms/display-requirements)을 따르세요.
**게시물을 임베드하거나 표시하는 경우, 사이트가 일일 노출수 1천만을 초과하면 X API 접근에 대해 저희에게 연락해야 합니다.** X는 X API 사용 조건으로 추가 약관을 요구할 권리를 보유합니다. X for Websites 개발자 사용에 대한 추가 제한 사항은 다음과 같습니다:
* **임베디드 게시물 및/또는 임베디드 타임라인**
* 관심 기반 광고 및 개인화를 위해 X의 웹사이트에서의 브라우징 활동에 관한 데이터 수집 및 사용을 완전히 공개하는 법적으로 충분한 통지를 사람들에게 제공해야 합니다. 또한 이러한 수집 및 사용에 대해 사람들로부터 법적으로 충분한 동의를 얻어야 합니다
* [여기](https://help.x.com/x-for-websites-ads-info-and-privacy)에 설명된 대로 사람들이 X의 관심 기반 광고 및 개인화에서 옵트아웃하는 방법에 대한 법적으로 충분한 지침을 제공해야 합니다
* **X for Websites 위젯**
* 법률이 그러한 정보 제공 및 동의 획득을 요구하는 경우, X의 [쿠키 사용](https://help.x.com/rules-and-policies/x-cookies)에 설명된 대로 기기의 쿠키 또는 기타 정보의 저장 및 접근에 대해 사람들에게 명확하고 포괄적인 정보가 제공되고 이에 동의하는지 확인해야 합니다
* **만 13세 미만의 어린이를 대상으로 하는 서비스**
* 만 13세 미만의 어린이를 대상으로 하는 서비스는 [여기](https://developer.x.com/docs/twitter-for-websites/privacy)에 설명된 대로 옵트아웃 매개변수를 'true'로 설정하여 임베디드 게시물 및/또는 임베디드 타임라인에서 X의 맞춤화를 옵트아웃해야 합니다
## 콘텐츠 재배포
**X 콘텐츠를 얻는 가장 좋은 곳은 X에서 직접 받는 것입니다. 따라서 저희는 X 콘텐츠를 제3자에게 재배포하는 것을 제한합니다.** 다운로드 가능한 데이터세트 또는 API를 통해 X 콘텐츠를 제3자에게 제공하는 경우, 게시물 ID, Direct Message ID 및/또는 사용자 ID만 배포할 수 있습니다(아래 설명된 경우 제외).
X의 서면 허가를 받지 않는 한 어떤 30일 기간 내에 1,500,000개를 초과하는 게시물 ID를 어떠한 개체(단일 개체와 관련된 여러 개인 포함)에게도 배포할 수 없습니다. 또한 개발자는 비자동화된 수단(예: 스프레드시트 또는 PDF 다운로드)을 통해 서비스를 사용하는 각 사람에게 매일 최대 500개의 공개 게시물 객체 및/또는 사용자 객체를 제공할 수 있습니다.
학술 연구자는 학술 기관을 대신한 비상업적 연구 또는 그러한 연구의 동료 심사나 검증을 유일한 목적으로 게시물 ID 및/또는 사용자 ID를 배포하도록 허용되며, X의 서면 승인이 있어야 합니다. 그러한 연구에 필요하고 X가 승인한 만큼의 게시물 ID 또는 사용자 ID만 사용될 수 있습니다.
제3자에게 제공된 모든 X 콘텐츠는 계속해서 이 정책의 적용을 받으며, 해당 제3자는 그러한 다운로드를 받기 전에 X [서비스 약관](https://x.com/tos), [개인정보 처리방침](https://x.com/privacy), [개발자 계약](/developer-terms/agreement) 및 [개발자 정책](/developer-terms/policy)에 동의해야 합니다. 이 [정책](/developer-terms/policy), [개발자 계약](/developer-terms/agreement) 또는 X와의 기타 계약에 포함된 X 콘텐츠의 배포에 관한 어떠한 다른 제한 사항이나 제한도 어떠한 개체가 우회하도록 허용해서는 안 됩니다.
**참고:** 이 섹션은 EU 디지털 서비스법(2022)("**DSA**") 제40조를 통해 X API 접근권을 가진 연구자에게는 적용되지 않으며, 대신 DSA 및 개발자 계약에 명시된 절차 및 제한 사항의 적용을 받습니다.
## 참여에 대한 유료 제공
**귀하의 서비스는 사람들이 X에서 조치를 취하도록 보상해서는 안 되며, 이는 플랫폼의 건전성을 저하시키는 비정품 참여를 초래하기 때문입니다.** X API를 사용할 때 어떠한 X 조치에 대해서도 금전적 또는 가상 보상을 판매하거나 받을 수 없습니다. 여기에는 게시물, 팔로우, 언팔로우, 리포스트, 좋아요, 댓글 및 답글이 포함되지만 이에 국한되지 않습니다.
## 서비스 정품성
**사람들이 서비스의 출처와 목적을 이해할 수 있도록 서비스를 명확하게 식별해야 합니다.** 서비스의 정체성과 기능을 감추거나 X 또는 제3자와의 잘못된 제휴 관계를 암시하는 이름, 로고 또는 URL을 사용하지 마세요. 이름을 판매하거나 다른 사람이 이름을 사용하는 것을 방지할 목적으로 애플리케이션을 만드는 것은 금지됩니다.
**귀하의 서비스에 대해 사람들을 다음으로 안내하는 URL(단축 URL 포함)을 사용할 수 없습니다:**
* 서비스와 무관한 사이트
* 스팸 또는 악성 소프트웨어 사이트
* X 정책을 위반하도록 사람들을 권장하는 사이트
## X 이름, 로고 및 유사한 마크
**X를 X 콘텐츠의 출처로 식별하기 위해서만 X 이름과 로고를 사용하고 표시할 수 있습니다.** X와의 지지, 후원 또는 관련성이라는 잘못된 느낌을 만드는 방식으로 X 이름과 로고, X Official Partner Program 배지 또는 기타 유사한 마크나 이름을 사용해서는 안 됩니다. X [브랜드 리소스](https://about.x.com/who-we-are/brand-toolkit)에는 올바른 방식으로 X 브랜드를 사용하는 데 도움이 되는 자세한 정보가 포함되어 있습니다.
**X가 API를 통해 귀하에게 보고한 대로만 X Verified Account 배지 및 기타 향상된 계정 분류를 사용할 수 있습니다.** 이를 통해 사람들은 귀하의 서비스가 표시하는 콘텐츠가 X에 표시된 것과 동일하다는 것을 알 수 있습니다.
## X에서의 광고
**X 콘텐츠 주변에서 광고할 수 있는 방법과 위치에 관한 제한이 있습니다.** 우선 광고는 게시물과 유사하거나 사람들이 게시물과 합리적으로 혼동할 수 없습니다. 광고에 대한 기타 규칙은 다음과 같습니다:
* **X 콘텐츠와 광고 사이에는 명확한 구분이 있어야 합니다.** X 광고 이외의 광고를 X 타임라인 내에 배치할 수 없습니다.
* **X는 X API를 통해 광고를 제공할 권리를 보유합니다.** API를 통해 X 광고를 제공하기 시작한 후 X 광고 게재를 결정한 경우, 관련 이용약관에 따라 광고 수익의 일부를 귀하와 공유합니다.
* **X 콘텐츠 또는 X API를 통해 얻은 정보를 사용하여 X 플랫폼 외부에서 사람들에게 광고를 타겟팅할 수 없습니다.**
아래에 나열된 X 서비스 또는 기능을 사용하는 경우 다음 추가 규칙이 적용됩니다:
## X 로그인
**예를 들어 OAuth 프로토콜을 통해 X에 로그인하고 로그아웃할 수 있는 쉽게 찾을 수 있는 옵션을 사람들에게 제공해야 합니다.** *Sign in with X* 옵션은 서비스의 다른 가입 또는 로그인 기능만큼이나 눈에 띄게 표시되어야 합니다. 또한 X 계정이 없는 사람들에게 X를 통해 계정을 만들 수 있는 기회를 제공해야 합니다.
***귀하의 서비스에서 누군가가 Sign in with X를 통해 인증되면 X 정체성을 명확하게 표시해야 합니다.*** X 정체성에는 그 사람의 현재 X @핸들, 아바타 및 X 로고가 포함됩니다. 서비스에서 누군가의 X 팔로워를 표시할 때는 관계가 X와 관련되어 있음을 명확하게 표시해야 합니다.
X는 귀하의 제품, 서비스 또는 귀하나 계열사가 제공하거나 귀하나 계열사를 위해 제공된 것에 Sign In with X(또는 기타 X 인증 방법)를 통해 인증되었거나 로그인한 총 고유 사용자 수를 모니터링할 권리를 보유하며, 그 총 수가 유사한 서비스 등급에 가입한 다른 개발자의 일반적인 수준을 크게 초과하는 경우, X의 서면 통지를 받은 후 귀하는 Enterprise 요금제에 신청(또는 이미 가입)해야 합니다.
귀하는 X가 수시로 *Sign in with X* 옵션을 검토하고 단독 재량으로 서비스에서 이 X 기능을 제거할 수 있음에 동의합니다.
## X Cards
**품질 경험을 보장하기 위해 카드가 표시되는 모든 플랫폼에서 렌더링되도록 카드를 개발해야 합니다.** 카드를 사용할 때 따라야 하는 추가 규칙은 다음과 같습니다:
* 카드 내에 그러한 미디어를 표시하려는 경우 게시물을 민감한 미디어에 대해 'true'로 표시해야 합니다
* 카드 내의 모든 자산 호스팅에 HTTPS를 사용해야 합니다. 카드는 활성 혼합 콘텐츠 브라우저 경고를 절대 생성해서는 안 됩니다
* 오디오 및 비디오 콘텐츠에는 정지 또는 일시 정지 컨트롤이 포함되어야 하며, 콘텐츠를 자동으로 재생하는 비디오는 기본적으로 '사운드 꺼짐'이어야 합니다
**카드의 의도된 용도를 포함하여 X가 카드에 부과한 제한을 초과하거나 우회할 수 없습니다.** 카드 사용에 대한 추가 제한 사항은 다음과 같습니다:
* X의 승인 없이 카드 내에 제3자 후원 콘텐츠를 배치할 수 없습니다
* 카드 내 또는 카드에서 X에 금전적 인센티브(가상 통화 포함)를 첨부할 수 없습니다
* URL 및 미디어와 같이 오해의 소지가 있거나 문맥적으로 관련이 없는 콘텐츠나 액션을 카드 내에 포함할 수 없습니다.
* App Card는 사람들이 게시물에서 명시적으로 앱을 홍보하거나 언급할 때만 게시물에 첨부할 수 있습니다.
## 성공을 위한 준비
첫날부터 서비스가 올바른 방식으로 구축되도록 하여 X API를 사용하는 동안 잠재적인 함정을 피할 수 있습니다. 개발자 정책의 이 섹션에는 모든 개발자가 X API 또는 X 콘텐츠를 사용하기 전에 따라야 하는 규칙이 포함되어 있습니다.
Free, Basic 및 Pro 요금제([developer.x.com](http://developer.x.com)에 설명됨)는 취미 개발자, 상업적 프로토타이핑, 초기 단계 X 제품 통합 및 제한된 최종 사용자를 지원하는 애플리케이션을 위해 설계되었습니다. 이 범위를 넘어 X API 및 X 콘텐츠를 사용하는 경우 Enterprise 요금제([developer.x.com](http://developer.x.com)에 설명됨)에 신청(또는 이미 가입)해야 합니다.
**저희는 X 개발자 플랫폼의 모든 제안된 사용을 검토하여 정책 준수 여부를 확인합니다 — 따라서 접근 권한을 부여받고 유지하기 위해 X API 및 X 콘텐츠의 계획된 사용을 공개(및 해당하는 경우 업데이트)해야 합니다.** 모든 새로운 개발자는 X API에 접근하기 위해 [개발자 계정을 신청](https://developer.x.com/portal/petition/essential/basic-info)해야 합니다. 승인된 개발자 계정이 없는 현재 개발자는 X의 지시에 따라 신청해야 합니다. 이 과정의 일부로 X API 및 X 콘텐츠의 의도된 사용에 대한 서면 설명을 저희에게 제공해야 합니다.
귀하의 사용 사례 설명은 귀하에게 구속력이 있으며, 이로부터의 실질적인 편차는 저희 규칙 위반에 해당할 수 있으며 집행 조치를 초래할 수 있습니다. 사용 사례에 대한 실질적인 수정 사항을 저희에게 통지하고 새로운 목적으로 X 콘텐츠 사용을 시작하기 전에 승인을 받아야 합니다. 이를 이행하지 않으면 API 및 데이터 접근 정지 및 해지로 이어질 수 있습니다.
**X API를 기반으로 구축하거나 X 콘텐츠에 접근함으로써 모든 X 정책을 준수해야 합니다.** 여기에는 이 [개발자 정책](/developer-terms/policy), [자동화 규칙](https://help.x.com/rules-and-policies/x-automation), [표시 요건](https://developer.x.com/developer-terms/display-requirements.html), [API 제한된 사용 규칙](/developer-terms/restricted-use-cases), [X 규칙](https://help.x.com/rules-and-policies/x-rules) 및 [X 브랜드 리소스](https://about.x.com/who-we-are/brand-toolkit)뿐만 아니라 X API 또는 X 콘텐츠의 사용과 관련하여 X와 체결한 [개발자 계약](/developer-terms/agreement) 또는 Master Licensing Agreement 또는 Order(해당되는 경우)를 포함하되 이에 국한되지 않는 기타 계약이 포함됩니다. 또한 이러한 정책의 수정 사항과 X에 의해 시작된 새로운 정책도 준수해야 합니다. 서비스 사용을 모니터링하고 서비스를 사용하는 사람들에 의한 X 정책 위반을 방지하도록 서비스를 설계하는 것은 귀하의 책임입니다. 이를 이행하지 않으면 API 및 X 콘텐츠 접근 정지 또는 해지로 이어질 수 있습니다.
**단일 사용 사례 또는 실질적으로 유사하거나 중복되는 사용 사례에 대해 여러 애플리케이션을 등록할 수 없습니다.** 이 맥락에서 "사용 사례"는 애플리케이션을 통해 수행되는 일관된 분석, 표시 또는 작업 집합입니다. 도구 또는 서비스의 "화이트 라벨" 버전은 허용되지 않습니다. 애플리케이션의 "화이트 라벨" 버전을 계획하는 경우, 저희에게 알리고 별도의 승인을 받아야 합니다.
*이 규칙에 대한 단일 예외로,* 동일한 서비스의 개발, 스테이징 및 프로덕션 인스턴스에 대해 최대 3개의 애플리케이션을 만들고 사용할 수 있습니다. 이러한 앱은 단일 계정에 등록되어야 하며, 단일 서비스의 개발, 스테이징 및 프로덕션 인스턴스로(이름과 설명에서) 명확하게 식별되어야 합니다. **개발 또는 스테이징 애플리케이션을 프로덕션 목적으로 사용할 수 없습니다.**
**모든 API 키 또는 기타 접근 자격 증명을 비공개로 유지해야 합니다.** 다른 사람이 소유한 API 키 또는 기타 접근 자격 증명을 사용하거나 다른 사람이 사용하도록 권장하거나 촉진할 수 없습니다.
**X와의 라이선스 계약은 X API 및 X 콘텐츠 사용을 제한합니다. 특히 X API에는 공정한 데이터 사용을 보장하고 플랫폼에서 스팸을 방지하는 데 도움이 되는 속도 제한이 있습니다.** 이 정책 또는 X와의 계약에 설명된 속도 제한 또는 기타 제한 사항이나 제한을 초과하거나 우회하거나, [Developer Site](https://developer.x.com/)에 나열되어 있거나 X가 귀하에게 전달한 것을 초과할 수 없습니다.
**X API를 통해 받은 X 콘텐츠의 소유권 표시 또는 마크를 제거하거나 변경할 수 없습니다.** 이는 사람들이 X 콘텐츠의 출처와 소유자가 누구인지 알 수 있도록 하는 데 도움이 됩니다.
**데이터 무결성 및 플랫폼 건강상의 이유로 X API 또는 X 서비스의 기능을 방해, 가로채기, 중단 또는 비활성화할 수 없습니다.** 즉, [developer.x.com](https://developer.x.com/)에 문서화된 대로 API를 의도된 대로 사용하세요. 허용 가능한 사용에 대한 자세한 내용은 [HackerOne 가이드라인](https://hackerone.com/x)을 참조하세요.
## 개인정보 보호 및 통제는 필수적입니다
X는 개인정보 보호를 진지하게 여기며, X 콘텐츠와 X API를 사용하는 모든 사람도 마찬가지로 행동할 것을 기대합니다. 사람들의 합리적인 개인정보 보호 기대와 일치하지 않는 방식으로 X 개발자 플랫폼, X API 또는 X 콘텐츠를 사용하는 것은 API 및 X 콘텐츠 접근 정지 및 해지를 포함할 수 있는 집행 조치의 대상이 될 수 있습니다.
개인정보 보호 및 통제에 대한 귀하의 약속은 X 콘텐츠의 모든 사용과 저희 API를 사용하여 구축하는 서비스의 모든 측면에 확장되어야 합니다. 이를 위해 서비스를 사용하는 사람들은 데이터를 어떻게 사용하고 자신을 대신하여 X에 접근하는지 이해하고 동의해야 합니다. 이는 사람들에게 명확하고 포괄적이며 투명한 개인정보 처리방침을 제공하고, 자신을 대신하여 어떠한 조치를 취하기 전에 서비스를 사용하는 각 사람으로부터 명시적이고 통보된 동의를 얻도록 하는 것을 통해 달성할 수 있습니다. **서비스에 인증하는 사람이 그 자체로 동의를 구성하지 않음에 유의하시기 바랍니다.**
## 동의 및 권한
**특히 다음 중 하나를 수행하기 전에 사람들로부터 명시적이고 통보된 동의를 얻어야 합니다:**
* 그들을 대신하여 *어떠한* 조치도 취하기. 여기에는 다음이 포함됩니다(이에 국한되지 않음):
* X에 콘텐츠 게시
* 계정 팔로우/언팔로우
* 프로필 또는 계정 정보 수정
* 게시물에 해시태그 또는 기타 콘텐츠 추가
* X API 또는 기타 X 도구가 아닌 다른 방법으로 접근한 콘텐츠 재게시
* 다른 사람의 X 콘텐츠를 사용하여 제품이나 서비스 홍보
* Direct Message(DM)와 같은 비공개 콘텐츠 또는 기타 사적이거나 기밀 정보 저장
* 보호된 콘텐츠 또는 기타 사적이거나 기밀 정보 공유 또는 게시
**서비스에서 사람들이 X에 콘텐츠를 게시할 수 있도록 하는 경우 게시 전에 다음을 수행해야 합니다:**
* 정확히 무엇이 게시될지 표시
* 콘텐츠에 어떤 지역 정보(있는 경우)가 추가될지 서비스를 사용하는 사람들에게 명확하게 알리기
**서비스에서 사람들이 서비스와 X에 모두 콘텐츠를 게시할 수 있도록 하는 경우 게시 전에 다음을 수행해야 합니다:**
* 콘텐츠 게시 권한 획득
* 콘텐츠를 게시할 위치 설명
**모든 X 콘텐츠의 보호 및 차단 상태를 존중해야 합니다. 한 사람의 인증 토큰을 사용하여 얻은 콘텐츠를 해당 콘텐츠를 볼 권한이 없는 다른 사람에게 제공할 수 없습니다.**
* **보호된 계정:** [보호된 계정](https://help.x.com/safety-and-security/public-and-protected-posts)의 콘텐츠는 소유자가 해당 계정을 팔로우하도록 승인한 사람에게만 이용 가능합니다. 따라서 보호된 계정에 접근하는 서비스를 운영하는 경우, 해당 콘텐츠를 볼 권한이 있는 특정 사람에게 그러한 콘텐츠를 제공하기 위해서만 그렇게 할 수 있습니다.
* **차단된 계정:** X의 사람들은 자신이 선택한 어떠한 이유로든 계정에 대한 접근을 [차단](https://help.x.com/using-x/blocking-and-unblocking-accounts)할 수 있습니다. 이 선택을 우회하기 위해 토큰(또는 기타 API 기반 조치)에서 얻은 정보를 혼합하는 것은 허용되지 않습니다.
**Direct Message(DM)는 본질적으로 비공개이므로, DM 기능을 제공하는 서비스는 개인 프라이버시를 보호하기 위한 추가 조치를 취해야 합니다. DM 콘텐츠를 해당 콘텐츠를 볼 권한이 없는 사람에게 제공할 수 없습니다. 서비스가 DM 기능을 제공하는 경우 다음도 수행해야 합니다:**
* DM에 대한 읽음 확인 이벤트를 보내는 경우 사람들에게 알리기. 이는 서비스에 직접 알림을 제공하거나 대화의 다른 참가자로부터 읽음 확인을 표시함으로써 수행할 수 있습니다.
* DM에서 전송될 미디어를 "공유"(즉, 여러 DM에서 재사용 가능)로 구성하기 전에 동의 획득. DM의 미디어를 "공유"할 수 있도록 허용하는 경우, 이 콘텐츠가 미디어 URL을 가진 누구에게나 접근 가능하다는 명확한 통지를 제공해야 합니다.
## 콘텐츠 준수
**X 콘텐츠를 오프라인으로 저장하는 경우 X의 해당 콘텐츠의 현재 상태와 최신 상태로 유지해야 합니다.** 구체적으로, X에서 삭제되거나 수정된 경우 소유한 어떠한 콘텐츠도 삭제하거나 수정해야 합니다. 이는 합리적으로 가능한 한 빨리, 또는 X 또는 해당 X 계정 소유자로부터 요청을 받은 후 24시간 이내에, 또는 X와의 계약이나 관련 법률에 의해 그 외의 방식으로 요구되는 대로 수행되어야 합니다. 이는 법률에 의해 그 외의 방식으로 금지되지 않는 한 수행되어야 하며, 오직 X의 명시적 서면 허가가 있어야만 수행됩니다.
수정된 콘텐츠는 다양한 형태를 취할 수 있습니다. 여기에는 다음이 포함됩니다(이에 국한되지 않음):
* 비공개로 전환되었거나 보호 상태를 획득한 콘텐츠
* 플랫폼에서 정지된 콘텐츠
* 지오태그가 제거된 콘텐츠
* X에서 보류되거나 제거된 콘텐츠
## Off-X 매칭
**X상의 사람을 X 외부에서 얻거나 저장된 정보와 매칭할 수 있는 상황을 제한합니다.** Off-X 매칭은 X 콘텐츠(X @핸들 또는 사용자 ID 포함)를 사람, 가정, 기기, 브라우저 또는 기타 오프-X 식별자와 연관시키는 것을 의미합니다. 이는 아래에 설명된 대로 또는 연관을 만들기 전에 사람으로부터 명시적인 옵트인 동의가 있는 경우에만 수행할 수 있습니다.
X 정체성을 오프-X 식별자에 연결하기 위해 사람의 명시적, 옵트인 동의가 없는 상황에서는, 누군가가 해당 목적으로 사용될 것을 합리적으로 예상할 수 있는 정보에만 기반하여 만드는 어떠한 연결도 요구합니다. 또한 사람의 명시적 옵트인 동의가 없는 경우 다음에만 기반하여 자신의 기록을 X 정체성과 매칭하려고 시도할 수 있습니다:
* **사람이 귀하에게 직접 제공한 정보.** 사전 관계가 없는 개인에 대한 기록, 즉 제3자로부터 얻은 개인에 대한 데이터는 이 기준을 충족하지 않음을 유의하세요; 및/또는
* **공개 데이터.** 이 맥락에서 "공개 데이터"란 다음을 의미합니다:
* 공개적으로 일반적으로 이용 가능한 리소스(예: 전문 협회 회원 디렉터리)에서 얻은 사람에 대한 정보
* 다음을 포함하여 공개적으로 이용 가능한 X상의 사람에 대한 정보:
* 게시물
* 계정 소개 및 공개적으로 명시된 위치를 포함한 프로필 정보
* 표시 이름 및 @핸들
## 개인정보 처리방침
**사람들이 서비스를 다운로드, 설치 또는 가입하도록 허용되기 전에 서비스의 개인정보 처리방침을 표시해야 합니다.** 최소한 다음 정보를 공개해야 합니다:
* 서비스를 사용하는 사람들로부터 수집하는 정보
* 해당 정보를 어떻게 사용하고 공유하는지(X와의 공유 포함)
* 사람들이 자신의 정보에 관한 문의 및 요청을 위해 어떻게 연락할 수 있는지
개인정보 처리방침은 모든 관련 법률과 일치해야 하며 [X의 개인정보 처리방침](https://x.com/privacy) 및 [기타 서비스 및 기업 계열사의 개인정보 처리방침](https://help.x.com/rules-and-policies/x-services-and-corporate-affiliates)보다 사람들을 덜 보호해서는 안 됩니다. 귀하 및/또는 X의 개인정보 처리방침을 준수할 수 없는 경우 X API에 대한 접근과 모든 X 콘텐츠 사용을 중단해야 합니다.
## 지역 데이터 사용
**지역 데이터의 사용은 이 정보의 민감한 특성으로 인해 추가 제한이 있습니다.** 서비스가 게시물에 위치 정보를 추가하는 경우 사람들에게 다음을 공개해야 합니다:
* 위치 정보를 추가하는 시점
* 위치 정보를 지오태그로 추가하는지 또는 주석 데이터로 추가하는지
* 위치 정보가 장소로 나열되어 있는지 또는 지리 좌표로 나열되어 있는지
애플리케이션이 사람들이 자신의 위치와 함께 게시하도록 허용하는 경우 X의 [지역 정보 가이드라인](/developer-terms/geo-guidelines)을 완전히 준수해야 합니다.
**독립형으로 위치 데이터 또는 지리 정보를 사용하는 것은 금지됩니다.** X 콘텐츠에 포함된 위치 데이터 및 기타 지리 정보를 게시물의 일부로가 아닌 다른 방식으로 저장, 집계 또는 캐시할 수 없으며 다른 사람이 그렇게 하도록 허용할 수 없습니다. 예를 들어, 시간에 따라 개인이 어디에 있었는지를 표시하기 위해 게시물에서 위치 데이터나 지리 정보를 분리할 수 없습니다. 집계된 지역 활동을 표시하는 히트 맵 및 관련 도구(예: 해시태그를 사용하는 도시의 사람 수)는 허용됩니다.
## X 비밀번호
**X 비밀번호를 저장하거나 사람들이 X 비밀번호, 계정 자격 증명 또는 개발자 애플리케이션 정보(consumer key 포함)를 귀하에게 직접 제공하도록 요청할 수 없습니다.** 서비스와 X상의 사람들을 연결하는 인증 도구로 [Sign-in with X](/fundamentals/authentication/guides/log-in-with-x)를 사용할 것을 권장합니다.
# X 개발자 PPU 계약
Source: https://docs.x.com/ko/developer-terms/ppu-agreement
X 개발자 페이 퍼 유스(Pay-Per-Use) 계약은 유료 X API 서비스에서 크레딧을 구매하고 사용하는 데 관한 조건(청구 및 사용 규칙 포함)을 다룹니다.
“결제(Pay)”를 클릭하고 유료 서비스(Paid Services)에서 사용할 크레딧을 구매하거나, 그 밖의 방법으로 라이선스 자료(Licensed Material)에 접근하거나 사용함으로써 귀하는 본 계약의 조건에 동의하는 것입니다. 크레딧은 별도로 명시되지 않는 한 만료되지 않으며, 법률에서 요구하는 경우를 제외하고는 양도 또는 환불이 불가합니다. 크레딧을 구매하려면 인증된 전화번호가 필요합니다.
본 X 개발자 PPU 계약(이하 “**계약**”)은 귀하(본 계약에서 “**귀하**”로 지칭)와 X 사이의 법적 구속력이 있는 계약이며, 유료 서비스(Paid Services, 아래 정의됨)를 포함하여 라이선스 자료(Licensed Material, 아래 정의됨)에 대한 귀하의 접근과 사용을 규율합니다.
라이선스 자료(아래 정의됨)에 접근하거나 사용하거나, 본 계약의 조건 수락 버튼 또는 유료 서비스용 크레딧 구매 버튼을 클릭함으로써 귀하는 본 계약의 조건에 구속되는 것에 동의합니다. 본문의 조건을 이해하지 못하거나 그 일부라도 수락하지 않는 경우에는 어떠한 라이선스 자료도 사용하거나 접근할 수 없습니다. 귀하가 X와 구속력 있는 계약을 체결하기 위한 법적 연령에 도달하지 않았거나, 관련 법률에 따라 라이선스 자료를 사용하거나 받는 것이 금지된 경우 라이선스 자료를 사용하거나 본 계약을 수락할 수 없습니다. 유료 서비스를 구매하고 사용하려면 다음 중 하나에 해당해야 합니다: (i) 만 18세 이상이거나 귀하가 거주하는 관할지의 법률이 정한 성년 연령 이상이거나, (ii) 해당 유료 서비스를 구매하고 사용하는 것에 대해 부모 또는 보호자의 명시적 동의를 받은 경우. 귀하가 부모 또는 법정 보호자로서 자녀(또는 귀하가 보호자인 자녀)가 유료 서비스를 구매하거나 사용하는 것을 허용하는 경우, 본 계약의 조건이 귀하에게도 적용됨에 동의하고, 본 계약을 준수하며, 해당 유료 서비스에서의 자녀의 활동 및 자녀도 본 계약의 조건을 준수하도록 할 책임이 귀하에게 있음에 동의합니다. 어떠한 경우에도 [**X 서비스 약관**](https://x.com/tos)의 “서비스 이용 자격” 섹션에 명시된 바와 같이, X 서비스 약관에서 정의된 “Services(서비스)”를 이용하려면 만 13세 이상이어야 합니다. 회사, 조직, 정부 또는 기타 법인을 대신하여 본 계약을 수락하거나 라이선스 자료를 사용하는 경우, 귀하는 해당 회사, 조직, 정부 또는 기타 법인을 본 계약에 구속시킬 권한이 있음을 진술 및 보증하며, 이 경우 본 계약에서 사용되는 “귀하” 및 “귀하의”라는 용어는 해당 법인을 지칭합니다. 본 계약의 조건에 동의하지 않는 경우, 귀하(및 귀하의 임직원)는 라이선스 자료에 접근하거나 이를 사용할 수 없습니다.
I. **정의**.
본 계약에서는 다음의 정의가 적용됩니다.
1. \*\*“크레딧(Credits)”\*\*은 유료 서비스 사용을 활성화하기 위해 귀하가 구매한 가상 단위를 의미하며, 각 API 호출 또는 작업은 가격표(Pricing Schedule)에 따라 특정 수의 크레딧을 차감합니다. 크레딧은 법률에서 요구하는 경우를 제외하고는 환불이 불가하고 양도할 수 없으며, 별도로 명시되지 않는 한 만료되지 않습니다.
2\. \*\*“개발자 사이트(Developer Site)”\*\*는 [**https://developer.x.com**](https://developer.x.com/)에 위치한 X의 개발자 사이트를 의미합니다.
3\. \*\*“Direct Message”\*\*는 X의 다이렉트 메시지 기능을 사용하여 한 사용자가 하나 이상의 특정 다른 사용자에게 X 애플리케이션에서 전송하는 비공개 메시지를 의미합니다.
4\. \*\*“지식재산권(Intellectual Property Rights)”\*\*은 전 세계의 모든 저작권, 저작인격권, 특허권, 상표권 및 그 밖의 지식재산권 또는 유사 권리(등록 또는 미등록)를 의미합니다.
5\. \*\*“라이선스 자료(Licensed Material)”\*\*는 개별적으로 또는 총체적으로 X API 및 X 콘텐츠(X Content)를 의미합니다.
6\. \*\*“유료 서비스(Paid Service(s))”\*\*는 X로부터 구매한 크레딧을 차감하는 대가로 귀하가 접근할 수 있는 라이선스 자료의 기능(feature) 또는 기능성(functionality)을 의미하며, 당사 가격 페이지에 상세히 기재된 호출 및 기능 사용에 따라 귀하의 계정에서 차감됩니다. 본 계약에서 별도로 정하지 않는 한, “라이선스 자료”에 대한 모든 언급은 유료 서비스를 포함하는 것으로 간주됩니다.
7\. \*\*“결제 포털(Payment Portal)”\*\*은 귀하의 라이선스 자료 사용을 옵트인하고, 유료 서비스용 크레딧 구매를 관리하며, 유료 서비스용 결제 수단을 관리하고, “자동 재충전(Auto-Recharge)”(섹션 VII.F 참조)을 활성화하며, 계정 정보를 업데이트할 수 있도록 귀하에게 제공되는 온라인 포털을 의미합니다.
8\. \*\*“Services(서비스)”\*\*는 X 콘텐츠를 표시하거나 라이선스 자료를 사용하는 귀하의 서비스, 웹사이트, 애플리케이션 및 기타 제공물(연구 포함)을 의미합니다.
9\. \*\*“Post”\*\*는 X 애플리케이션을 통해 배포되는 단문 형식의 텍스트 및 멀티미디어 기반 메시지를 의미합니다.
10\. \*\*“가격표(Pricing Schedule)”\*\*는 API 호출 또는 작업당 현재 가격 목록을 의미하며, [https://developer.x.com/#pricing](https://developer.x.com/#pricing)에서 확인할 수 있습니다.
11\. \*\*“X”\*\*는 (a) 귀하의 주된 사업장이 유럽연합, EFTA 회원국 및 영국 이외에 있는 경우 X Corp. (865 FM 1209, Building 2, Bastrop, TX 78602, USA), 또는 (b) 귀하의 주된 사업장이 유럽연합, EFTA 회원국 또는 영국에 있는 경우 X Internet Unlimited Company (One Cumberland Place, Fenian Street, Dublin 2, D02 AX07, Ireland)를 의미합니다.
12\. \*\*“X API”\*\*는 X 애플리케이션 프로그래밍 인터페이스(각각 “API”), 소프트웨어 개발 키트(각각 “SDK”) 및 X가 개발자 사이트를 통해 제공하는 관련 도구, 문서, 데이터, 기술, 코드 및 기타 자료를 의미합니다.
13\. \*\*“X 애플리케이션(X Applications)”\*\*은 일반적으로 “X”라고 불리는 X의 실시간 정보 서비스를 의미하며, 여기에는 현재 X가 자사 웹사이트 및 X가 소유·운영·통제하는 모바일 애플리케이션, 소셜 플러그인 및 애플리케이션 프로그래밍 인터페이스에서 제공하는 서비스가 포함됩니다.
14\. \*\*“X 콘텐츠(X Content)”\*\*는 Post, 각 Post에 대해 생성된 고유 식별 번호, X 엔드 유저 프로필 정보 및 X API 또는 X가 승인한 기타 수단을 통해 귀하에게 제공되는 기타 모든 데이터와 정보, 그리고 그 사본 및 파생 저작물을 의미합니다.
15\. \*\*“X 마크(X Marks)”\*\*는 본 계약에 따른 사용만을 위해 X가 개발자 사이트 등을 통해 귀하에게 제공하는 X의 명칭, 상표 및 로고를 의미합니다.
16\. \*\*“Users(사용자)”\*\*는 귀하의 Services의 방문자, 사용자 또는 고객을 의미합니다.
**II. X API 및 X 콘텐츠.**
**A. X가 부여하는 라이선스.** 귀하가 본 계약 및 관련 편입 개발자 약관(Incorporated Developer Terms, 아래 정의됨)의 조건을 준수하는 것을 조건으로, X는 이로써 귀하에게 다음의 목적만을 위한 비독점적, 무상, 양도 불가, 재실시 불가, 취소 가능한 라이선스를 부여합니다.
1\. X가 명시적으로 승인한 바에 따라, X API를 사용하여 X 콘텐츠를 귀하의 Services에 통합하거나 X 콘텐츠에 대한 분석을 수행할 것;
2\. 본 계약에서 허용하는 범위 내에서, 합리적인 양의 X 콘텐츠를 복사하여 귀하의 Services 및 이를 통해 Users에게 표시할 것;
3\. X 콘텐츠를 귀하의 Services에서 표시하기 위한 포맷팅 목적으로만 수정할 것; 및
4\. 본 계약에 규정된 바에 따라 X 애플리케이션이 X 콘텐츠의 출처임을 표시하기 위해 X 마크를 사용하고 표시할 것.
**B. X에게 부여하는 라이선스.** 귀하는 이로써 X에게, 귀하가 [**임베디드 Post 또는 임베디드 타임라인**](https://publish.x.com)을 사용하여 X 콘텐츠를 표시하는 모든 웹페이지 또는 애플리케이션에 대해, 웹 스파이더 및/또는 크롤러를 포함한 어떠한 수단으로든 접근, 색인화 및 캐싱할 수 있는 비독점적, 무상, 양도 불가, 재실시 불가, 취소 가능한 라이선스를 부여합니다.
**C. 편입 약관.** 라이선스 자료에 대한 귀하의 접근 및 사용은 다음의 추가 약관 및 정책(총칭하여 “**편입 개발자 약관(Incorporated Developer Terms)**”)의 적용을 받으며, 귀하는 이를 준수해야 합니다.
1\. [**X 개발자 정책**](https://docs.x.com/developer-terms/policy);
2\. [**API 제한 사용 규칙**](https://docs.x.com/developer-terms/restricted-use-cases);
3\. [**X 규칙**](https://help.x.com/rules-and-policies/x-rules);
4\. 귀하의 X 콘텐츠 표시와 관련하여, [**표시 요건**](https://docs.x.com/developer-terms/display-requirements);
5\. 귀하의 X 마크 사용 및 표시와 관련하여, [**X 브랜드 가이드라인**](https://about.x.com/who-we-are/brand-toolkit); 및
6\. 귀하의 계정에서 자동화된 작업을 수행하는 것과 관련하여, [**자동화 규칙**](https://help.x.com/rules-and-policies/x-automation).
**III. 사용 제한 사항.**
**A. 리버스 엔지니어링 및 기타 제한 사항.** 귀하는 다음을 하거나 시도해서는 안 되며, 타인이 그렇게 하도록 허용해서도 안 됩니다: (a) X API를 리버스 엔지니어링, 디컴파일, 디스어셈블 또는 번역하거나, 그 밖의 방법으로 X API 또는 그 일부의 기반이 되는 소스 코드, 영업 비밀 또는 노하우를 도출하려는 시도; (b) X API의 기능 또는 X API의 모니터링 메커니즘을 방해, 수정, 중단 또는 비활성화하는 행위; (c) 라이선스 자료를 사용 또는 접근하여 X 애플리케이션과 대체 가능하거나 유사한 서비스 또는 제품을 만들거나 만들려는 시도; (d) 본 계약에서 명시적으로 허용된 경우를 제외하고 라이선스 자료의 전부 또는 일부를 제3자에게 판매, 임대, 대여, 재실시, 배포, 재배포, 신디케이션, 파생물 창작, 양도 또는 그 밖의 방식으로 이전하거나 접근을 제공하는 행위; (e) 서비스 뷰로(service bureau), 렌탈 또는 관리 서비스 기반으로 X API 사용을 제공하거나, 다른 개인 또는 단체가 X API로 링크를 만들거나 다른 서버 또는 무선/인터넷 기반 장치에서 X API를 “프레이밍(frame)” 또는 “미러링(mirror)”하도록 허용하거나, 그 밖의 방법으로 X API의 토큰, 키, 비밀번호 또는 기타 로그인 자격 증명을 제3자에게 제공하는 행위; (f) 라이선스 자료를 불법, 무단 또는 기타 부적절한 목적으로 사용하는 행위; (g) 라이선스 자료를 사용하여 개별 X 사용자의 비공개 정보를 도출하거나 획득하는 행위; (h) X 애플리케이션, X API 또는 그 안에 포함된 X 콘텐츠의 무결성 또는 성능을 방해하거나 중단시키는 행위; (i) X 콘텐츠의 소유권 고지 또는 마크를 제거 또는 변경하는 행위; (j) X 애플리케이션, X API, X 콘텐츠 또는 관련 시스템 또는 네트워크에 대한 무단 접근을 시도하는 행위; (k) X API 또는 X 콘텐츠를 사용하여 파운데이션 모델(foundation model) 또는 프론티어 모델(frontier model)을 파인 튜닝(fine-tune) 또는 학습(train)시키는 행위; 또는 (l) X 콘텐츠를 단독으로 또는 제3자 데이터와 결합하여, 또는 그로부터의 파생 분석을 사용하여, X 애플리케이션 외부에서 사용자를 대상으로 광고를 타기팅하거나 제공하는 행위.
**B. 상업적 사용 제한.** 귀하의 Services가 ‘비상업적(non-commercial)’으로 지정된 경우, 귀하는 라이선스 자료를 상업적 사용(Commercial Use, 아래 정의됨)해서는 안 됩니다. 상업적 사용 제한은 공식 등록된 비영리 단체 또는 NGO에는 적용되지 않을 수 있습니다. “상업적 사용”이란 다음을 의미합니다: (a) 사업체(즉, 제품 또는 서비스를 통해 수익을 창출하는 것이 주된 목적인 단체)에 의한 또는 사업체를 위한 라이선스 자료의 사용 또는 X API에 대한 접근, 또는 (b) 수익화되는 제품 또는 서비스의 일부로서의 사용(예: 웹사이트 광고, 라이선스 수수료, 인앱 프로모션, 스폰서십).
**C. 모니터링 또는 측정 금지.** 이와 상반된 어떠한 규정에도 불구하고, 귀하는 다음 정보를 비상업적, 내부 목적(예: Services의 기능 개선)으로만 사용할 수 있습니다: (a) X 애플리케이션 사용자 메트릭 집계(예: X 애플리케이션의 활성 사용자 또는 계정 수); (b) X 애플리케이션의 응답성; 및 (c) X API의 분석, 사용 또는 성능에 관한 결과, 사용 통계, 데이터 또는 기타 정보(집계 형태 또는 기타 형태). 이러한 모든 정보는 기밀 정보(Confidential Information, 아래 정의됨)입니다.
**D. 요청 속도 제한(Rate Limits).** 귀하는 X API의 접근, 호출 또는 사용에 대한 제한(“Rate Limits”)을 초과하거나 우회하려고 시도해서는 안 되며, 합리적인 요청 볼륨을 초과하거나 과도하거나 남용적인 사용을 구성하거나 그 밖의 방식으로 본 계약을 준수하지 않는 방식으로 X API를 사용해서도 안 됩니다. API 호출 및 요청은 [https://developer.x.com/#pricing](https://developer.x.com/#pricing)에서 확인할 수 있는 가격표(Pricing Schedule)에 지정된 대로 귀하의 잔액에서 크레딧을 차감합니다. 호출에 대해 귀하의 크레딧 잔액이 부족한 경우, 해당 요청에 대한 차감을 허용하기에 충분한 크레딧 잔액이 될 때까지 요청은 거부됩니다. 귀하가 Rate Limits, X API 사용을 제한하는 통제를 초과하거나 우회하려고 시도했다고 X가 합리적으로 판단하거나, 그 밖의 방식으로 라이선스 자료를 본 계약을 위반하여 사용하고 있는 경우, 라이선스 자료를 사용할 수 있는 귀하의 능력은 일시적으로 정지되거나 영구적으로 차단될 수 있습니다. X는 라이선스 자료 및 X 애플리케이션을 개선하고 귀하가 본 계약 및 편입 개발자 약관을 준수하는지 확인하기 위해 귀하의 X API 사용을 모니터링할 수 있습니다. 귀하는 귀하의 사용과 관련된 추가 정보에 대한 X의 요청을 준수하는 것에 동의합니다. X는 언제든지 귀하의 라이선스 자료 사용을 검토할 수 있습니다. X가 X API에 대한 접근을 허가하거나 라이선스 자료 사용을 허용하는 것은 귀하의 사용에 대한 승인이나, 본 계약 및 X 정책을 준수하는 사용을 요구할 X의 권리에 대한 포기 또는 제한으로 간주되지 않습니다. 지급된 금액은 환불되지 않으나, X는 재량에 따라 사용되지 않은 크레딧이 본 계약을 준수하는 사용을 위해 이용되도록 허용할 수 있습니다.
**E. 위치 데이터.** 귀하는 X 콘텐츠에 포함된 위치 데이터 및 기타 지리 정보를, 이러한 데이터가 부착된 X 콘텐츠와 함께 사용되는 경우를 제외하고는 집계, 캐싱 또는 저장해서는 안 되며, 타인이 이를 하도록 허용해서도 안 됩니다. 위치 데이터 및 지리 정보는 X 콘텐츠에 태그된 위치를 식별하기 위한 용도로만 사용할 수 있습니다.
**F. X 마크의 사용.** 귀하는 X 마크를 등록된 회사명, 로고 또는 서비스나 제품 이름에 포함해서는 안 됩니다. 귀하는 X 마크의 파생물을 만들거나 X의 보증, 후원 또는 X와의 연관성을 나타내거나 합리적으로 암시하는 방식으로 X 마크를 사용해서는 안 됩니다. X 마크의 모든 사용 및 그 사용에서 발생하는 모든 신용(goodwill)은 X의 이익으로 귀속됩니다. 귀하는 라이선스 자료에 있는 소유권 고지 또는 X 마크를 제거하거나 변경해서는 안 됩니다.
**G. 보안.** 귀하는 X API의 보안을 유지해야 하며, X API의 토큰, 키, 비밀번호 또는 기타 로그인 자격 증명을 제3자에게 제공해서는 안 됩니다. 귀하는 바이러스, 웜 또는 기타 유해한 코드나 자료에 의한 접근을 포함하여 X API의 기능 및 기능성에 대한 무단 접근 또는 사용을 방지하기 위해 업계 표준의 보안 조치를 사용해야 합니다. 귀하는 그러한 데이터에 대해 업계 표준의 조직적·기술적 보호 조치를 사용하여, 그리고 귀하가 저장하는 유사한 데이터의 보안 유지에 사용하는 것과 다르지 않은 수준의 주의를 기울여 X 콘텐츠를 무단 접근으로부터 기밀 유지 및 안전하게 유지해야 합니다. 귀하는 라이선스 자료와 관련된 보안 침해 또는 잠재적 취약점을 알거나 의심하는 경우 즉시 X에 통지하고, 조사에 협의·협력하며, 필요한 통지에 협조하고, X가 합리적으로 요청하는 정보를 제공해야 합니다. 귀하는 귀하의 라이선스 자료 접근으로 인해 발생한 그러한 침해 또는 잠재적 취약점을 신속하게 시정해야 합니다.
**H. 디지털 서비스법(Digital Services Act).** 본 계약의 반대되는 어떠한 규정에도 불구하고, 귀하가 디지털 서비스법(Digital Services Act, Regulation (EU) 2022/2065)(“DSA”) 제40조에 기술된 절차에 따라 라이선스 자료에 대한 접근을 제공받는 경우, 라이선스 자료에 대한 귀하의 접근 및 사용은 유럽연합 내 시스템적 위험의 탐지, 식별 및 이해에 기여하는 연구를 수행하는 목적으로만 제한되며, X가 DSA에 따른 의무를 준수하는 데 필요한 범위 내에서만 허용됩니다. 이러한 라이선스 자료의 사용은 본 계약 III(B)조에 기술된 대로 비상업적입니다. 귀하는 X API를 통해 검색한 라이선스 자료(그 파생물 포함)를 승인된 신청서에 명시된 사람 이외의 개인 또는 단체에 공개, 복제, 라이선스 또는 그 밖의 방법으로 배포해서는 안 됩니다. 다만 (i) 제40조에 기술된 “검증된 연구자(vetted researcher)” 지위 및 절차에 따라 DSA가 구체적으로 허용하는 디지털 서비스 조정관(Digital Services Coordinator) 또는 기타 당사자에게 정보가 공개되는 경우, 또는 (ii) 법률상 공개가 요구되는 경우는 예외입니다.
**I. 토큰.** X는 X 애플리케이션의 기능 또는 기능성에 대한 접근 및 사용을 가능하게 하는 토큰을 포함하되 이에 국한되지 않고, 귀하에게 제공하는 토큰의 수를 제한할 수 있습니다.
**J. 계약상의 사용 수준.** X는 언제든지 본 계약에 따른 라이선스 자료의 귀하의 사용을 검토할 수 있으며, 귀하의 사용을 정지하거나 종료하고 X가 라이선스 자료의 계속 사용을 검토할 수 있도록 귀하에게 엔터프라이즈(Enterprise) 접근 신청서를 제출할 것을 요구할 수 있습니다([**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction) 참조).
**K. 아이프레임(I-Framing) 금지:** 귀하는 어떠한 경우에도 라이선스 자료, X 콘텐츠, X API 또는 X 애플리케이션의 요소를 귀하의 Services 또는 기타 플랫폼에서 아이프레임(iframe), 인라인 프레임 또는 이와 유사한 임베드 메커니즘 내에 임베드, 표시 또는 다른 방식으로 통합해서는 안 됩니다. 이 금지 사항은 절대적이며, 표시, 통합 또는 재배포 목적으로 X 콘텐츠를 프레이밍하려는 시도를 포함하되 이에 국한되지 않습니다. 본 조항 위반은 섹션 VII.I에 기술된 대로 귀하의 개발자 계약 및 라이선스 자료(예: X API, X 데이터 라이선스, 개발자 콘솔)에 대한 접근의 즉시 종료로 이어질 수 있습니다.
**L. 셀프 서비스 사용.** 페이 퍼 유스(Pay-Per-Use), Basic 및 Pro 플랜([developer.x.com](https://developer.x.com)에 기술된 대로)은 취미 개발자, 상업적 프로토타이핑, 초기 개발, 초기 단계의 X 제품 통합 및 제한된 수의 엔드 유저를 지원하는 애플리케이션을 위해 설계되었습니다. 귀하가 이 범위를 벗어나서 X API를 사용하는 경우, 엔터프라이즈(Enterprise) 플랜([developer.x.com](https://developer.x.com)에 기술된 대로)을 신청하거나 이미 구독해야 합니다.
**M. 상업적 사용:** 귀하가 취미 프로젝트, 상업적 프로토타이핑, 초기 개발, 초기 단계의 X 제품 통합 또는 제한된 수의 엔드 유저를 위한 애플리케이션의 범위를 벗어나서 X API를 사용하는 경우, 엔터프라이즈(Enterprise) 플랜(developer.x.com에 기술된 대로)을 신청하거나 이미 구독해야 합니다.
**IV. 업데이트 및 삭제.**
**A. 업데이트.** X는 라이선스 자료의 전부 또는 일부의 기능 또는 기능성을 수시로 업데이트, 수정 또는 중단할 수 있습니다(각각의 경우 “업데이트”). 귀하는 라이선스 자료의 최신 버전을 구현하고 사용해야 하며, 업데이트의 결과로 필요한 귀하의 Services에 대한 변경 사항을 귀하의 단독 비용으로 수행해야 합니다. 업데이트는 귀하의 Services가 X API에 접근하거나 통신하는 방식 또는 X 콘텐츠를 표시하는 방식에 부정적인 영향을 미칠 수 있습니다. X는 업데이트로 인해 발생하는 어떠한 종류의 손해에 대해서도 책임을 지지 않습니다.
**B. 삭제.** X 콘텐츠가 삭제되거나, 보호 상태(protected status)를 얻거나, 그 밖의 방법으로 X 애플리케이션에서 정지, 보류, 수정 또는 삭제되는 경우(위치 정보의 삭제 포함), 귀하는 X 또는 X 사용자가 자신의 X 콘텐츠에 대해 서면으로 요청한 후 가능한 한 빠르게, 어떠한 경우에도 24시간 이내에 해당 X 콘텐츠를 삭제 또는 수정(해당하는 경우)하기 위해 모든 합리적인 노력을 기울여야 합니다. 다만 법률 또는 규정으로 금지되는 경우 및 X의 명시적 서면 허가가 있는 경우는 예외입니다.
**V. 소유권, 베타 및 피드백.**
**A. 소유권.** 본 계약에 명시적으로 달리 규정되지 않는 한, 어느 당사자도 상대방이 소유하거나 라이선스를 부여받은 지식재산권에 대한 어떠한 권리, 권원 또는 이익도 취득하지 않습니다. 라이선스 자료는 라이선스가 부여되는 것이지 판매되는 것이 아니며, X(또는 해당하는 경우 라이선서 또는 X 애플리케이션 사용자)는 본 계약에서 명시적으로 부여되지 않은 모든 지식재산권을 포함한 모든 권리를 보유하고 유보합니다. 귀하는 X의 소유권에 반하는 어떠한 행위도 해서는 안 됩니다. 여기에는 X의 X 마크 소유권에 대한 이의 제기, 본 계약에서 부여된 라이선스의 유효성에 대한 이의 제기, 또는 본 계약에서 구체적으로 허가된 경우를 제외하고 X 마크를 복사 또는 활용하는 행위가 포함되지만 이에 국한되지 않습니다. 법률의 작용 또는 그 밖의 방법으로 귀하가 X 마크 또는 혼동을 일으킬 정도로 유사한 마크에 대한 권리를 취득하는 경우, 귀하는 X에게 아무런 비용 없이 즉시 그 권리를 X에게 양도해야 합니다.
**B. 베타.** X는 수시로 귀하에게 일반적으로 제공되지 않는 알파, 베타, 연구, 파일럿, 마케팅 서비스 또는 기타 프로그램(각각 “베타”)에 대한 사전 접근을 제공할 수 있습니다. 베타는 기밀 정보로 간주됩니다. 귀하의 베타 참여는 귀하 자신의 책임으로 이루어지며, 추가 요건의 적용을 받을 수 있고, X가 기존 또는 잠재적인 프로그램, 제품 및/또는 도구를 연구, 분석 및 검증하는 데 도움이 될 수 있습니다.
**C. 피드백.** X는 귀하가 X, 라이선스 자료, 베타 또는 X의 기타 제품이나 서비스와 관련하여 X에 제공한 모든 피드백, 코멘트 또는 제안(“피드백”)을 귀하 또는 제3자에 대한 어떠한 보상이나 의무 없이 어떠한 방식으로든 자유롭게 사용할 수 있으며, 피드백은 기밀 정보로 간주됩니다. 귀하는 이로써 피드백에 대한 모든 권리, 권원 및 이익을 X에게 취소 불가능하게 양도합니다.
**VI. 기밀 유지.**
귀하는 라이선스 자료와 관련된 비공개 정보, 소프트웨어 및 사양(“기밀 정보”)에 대한 접근이 제공될 수 있습니다. 귀하는 본 계약에 따른 귀하의 권리를 행사하는 데 필요한 경우에만 기밀 정보를 사용할 수 있습니다. 귀하는 X의 사전 서면 동의 없이는 기밀 정보를 제3자에게 공개해서는 안 됩니다. 귀하는 유사한 성격의 자신의 기밀 정보를 보호하기 위해 사용하는 것과 동일한 방식으로, 그리고 어떠한 경우에도 합리적인 정도의 주의보다 낮지 않은 수준으로 기밀 정보를 무단 사용, 접근 또는 공개로부터 보호해야 합니다.
**VII. 기간; 크레딧 구매 조건; 크레딧 차감; 정지 및 종료.**
**A. 기간.** 본 계약의 기간은 (i) 귀하가 본문의 조건을 수락한 날 또는 (ii) 귀하가 라이선스 자료 중 어느 하나에 접근하거나 사용하기 시작한 날 중 더 이른 날에 시작되어, 아래에서 기술된 대로 조기 종료되지 않는 한 귀하가 라이선스 자료에 대한 접근 및 사용을 중단할 때까지 계속됩니다.
**B. 크레딧 구매 조건.** 라이선스 자료의 일부로 제공되는 유료 서비스는 [https://developer.x.com/#pricing](https://developer.x.com/#pricing), 개발자 사이트 및 결제 포털에 기술된 대로 X API 사용을 포함한 기능, 혜택 또는 서비스 사용에 따라 차감되는 크레딧 구매를 통해 제공됩니다. 귀하가 유료 서비스를 구매하는 경우, 결제 포털을 통해 해당 요금을 선불로 지급함으로써 먼저 크레딧을 구매합니다. 귀하의 크레딧 잔액은 구매 후 업데이트되며, 유료 서비스를 사용함에 따라 차감됩니다. 유료 서비스에 대한 접근을 활성화하기 위해 필요한 경우 추가 크레딧을 구매해야 합니다. 섹션 VII.D에 상세히 설명된 선택적 “자동 재충전(Auto-Recharge)” 기능을 활성화하지 않는 한, 크레딧 구매는 반복되지 않습니다. 귀하가 결제 포털을 통해 크레딧을 구매하는 경우, 귀하는 본문의 조건에 명시적으로 동의하고 결제를 승인합니다. X는 잔액이 낮을 때 알림을 제공할 수 있습니다. 크레딧 가격 및 차감율은 가격표에 명시된 대로 수시로 변경될 수 있습니다. X는 가격의 실질적 변경에 대해 합리적인 사전 통지를 제공하며, 이러한 통지는 개발자 사이트 또는 결제 포털을 통해 제공될 수 있습니다. 가격 변경은 향후의 구매 및 차감에 적용됩니다. 귀하가 가격 변경에 동의하지 않는 경우, 크레딧 구매 및 유료 서비스 사용을 중단할 수 있습니다. 크레딧은 별도로 명시되지 않는 한 만료되지 않으며, 법률에서 요구하는 경우를 제외하고 양도 또는 환불이 불가합니다.
**C. 크레딧 차감:** 유료 서비스에 대한 접근에는 귀하의 계정에 충분한 크레딧이 있어야 합니다. 가격표에 명시된 각 API 호출, 요청 또는 기타 기능이나 서비스 사용은 가격표에 명시된 비율에 따라 귀하의 잔액에서 크레딧을 차감합니다. 차감율은 다를 수 있으며, 가격표는 변경될 수 있습니다. X는 각 호출, 요청 또는 가격표에 명시된 기타 기능이나 서비스 사용 시점에 크레딧을 차감하고, 잔액이 부족한 유료 서비스는 거부하는 것을 목표로 합니다. 그 경우, 유료 서비스를 활성화하기 위해 추가 크레딧을 구매해야 합니다. 귀하는 음의 크레딧 잔액을 유지할 수 없습니다. 유료 서비스에 대한 접근을 유지하는 데 도움이 되도록 크레딧 잔액을 모니터링하는 것은 귀하의 책임입니다.
**D. 사용 분쟁:** 크레딧 차감에 오류가 있다고 판단되는 경우, 귀하는 분쟁이 있는 차감으로부터 30일 이내에 [billing support](https://docs.x.com/forms/billing-support)를 통해 X에 통지해야 합니다. X는 조사할 것이며, 오류가 확인되면 그에 따라 귀하의 크레딧 잔액을 조정합니다. 조정은 X의 단독 재량에 따르며, 본 계약의 적용을 받습니다.
**E. 결제 조건.** X는 유료 서비스, 기기, 운영 체제, 지리적 위치 또는 기타 요소에 따라 다른 결제 옵션을 제공할 수 있으며, 이는 수시로 업데이트될 수 있습니다. 이러한 결제 옵션에는 제3자 결제 처리자(“결제 처리자(Payment Processor)”)를 사용한 웹 결제가 포함될 수 있습니다. 유료 서비스에 접근하는 경우, 귀하는 다음에 동의합니다: (i) 크레딧에 대해 게시된 가격과 함께 적용되는 세금, 부가금, 신용카드 수수료, 은행 수수료, 외환 거래 수수료, 외화 환전 수수료 및 환율 변동과 관련된 추가 금액을 지급할 것; (ii) 주어진 결제 방법 사용과 관련하여 결제 처리자가 부과하는 관련 서비스 약관, 개인정보 처리방침 또는 기타 법적 계약이나 제한(추가 연령 제한 포함)을 준수할 것. 수수료는 크레딧 구매 시점에 청구됩니다. 크레딧 잔액을 모니터링하고 은행, 신용카드, 직불카드 및/또는 기타 결제 정보가 항상 최신이고 완전하며 정확하게 유지되도록 하는 것은 귀하의 책임입니다. 결제 처리자를 통해 유료 서비스에 대한 결제를 하는 경우, X는 결제가 이루어진 시점, 구매한 플랫폼 및 기타 정보와 같은 거래에 관한 정보를 받을 수 있습니다. X는 결제 처리자, 귀하의 은행, 귀하의 신용카드 회사 또는 어떠한 결제 네트워크의 오류나 지연에 대해서도 책임을 지지 않습니다. X에 대한 모든 결제는 본 계약에서 명시적으로 달리 규정되거나 법률에서 요구하는 경우를 제외하고는 환불되지 않습니다.
**F. 선택적 자동 재충전 기능.** 귀하는 개발자 콘솔을 통해 “자동 재충전(auto-recharge)” 기능을 옵트인하여, 크레딧 잔액이 자동 재충전 도구에서 설정한 임계값 아래로 떨어질 때 X가 귀하의 저장된 결제 수단에 사용자가 선택한 금액을 자동으로 청구하도록 승인할 수 있으며, 청구액에는 섹션 VII.E에 따른 해당 금액에 대한 관련 세금 및 수수료가 포함됩니다. 귀하는 결제 포털을 통해 언제든지 이 기능을 수정하거나 비활성화할 수 있으며, 이를 활성화함으로써 임계값이 충족될 때마다 X가 제3자 결제 처리자를 통해 선택된 금액을 청구하는 것에 동의합니다. 다만 실패한 청구(예: 유효하지 않은 결제 수단으로 인한)는 크레딧 추가를 방해합니다. 자동 재충전을 활성화한다고 해서 유료 서비스에 대한 중단 없는 접근이 보장되지는 않습니다. 낮은 잔액이나 자동 재충전 이벤트에 대해 X가 제공할 수 있는 알림과 관계없이 귀하는 여전히 크레딧 잔액을 모니터링할 책임이 있으며, 자동 재충전 청구는 법률에서 요구하는 경우를 제외하고 환불되지 않습니다.
**D. 세금 및 수수료.** 모든 요금은 거래, 라이선스 자료의 제공 또는 X 콘텐츠의 제공에 대해 현재 시행 중이거나 향후 제정 또는 부과되는 모든 세금 및 유사 수수료(판매세, 사용세 또는 부가가치세, 재화 및 서비스세, 소비세, 관세, 관세율 또는 유사한 부과금 포함)를 제외합니다. 이러한 세금에는 VAT, GST, 판매세, 원천징수세 및 기타 관련 세금이 포함될 수 있지만 이에 국한되지 않으며, X의 순소득에 근거하는 세금은 제외됩니다. 귀하는 이러한 모든 세금, 관세 및 부과금과 그러한 금액의 지급으로 인해 발생하는 관련 벌금 및 이자의 지급에 대해 책임이 있습니다. 또한, 특정 관할지에서 X가 부담하는 디지털 서비스세(“DST”) 또는 유사한 관할지 특유의 세금 또는 규제 수수료와 관련된 비용을 회수하기 위해 부가금이 청구될 수 있습니다. 이 부가금은 해당하는 경우 청구서에 별도 항목으로 표시되며, X의 단독 재량으로 결정된 대로 적용 요금의 백분율로 계산됩니다. X는 세율 또는 수수료율 인상이나 관련 관리 비용에 대응하여 사전 통지 없이 언제든지 이 부가금을 조정할 수 있습니다. 귀하의 위치에 따라 X는 귀하의 유료 서비스 구매로 인해 발생하는 거래세와 관련된 정보를 수집하고 보고할 책임이 있을 수 있습니다. 귀하는 X가 세금 징수 및 보고 의무를 이행하기 위해 귀하의 계정 및 개인 정보를 관련 세무 당국에 제공하도록 허가합니다.
**E. 환불 및 유료 서비스 중단.** 귀하는 언제든지 추가 API 호출을 하지 않음으로써 유료 서비스 사용을 중단할 수 있습니다. 미사용 크레딧은 환불 및 양도가 불가하며, 법률에서 요구하는 경우를 제외하고는 구매되거나 사용된 크레딧에 대한 환불이 없습니다. 크레딧 구매는 선불이며 환불 불가(법률에서 요구하는 경우 제외)입니다. 귀하는 아래의 철회권과 같이 관련 법률(예: 아래 철회권)에 따라서만 미사용 크레딧에 대한 환불을 요청할 수 있습니다. 아래에 규정된 대로 법률에 따라 철회 권리가 있지 않는 한 모든 거래는 최종적입니다.
**1. EU 또는 영국 거주 사용자의 철회권 및 환불.** 귀하는 구매일로부터 14일 이내(“철회 기간”)에 어떠한 이유도 제시하지 않고 크레딧 구매를 철회할 법적 권리가 있습니다. 이 권리를 행사하려면 철회 기간이 만료되기 전에 [billing support](https://docs.x.com/forms/billing-support)로 명확한 철회 진술서를 제출하여 철회 결정을 X에 알려야 합니다. 귀하가 철회 기간 내에 철회하고 크레딧을 사용하지 않은 경우, X는 귀하가 명시적으로 달리 동의하지 않는 한, 철회 통지를 받은 후 14일 이내에 구매에 사용된 것과 동일한 결제 방법을 사용하여 관련 세금 또는 수수료를 포함한 크레딧 구매 대금 전액을 환불합니다.
다만 귀하가 철회 기간 동안 크레딧을 사용하는 경우(예: API 호출 또는 요청을 함으로써), 귀하의 사전 명시적 동의와 그러한 사용 시 철회권이 상실된다는 인지에 따라 유료 서비스가 개시된 것이므로 철회권을 포기한다는 점을 귀하는 명시적으로 인정하고 이에 동의합니다. 철회 기간 동안 구매한 크레딧의 일부만 사용한 후 철회권을 행사하는 경우, X는 [https://developer.x.com/#pricing](https://developer.x.com/#pricing)에서 확인할 수 있는 가격표에 따라 계산된 미사용 크레딧에 해당하는 금액을 환불합니다.
**2. 대만 거주 사용자의 철회권 부재.** 귀하가 대만에 거주하는 소비자인 경우, 소비자 보호법에 따라 크레딧 구매에 대해 7일의 철회 기간이 부여될 수 있으며, 크레딧을 사용한 경우에는 철회권이 상실됩니다. 이 권리를 행사하려면 구매일로부터 7일 이내에 [billing support](https://docs.x.com/forms/billing-support)로 X에 통지해야 합니다. 미사용 크레딧에 대한 환불은 관련 법률에 따라 처리됩니다.
**F. 크레딧은 X 계정 간에 양도 불가.** 각 크레딧 구매는 단일 X 계정에 적용됩니다. 즉, 귀하의 구매는 크레딧을 구매할 때 사용한 계정에만 적용되며, 귀하가 접근 또는 통제할 수 있는 다른 계정에는 적용되지 않습니다. 여러 계정을 보유하거나 통제하고 각 계정에서 유료 서비스에 대한 접근을 원하는 경우, 각 계정에서 필요한 크레딧을 개별적으로 구매해야 합니다. 귀하는 다른 사람이 귀하의 X 계정을 사용하여 그 사람이 주문하지 않은 라이선스 자료에 접근하도록 허용해서는 안 됩니다. 미국 재무부 해외자산통제국(Office of Foreign Assets Control)이 시행하는 제재 또는 기타 적용 가능한 제재 당국이 시행하는 제재를 포함하되 이에 국한되지 않는 경제 제재에 따라 미국인이 거래하도록 허용되지 않는 사람(“금지 대상자(Prohibited Person)”)인 경우, 크레딧을 구매하거나 라이선스 자료를 사용할 수 없습니다. 여기에는 다음 국가 및 지역에 소재하거나 그 시민이거나 통상적으로 거주하는 사람이 포함되지만 이에 국한되지 않습니다: 쿠바, 이란, 우크라이나의 크림 지역, 북한 및 시리아. 귀하는 자신이 금지 대상자가 아님을 진술 및 보증합니다.
**G. 제한 사항 및 의무.** 귀하는 귀하의 국가에서 라이선스 자료를 사용할 법적 자격이 있고 X가 해당 크레딧 구매, 유료 서비스 또는 라이선스 자료를 지원하는 국가에 거주하는 경우에만 크레딧을 구매·사용하고 라이선스 자료를 사용할 수 있습니다. X는 재량에 따라 특정 국가에서 라이선스 자료에 접근하거나 크레딧을 구매할 수 있는 능력을 제한할 수 있습니다. X는 수시로 지원되는 국가 목록을 수정할 권리를 보유합니다. X는 크레딧의 판매 또는 유료 서비스에 대한 접근을 거부하거나, 단독 재량으로 유료 서비스의 판매 또는 사용, 또는 라이선스 자료의 사용을 취소 또는 중단할 권리를 보유합니다.
**H. 정지.** X는 다음의 경우 통지 없이 즉시 귀하의 라이선스 자료에 대한 사용 및 접근을 정지할 수 있습니다: (a) X가 합리적으로 다음과 같이 판단하는 경우, (i) 귀하의 라이선스 자료 사용이 라이선스 자료에 손상을 입히거나 과도한 부담을 주는 경우, (ii) 귀하가 본 계약을 위반한 경우, (iii) 귀하가 X에 대해 위험 또는 법적 노출 가능성을 초래하는 경우, (iv) X의 귀하에 대한 라이선스 자료 제공이 더 이상 상업적으로 실행 가능하지 않은 경우; (b) 장기간의 비활성 상태; (c) 관할 법원, 규제 당국 또는 법 집행 기관으로부터 그렇게 하도록 요청 또는 지시를 받은 경우; 또는 (d) 유료 서비스에 대한 미지급의 경우. X는 그러한 정지로 인해 발생하는 어떠한 종류의 손해에 대해서도 책임을 지지 않습니다.
**I. 종료.** X는 X의 단독 재량으로 어떠한 이유로든 본 계약을 종료할 수 있습니다. X의 그러한 조기 종료는 즉시 효력을 발생합니다. 귀하가 본 계약의 조건을 위반하는 경우, X는 귀하에 대한 통지 즉시 정당한 사유로 본 계약을 종료할 수 있으며, 귀하는 어떠한 크레딧에 대해서도 환불을 받지 않습니다. 귀하는 개발자 사이트에서 유료 서비스에 대한 접근 또는 라이선스 자료의 사용을 취소할 수 있습니다. 귀하는 어떠한 크레딧에 대해서도 환불받을 자격이 없으며, 사용되지 않은 크레딧의 사용에 대한 자격도 없습니다. 본 계약이 종료되면: (a) 본 계약에서 부여된 모든 라이선스는 즉시 만료되며, 귀하는 라이선스 자료 사용을 중단해야 합니다; (b) 귀하는 귀하가 소유한 모든 형태와 유형의 매체에 있는 모든 라이선스 자료와 그 사본을 영구적으로 삭제해야 합니다. 어떠한 이유로든 X의 요청에 따라 귀하는 신속하게(어떠한 경우에도 그러한 요청 후 10 영업일 이내에) 본 섹션의 앞서 언급된 (b) 항의 조항 준수 증거(예: 삭제 확인 스크린샷)를 제공해야 합니다. 본 계약의 당사자들은 본 계약에서 허용된 대로 본 계약의 종료로 인해서만 발생하는 어떠한 손해에 대해서도 서로 책임을 지지 않습니다.
**VIII. 준수 감사.**
X 또는 기밀 유지 의무에 구속되는 상호 합의된 제3자 대리인은 귀하에 대한 합리적인 통지 후 정상 영업 시간 중 합리적인 시간에, 본 계약의 이행과 관련하여 귀하의 통제 또는 소유 하에 있는 모든 기록을 검사 및 감사할 자격이 있으며, 이는 본 계약 준수와 감사 이전 2년 동안 X에게 지급되어야 할 요금을 검증하기 위한 것입니다. X는 미준수의 합리적인 원인이 없는 한 12개월에 한 번을 초과하여 감사권을 행사할 수 없으며, 그러한 감사는 귀하의 사업 활동을 부당하게 방해해서는 안 됩니다. 귀하는 그러한 감사에 대해 전면적으로 협조하고 지원할 것이며, 귀하가 소유한 모든 라이선스 자료, 관련 계약 및 기록에 대한 접근을 제공합니다. 앞서 언급한 사항의 일반성을 제한하지 않는 범위 내에서, 감사의 일환으로 X는 서면 보고서를 요청할 수 있으며, 귀하는 승인된 대표자가 서명하고 라이선스 자료의 당시 현재 배치를 나열한 보고서를 제공하는 것에 동의합니다. 귀하는 그러한 감사에서 밝혀진 미지급 금액을 감사 완료 후 30영업일 이내에 X에 지급해야 합니다. 또한, 그러한 감사에서 귀하의 미지급이 5% 이상인 것으로 밝혀지면, 귀하는 그러한 감사의 합리적인 비용과 경비에 대해서도 X에 상환해야 합니다. 본 섹션의 요건은 본 계약 종료 후 1년 동안 존속됩니다.
**IX. 면책 조항.**
관련 법률에서 허용하는 최대 범위 내에서, 라이선스 자료는 “있는 그대로(AS IS)”, “있는 위치에서(WHERE IS)”, 모든 결함이 있는 상태로 귀하에게 제공되며, X는 상품성, 비침해성, 특정 목적 적합성에 대한 보증 및 본 계약, 거래 과정 또는 상관습에서 발생하는 모든 보증이나 조건을 포함하되 이에 국한되지 않는 명시적, 묵시적, 법정 또는 기타의 모든 보증을 부인합니다. X는 라이선스 자료 또는 본 계약에 따라 제공되는 기타 X 제품 또는 서비스가 귀하의 요구 사항을 충족할 것이라거나, 그러한 라이선스 자료 또는 기타 제품이나 서비스의 사용이 오류가 없거나, 중단되지 않거나, 바이러스가 없거나, 안전할 것이라고 보증하지 않습니다. 귀하는 라이선스 자료의 사용 및 귀하가 제공하는 모든 콘텐츠에 대해 책임이 있습니다. 이 보증 면책은 일부 관할지에서 유효하지 않을 수 있으며, 귀하는 법률에 따라 포기하거나 부인할 수 없는 보증 권리를 가질 수 있습니다.
**또한 귀하는 유료 서비스가 “있는 그대로(AS IS)” 및 “이용 가능한 대로(AS AVAILABLE)” 귀하에게 제공된다는 점을 이해하고 이에 동의합니다.**
**X. 배상.**
귀하는 (a) 귀하가 본 계약과 부합하지 않는 방식으로 라이선스 자료를 사용하는 것 또는 (b) 귀하의 Services의 성능, 홍보, 판매 또는 배포로부터 발생하는 범위 내에서, 모든 소송, 청구, 클레임 및 소송(제조물 책임 청구를 포함하되 이에 국한되지 않음)에 대해 X를 방어해야 하며, 모든 책임, 손해 및 비용(합리적인 변호사 비용을 포함하되 이에 국한되지 않음)으로부터 X를 배상해야 합니다. 본 섹션에 따라 X가 귀하에게 배상 또는 방어를 요구하는 경우, X는 배상 또는 방어를 구하는 X에 대해 제기된 청구를 귀하에게 신속하게 서면으로 통지합니다. X는 X가 선택한 법률 자문과 함께 청구 방어에 대한 완전한 통제권을 인수할 수 있습니다. 귀하는 X의 사전 서면 동의 없이는 X의 권리에 영향을 미치거나, X의 과실 인정을 구성하거나, X를 어떠한 방식으로든 구속하는 제3자와의 계약을 체결해서는 안 됩니다. X가 그러한 청구에 대한 방어의 통제권을 인수하는 경우, X는 귀하의 사전 서면 승인 없이 귀하로부터의 지급이 요구되는 어떠한 청구도 합의해서는 안 됩니다.
**XI. 책임 제한.**
어떠한 경우에도 X는 본 계약과 관련하여 또는 본 계약으로부터 발생하는 어떠한 간접적, 특별, 부수적, 예시적, 징벌적 또는 결과적 손해 또는 사용, 데이터, 사업, 신용 또는 이익의 상실이나 손상에 대해 귀하 또는 어떠한 사용자에게도 책임을 지지 않습니다. 어떠한 경우에도, 본 계약에 따른 모든 청구에 대한 X의 총 책임은 50달러(\$50.00)를 초과하지 않습니다. 앞서 언급한 제한, 배제 및 면책은 그러한 책임이 계약, 보증, 불법 행위, 엄격 책임 또는 기타에 근거한 어떠한 청구에서 발생하는지 여부에 관계없이, 그리고 X가 그러한 손실 또는 손해의 가능성에 대해 조언을 받았는지 여부에 관계없이 적용됩니다. 관련 법률이 본 계약의 어떠한 책임 제한도 금지하는 경우, 당사자들은 그 제한이 관련 법률에 부합하도록 수정된 것으로 간주된다는 데 동의합니다. 당사자들은 본 계약에 명시된 책임 제한이 위험의 합의된 배분이며, 그러한 제한은 어떠한 제한된 구제책의 본질적 목적의 실패에도 불구하고 적용된다는 데 동의합니다.
**XII. 계약 업데이트.**
X는 수시로 본 계약 또는 편입 개발자 약관을 업데이트하거나 수정할 수 있습니다. 귀하는 업데이트를 위해 정기적으로 개발자 사이트를 확인해야 합니다. X는 이러한 사이트에 업데이트된 조건을 게시하거나, 서비스 알림을 통해, 또는 기타 적절한 수단(예: 귀하의 계정과 연결된 이메일 주소로의 이메일)을 통해 이러한 조건의 실질적 개정을 귀하에게 알립니다. 변경 사항은 소급 적용되지 않으며, 개발자 사이트에서 확인할 수 있는 본 계약의 가장 최신 버전이 라이선스 자료에 대한 귀하의 접근 및 사용과 그에 상응하는 모든 거래를 규율합니다. 귀하의 라이선스 자료에 대한 지속적인 접근 또는 사용은 그러한 업데이트 및 수정에 대한 구속력 있는 수락을 구성합니다.
**XIII. 분쟁 해결 및 집단 소송 포기.**
**A. 이 섹션은 귀하가 유럽연합, EFTA 회원국 또는 영국 이외에 거주하는 경우(미국에 거주하는 경우 포함)에만 귀하에게 적용됩니다. 이 섹션을 주의 깊게 읽어주십시오 – 이는 법원에 소송을 제기할 권리를 포함하여 귀하의 법적 권리에 상당한 영향을 미칠 수 있습니다.**
**1. 준거법 및 관할지 선택.** 당사자 간의 반대되는 어떠한 계약에도 불구하고, 텍사스주의 법률(법률의 저촉 규정 제외)이 본 계약과 귀하와 X 사이에서 발생하는 어떠한 분쟁도 규율합니다. 본 계약과 관련된 모든 분쟁(본 계약, 라이선스 자료의 마케팅 및/또는 라이선스 자료에서의 귀하의 참여로부터 발생하거나 이와 관련된 어떠한 분쟁, 청구 또는 논란 포함)은 미국 텍사스주 북부지역 연방지방법원 또는 미국 텍사스주 태런트 카운티에 있는 주 법원에서만 제기되며, 귀하는 그러한 법정에서의 대인 관할권에 동의하고 불편한 법정에 대한 어떠한 이의도 포기합니다. 앞서 언급한 사항을 침해하지 않고, 귀하는 X가 그 단독 재량으로 귀하에 대한 청구, 소송 원인 또는 분쟁을 청구에 대한 관할과 재판지가 있는 귀하가 거주하는 국가의 관할 법원에 제기할 수 있다는 데 동의합니다.
귀하가 공식 자격으로 라이선스 자료를 사용하는 미국의 연방, 주 또는 지방 정부 기관이며, 위의 준거법, 관할 또는 재판지 조항을 법적으로 수락할 수 없는 경우, 그러한 조항은 귀하에게 적용되지 않습니다. 그러한 미국 연방 정부 기관의 경우, 본 계약 및 이와 관련된 모든 조치는 미국의 법률(법률의 저촉 참조 없이)에 의해 규율되며, 연방법이 없는 경우 연방법이 허용하는 범위 내에서 텍사스주의 법률(법률의 선택 제외)에 의해 규율됩니다.
**2. 귀하는 X에 대한 청구를 제기할 1년의 기간을 가집니다.** 본 계약에서 발생하거나 이와 관련된 X에 대한 어떠한 청구도 관련 법률이 해당 청구에 대한 정상적인 소멸시효를 계약에 의해 단축할 수 없다고 규정하지 않는 한, 분쟁을 발생시키는 사건이나 사실의 발생일로부터 1년 이내에 제기해야 합니다. 이 기간 내에 청구를 제기하지 않으면, 귀하는 그러한 사건 또는 사실에 근거한 어떠한 종류 또는 성격의 청구 또는 소송 원인도 추구할 권리를 영구적으로 포기하며, 그러한 청구 또는 소송 원인은 영구적으로 금지되고 X는 그러한 청구에 대해 어떠한 책임도 지지 않습니다.
**3. 집단 소송 포기.** 법률에서 허용하는 범위 내에서, 귀하는 또한 어떠한 소위 집단 소송, 공동 소송 또는 대표 소송 절차에서 원고 또는 집단 구성원으로 참여할 권리를 포기합니다.
**4. 이 섹션의 변경.** 이 분쟁 해결 섹션은 귀하와 X 간의 관계 종료(X가 제공하는 서비스나 커뮤니케이션의 취소 또는 구독 해지 포함) 후에도 존속합니다.
**5. 금지 명령적 구제.** 앞서 언급한 사항에도 불구하고, 귀하는 X의 지식재산 또는 기밀 정보를 보호하는 본 계약의 위반 또는 위반 위협 시 X에 대해 금전적 손해가 부적절한 구제책이 될 것이며, 그러한 위반 또는 위협 시 X는 자격이 있는 다른 구제책 외에도 담보 제공 필요 없이 예비적 또는 금지적 구제(그러한 조항 위반 행위를 금지하는 명령 포함)와 적절한 경우 특정 이행을 받을 자격이 있다는 데 동의합니다. 당사자들은 국제 물품매매계약에 관한 유엔협약 및 통일 컴퓨터 정보 거래법이 당사자들이 사업을 하거나 설립된 주에 관계없이 본 계약에 적용되지 않는다는 데 동의합니다. 본 계약에 따른 어떠한 약정 또는 권리에 대한 X의 포기는 X가 승인한 서면으로 문서화되지 않는 한 효력이 없습니다.
**B. 이 섹션은 귀하가 유럽연합, EFTA 회원국 또는 영국에 거주하는 경우에만 귀하에게 적용됩니다. 이 섹션을 주의 깊게 읽어주십시오 – 이는 법원에 소송을 제기할 권리를 포함하여 귀하의 법적 권리에 상당한 영향을 미칠 수 있습니다.**
**1. 준거법 및 관할지 선택.** 법률에서 허용하는 범위 내에서, 본 계약과 관련된 모든 분쟁(본 계약, 라이선스 자료의 마케팅 및/또는 라이선스 자료에서의 귀하의 참여로부터 발생하거나 이와 관련된 어떠한 분쟁, 청구 또는 논란 포함)은 당사자 간의 반대되는 어떠한 계약에도 불구하고 법률의 저촉 규정을 고려하지 않고 아일랜드의 관할 법원에서만 제기되며, 아일랜드 법률에 의해 규율됩니다. 앞서 언급한 사항을 침해하지 않고, 귀하는 X가 그 단독 재량으로 귀하에 대한 청구, 소송 원인 또는 분쟁을 청구에 대한 관할과 재판지가 있는 귀하가 거주하는 국가의 관할 법원에 제기할 수 있다는 데 동의합니다.
**2. 귀하는 X에 대한 청구를 제기할 1년의 기간을 가집니다.** 본 계약에서 발생하거나 이와 관련된 X에 대한 어떠한 청구도 관련 법률이 해당 청구에 대한 정상적인 소멸시효를 계약에 의해 단축할 수 없다고 규정하지 않는 한, 분쟁을 발생시키는 사건이나 사실의 발생일로부터 1년 이내에 제기해야 합니다. 이 기간 내에 청구를 제기하지 않으면, 귀하는 그러한 사건 또는 사실에 근거한 어떠한 종류 또는 성격의 청구 또는 소송 원인도 추구할 권리를 영구적으로 포기하며, 그러한 청구 또는 소송 원인은 영구적으로 금지되고, X는 그러한 청구에 대해 어떠한 책임도 지지 않습니다.
**3. 집단 소송 포기.** 법률에서 허용하는 범위 내에서, 귀하는 또한 어떠한 소위 집단 소송, 공동 소송 또는 대표 소송 절차에서 원고 또는 집단 구성원으로 참여할 권리를 포기합니다.
**4. 이 섹션의 변경.** 이 분쟁 해결 섹션은 귀하와 X 간의 관계 종료(X가 제공하는 서비스나 커뮤니케이션의 취소 또는 구독 해지 포함) 후에도 존속합니다.
**5. 금지 명령적 구제.** 앞서 언급한 사항에도 불구하고, 귀하는 X의 지식재산 또는 기밀 정보를 보호하는 본 계약의 위반 또는 위반 위협 시 X에 대해 금전적 손해가 부적절한 구제책이 될 것이며, 그러한 위반 또는 위협 시 X는 자격이 있는 다른 구제책(금전적 손해 포함) 외에도 담보 제공 필요 없이 그러한 예비적 또는 금지적 구제(그러한 조항 위반 행위를 금지하는 명령 포함)와 적절한 경우 특정 이행을 받을 자격이 있다는 데 동의합니다. 당사자들은 국제 물품매매계약에 관한 유엔협약 및 통일 컴퓨터 정보 거래법이 당사자들이 사업을 하거나 설립된 주에 관계없이 본 계약에 적용되지 않는다는 데 동의합니다. 본 계약에 따른 어떠한 약정 또는 권리에 대한 X의 포기는 X가 승인한 서면으로 문서화되지 않는 한 효력이 없습니다.
**XIV. 기타.**
**A. 양도.** 귀하는 X의 사전 서면 동의를 제외하고, 자발적으로든 법률의 작용, 계약, 합병(귀하가 존속 법인이든 소멸 법인이든), 주식 또는 자산 매각, 통합, 해산, 정부 조치 또는 그 밖의 방식으로든 본 계약에서 부여된 권리 또는 의무의 전부 또는 일부를 양도해서는 안 됩니다. X는 미국 외부에 거주하는 X 사용자의 정보를 담당하는 아일랜드 회사인 X Internet Unlimited Company를 대신하여 수정 및 동의에 서명할 권한을 부여받았습니다. 본 섹션을 위반한 어떠한 양도 시도도 무효이며, X는 본 계약을 종료할 수 있습니다.
**B. 사용자 보호.** X가 서면으로 명시적으로 승인하지 않는 한, 귀하는 다음의 목적으로 X 콘텐츠 또는 X 콘텐츠에서 파생된 정보를 사용하거나 알면서 표시, 배포 또는 그 밖의 방법으로 이용 가능하게 해서는 안 됩니다: (a) X 사용자 또는 X 콘텐츠에 대한 조사 또는 추적을 포함하되 이에 국한되지 않는 감시 실시 또는 제공 또는 정보 수집; (b) 불법적이거나 차별적인 목적을 위한 또는 X 사용자의 합리적인 프라이버시 기대와 부합하지 않는 방식으로의 분석 또는 연구 실시 또는 제공; (c) 민감한 사건(시위, 집회 또는 공동체 조직 회의를 포함하되 이에 국한되지 않음) 모니터링; 또는 (d) 건강(예: 임신), 부정적인 재정 상태 또는 상황, 정치적 소속 또는 신념, 인종 또는 민족적 출신, 종교적 또는 철학적 소속 또는 신념, 성생활 또는 성적 지향, 노동조합 가입, 범죄의 혐의 또는 실제 실행과 관련된 X 콘텐츠 또는 법률에서 금지하는 기타 민감한 개인 정보 범주를 포함한 민감한 개인 정보에 근거한 개인 타기팅, 세그멘테이션 또는 프로파일링.
**C. 정부 사용.** 귀하가 정부 관련 기관이거나 정부 관련 기관을 대신하여 활동하는 사용자(각각 “**정부 최종 사용자(Government End User)**”)에게 X 콘텐츠를 표시, 배포 또는 그 밖의 방법으로 제공하는 경우; (a) 귀하는 엔터프라이즈(Enterprise) 플랜([**https://docs.x.com/enterprise-api/introduction**](https://docs.x.com/enterprise-api/introduction)에 기술된 대로)을 신청하거나 이미 구독해야 합니다; (b) 귀하의 사용 사례를 X에 검토를 위해 제출할 때 그러한 모든 정부 최종 사용자를 식별해야 합니다; 그리고 (c) 그 후 Services가 정부 최종 사용자에게 또는 새로운 사용 사례를 위해 X 콘텐츠를 표시, 배포 또는 그 밖의 방법으로 제공하기 전에 새로운 정부 최종 사용자 또는 기존 정부 최종 사용자와의 새로운 사용 사례에 대해 X에 서면으로 통지해야 합니다. X는 귀하가 어떠한 정부 최종 사용자에게도 X 콘텐츠를 제공하는 것을 금지할 수 있습니다. 귀하는 감시 실시 또는 정보 수집을 주된 기능 또는 임무로 하는 어떠한 정부 최종 사용자에게도 X 콘텐츠 또는 X 콘텐츠로부터 파생된 정보를 사용하거나 알면서 표시, 배포 또는 그 밖의 방법으로 제공해서는 안 됩니다. 법 집행 기관이 진행 중인 조사 목적으로 X 또는 그 사용자에 관한 정보를 요청하는 경우, 귀하는 그들을 [**https://help.x.com/rules-and-policies/x-law-enforcement-support**](https://help.x.com/rules-and-policies/x-law-enforcement-support)에 있는 X의 법 집행 기관 지침(Guidelines for Law Enforcement)에 안내할 수 있습니다. X API 및 X 콘텐츠는 48 C.F.R. 12.212에서 사용되는 용어인 “상업용 컴퓨터 소프트웨어(commercial computer software)” 및 “상업용 컴퓨터 소프트웨어 문서화(commercial computer software documentation)”로 구성된 48 C.F.R. 2.101에 정의된 “상업용 품목(commercial items)”입니다. 정부 기관에 의한 X API 또는 X 콘텐츠의 어떠한 사용, 수정, 파생물, 복제, 공개, 성능, 표시, 공시 또는 배포도 본 계약의 조건에서 명시적으로 허용된 경우를 제외하고 금지됩니다. 또한 미국 정부 기관에 의한 어떠한 사용도 48 C.F.R. 12.212 및 48 C.F.R. 227.7202-1 내지 227.7202-4에 따라 이루어져야 합니다. 귀하가 미국 주 또는 지방 정부 기관의 직원 또는 대표로서 공식 자격으로 X API 또는 X 콘텐츠를 사용하고 있으며 본문의 배상, 관할, 재판지 또는 기타 조항을 법적으로 수락할 수 없는 경우, 그러한 조항은 법률에서 요구하는 범위 내에서 그러한 기관에 적용되지 않습니다. 계약자/제조자는 X Corp., 865 FM 1209, Building 2, Bastrop, TX 78602, USA입니다.
**D. 법률, 수출 및 수입 준수.** 각 당사자는 뇌물 수수 및/또는 부패에 관한 모든 법률을 포함하되 이에 국한되지 않는 모든 관련 외국, 연방, 주 및 지방 법률, 규칙 및 규정을 준수합니다. 라이선스 자료는 미국 수출법의 적용을 받으며 인도되거나 사용되는 국가의 수입 및 사용 법률의 적용을 받을 수 있습니다. 귀하는 이러한 법률을 준수해야 합니다. 이러한 법률에 따라, 라이선스 자료는 라이선스 또는 관련 정부 당국의 승인 없이 미국 정부가 금수 조치를 취한 국가(현재 쿠바, 이란, 북한, 북수단 및 시리아)를 포함하여 이러한 법률에 의해 제한된 어떠한 국가 또는 외국인에게도, 미국 해외자산통제국(U.S. Office of Foreign Assets Control)에 의해 금지된 개인 또는 단체를 포함하되 이에 국한되지 않는 제한 또는 거부된 최종 사용자에게, 또는 어떠한 제한된 최종 용도로도 판매, 임대, 다운로드, 이동, 수출, 재수출 또는 국경을 넘어 이전될 수 없습니다. 귀하는 귀하의 Services에 필요한 모든 권리 및 라이선스를 유지해야 합니다.
**E. 데이터 보호 부속서.** 각 당사자는 [**https://gdpr.x.com/controller-to-controller-transfers.html**](https://gdpr.x.com/en/controller-to-controller-transfers.html)에 있는 X Controller-to-Controller Data Protection Addendum(수시로 X가 업데이트할 수 있음)을 준수해야 합니다.
**F. 존속.** 본 계약의 섹션 III(사용 제한), V(소유권 및 피드백), VI(기밀 유지), VII(I)(종료), VIII(준수 감사), IX(보증 면책), X(배상), XI(책임 제한), XIII(분쟁 해결 및 집단 소송 포기); 그리고 XIV(기타)는 본 계약의 종료 후에도 존속합니다.
**G. 전체 계약.** 본 계약은 본 계약의 대상에 관한 당사자들의 전체 이해를 구성하며, 서면이든 구두이든 대상과 관련된 당사자 간의 다른 모든 계약을 대체합니다. 본 계약의 어떤 조항이 법원에 의해 집행 불가능하다고 판결되는 경우, 본 계약의 나머지 조항은 계속 효력을 유지합니다. 본 계약에 따른 어떠한 포기도 서면으로 작성되고 포기를 부여하는 당사자에 의해 서명되지 않는 한 효력이 없습니다. 한 번 부여된 포기는 다른 경우에 포기로 작동하지 않습니다. 본 계약은 어떠한 파트너십, 대리 또는 합작 투자도 창설하거나 암시하지 않습니다.
[**개발자 정책 및 약관**](https://docs.x.com/developer-terms)
[**@XDEVELOPERS**](https://x.com/XDevelopers) 팔로우
[**개발자 뉴스 구독**](https://developer.x.com/twitterdev-news-subscription)
# 표시 요건: 답글
Source: https://docs.x.com/ko/developer-terms/reply-requirements
X API를 사용하는 앱에서 게시물에 대한 답글을 표시하기 위한 요건으로, 스레드 구조, 출처 표기, 답글 컨텍스트 규칙을 포함합니다.
## 답글
답글을 표시할 때는 다음 가이드라인을 준수하세요.
### 기본 답글의 경우:
### 소셜 컨텍스트가 포함된 답글의 경우:
### 인용의 경우:
# X API의 제한된 사용
Source: https://docs.x.com/ko/developer-terms/restricted-use-cases
오프플랫폼 추적, 정부 감시, 민감한 데이터 처리, 금지 도구 등을 포함한 X API의 제한된 사용 사례에 대한 세부 정보입니다.
당사 개발자 플랫폼의 사용을 위해서는 [개발자 계약 및 정책](/developer-terms/agreement)과 [표시 요건](https://docs.x.com/developer-terms/display-requirements) 및 [자동화 규칙](https://help.x.com/en/rules-and-policies/twitter-automation)을 포함한 관련 정책을 검토하고 이에 동의해야 합니다. 당사 계약과 정책은 특히 여러 제한된 사용 사례에 대한 지침을 제공합니다. 이러한 제한 사항 중 일부에 대한 추가 정보를 아래에 제공합니다.
## 자동화, 스팸 및 자동 응답
X의 API 및 개발자 제품을 사용하여 스팸을 생성하거나 스팸성 행동에 관여하는 것은 금지됩니다. 스팸에 관한 [X 규칙](https://t.co/rules)을 검토하고, 애플리케이션이 당사 정책을 위반하거나 사용자가 이를 위반하도록 하지 않는지 확인해야 합니다.
애플리케이션이 게시물 게시, 계정 팔로우, Direct Message 전송 등 X 서비스에서 쓰기 작업을 수행하는 데 사용되는 경우, 서비스가 당사 가이드라인을 준수하는지 확인하기 위해 [자동화 규칙](https://support.x.com/articles/76915)을 신중하게 검토해야 합니다. 특히 다음 사항을 준수해야 합니다:
* [자동화된 답글 또는 메시지](https://twittercommunity.com/t/policy-clarification-automated-replies-and-mentions/94444)를 사용자에게 보내기 전에 항상 사용자의 명시적인 동의를 받으세요
* 귀하로부터 연락받는 것을 거부하는 사용자 요청을 즉시 존중하세요
* [대량 팔로우](https://twittercommunity.com/t/policy-clarification-aggressive-following-and-inorganic-following-behavior/92769)를 포함한 대량, 공격적 또는 스팸성 작업을 수행하지 마세요
* [여러 계정](https://blog.x.com/developer/en_us/topics/tips/2018/automation-and-the-use-of-multiple-accounts.html)에 걸쳐 동일하거나 실질적으로 유사한 콘텐츠를 게시하지 마세요
## 민감한 정보
X 데이터를 사용하여 X 사용자에 대한 잠재적으로 민감한 특성을 도출하거나 추론하는 것에 대해 주의해야 합니다. X 사용자에 대한 다음 정보를 도출, 추론하거나 도출/추론한 정보를 저장하지 마세요:
* 건강(임신 포함)
* 부정적인 재정 상태 또는 상황
* 정치적 소속 또는 신념
* 인종 또는 민족적 출신
* 종교적 또는 철학적 소속 또는 신념
* 성생활 또는 성적 지향
* 노동조합 가입
* 범죄 행위의 혐의 또는 실제 행위
개인 데이터(예: 사용자 ID, 사용자 이름, 기타 식별자)를 저장하지 않는 X 콘텐츠의 집계 분석은 해당 분석이 적용 법률 및 개발자 계약과 정책의 모든 부분을 준수하는 한 허용됩니다.
## Off-X 매칭
Off-X 매칭은 X 사용자 이름이나 사용자 ID를 포함한 X 콘텐츠를 개인, 가정, 기기, 브라우저 또는 기타 오프-X 식별자와 연관시키는 것을 의미합니다. 한 가지 예로 X 사용자 이름을 기업의 고객 기록과 연결하는 것을 들 수 있습니다(즉, 귀하의 고객 기록에서 "John Doe"가 X의 @johndoe와 매칭됨).
우리는 사람들이 X에서 별도의, 원한다면 익명의 정체성을 만드는 것에 편안함을 느끼기를 원합니다. X 사용자에 관한 어떤 정보를 오프-X 식별자와 연관시키려는 경우, 연관을 만들기 전에 사용자로부터 명시적, 옵트인 동의를 받아야 합니다. 예를 들어, 사용자가 귀하의 서비스에 가입하는 과정에서 자신의 X 핸들을 귀하에게 직접 공유하는 경우 이러한 동의를 얻을 수 있습니다.
사용자의 명시적, 옵트인 동의 없이 그들의 X 정체성을 오프-X 식별자에 연결하는 상황에서는, 사용자가 해당 목적으로 사용될 것을 합리적으로 예상할 수 있는 정보에만 기반하여 연결을 만들도록 요구합니다. 사용자가 자신이 제공한 정보를 사용해 X 계정을 X 외부의 정체성에 연결하는 것을 알게 되면 놀랄 것 같다면, 그렇게 하지 마세요. 또한, 사용자의 명시적 옵트인 동의가 없는 경우 다음에 기반해서만 자신의 기록을 X 정체성과 매칭하려고 시도할 수 있습니다:
* **사용자가 귀하에게 직접 제공한 정보.** 사전 관계가 없는 개인에 관한 기록, 즉 제3자로부터 얻은 개인에 관한 데이터는 이 기준을 충족하지 않습니다. 및/또는
* **공개 데이터.** 이 맥락에서 "공개 데이터"란 다음을 의미합니다:
* 공개적이고 일반적으로 이용 가능한 리소스(예: 전문 협회 회원 디렉터리)에서 얻은 사용자에 관한 정보
* 공개적으로 이용 가능한 X 상의 사용자 정보 (다음 포함):
* 게시물
* 사용자 프로필 정보(사용자 소개 및 공개적으로 명시된 위치 포함)
* 표시 이름 및 사용자 이름
## X 콘텐츠의 재배포
X API를 통해 얻은 X 콘텐츠를 다른 당사자와 공유해야 하는 경우, 가장 좋은 방법은 게시물 ID, Direct Message ID 및/또는 사용자 ID를 공유하는 것입니다. 그러면 콘텐츠의 최종 사용자가 X API를 사용하여 이를 재수화(rehydrate)(즉, 전체 게시물, 사용자 또는 Direct Message 콘텐츠를 요청)할 수 있습니다. 이는 X 콘텐츠의 최종 사용자가 항상 최신 정보를 우리에게서 직접 얻을 수 있도록 보장하는 데 도움이 됩니다.
당사는 자동화되지 않은 수단을 통한 수화된(hydrated) X 콘텐츠의 제한된 재배포를 허용합니다. 이러한 방식으로 수화된 X 콘텐츠를 다른 당사자와 공유하기로 선택한 경우, 수신자당 하루 최대 50,000개의 수화된 공개 게시물 객체 및/또는 사용자 객체만 공유할 수 있으며, 이 데이터를 공개적으로 이용 가능하게 해서는 안 됩니다(예: 블로그 게시물의 첨부 파일이나 공개 Github 저장소에).
X 콘텐츠 재배포와 관련하여 유의해야 할 몇 가지 다른 사항이 있습니다:
* X로부터 사전에 명시적인 서면 허가를 받지 않는 한, 30일 기간 내에 단일 개체에 총 1,500,000개 이하의 게시물 ID만 배포할 수 있습니다.
* 학술 기관을 대신하여 비상업적 연구를 유일한 목적으로 게시물 ID 및/또는 사용자 ID를 재배포하는 개인은 무제한의 게시물 ID 및/또는 사용자 ID를 재배포할 수 있습니다.
* 위와 같이 X 콘텐츠를 공유할 권한을 요청하려면 API 정책 지원 양식을 사용하세요.
X 콘텐츠를 제3자에게 배포할 수 있는 범위에서, 이 콘텐츠는 개발자 계약 및 정책의 적용을 계속 받으며, 해당 제3자는 X 콘텐츠를 받기 전에 X의 [서비스 약관](https://x.com/en/tos), [개인정보 보호정책](https://x.com/en/privacy), [개발자 계약](/developer-terms/agreement), [개발자 정책](/developer-terms/policy)에 동의해야 합니다.
## 다중 애플리케이션
단일 사용 사례 또는 실질적으로 유사하거나 중복되는 사용 사례에 대해 여러 애플리케이션을 등록하는 것은 허용되지 않습니다. 이 정책에 대해서는 [여기](https://twittercommunity.com/t/policy-clarification-multiple-applications-for-the-same-use-case/92080)에서 자세히 알아보세요.
이 맥락에서 "사용 사례"는 애플리케이션을 통해 수행되는 일관된 분석, 표시 또는 작업 집합으로 정의됩니다. 동일한 서비스 또는 애플리케이션을 다른 최종 사용자에게 제공하는 것은 단일 사용 사례에 해당합니다: 다만, 도구 또는 서비스의 "화이트 라벨" 버전은 포함되지 않습니다. 애플리케이션의 "화이트 라벨" 버전을 계획하는 경우, 당사에 알리고 별도의 승인을 받아야 합니다. 이러한 규칙은 귀하가 등록한 애플리케이션과 도구 또는 서비스의 최종 사용자가 등록한 애플리케이션 모두에 적용됩니다; 도구나 서비스를 사용하기 위해 최종 사용자에게 애플리케이션을 등록하도록 요구하는 것은 귀하, 귀하의 애플리케이션, 귀하의 고객 및/또는 도구 또는 서비스의 최종 사용자에 대한 집행 조치로 이어질 수 있습니다.
이 규칙의 유일한 예외는 동일한 서비스의 개발("dev"), 스테이징 및 프로덕션("prod") 인스턴스를 만드는 것입니다. 이러한 애플리케이션이 (예를 들어, 애플리케이션 이름이나 설명에서) 명확하게 라벨링되어 있고, 개발 또는 스테이징 애플리케이션을 프로덕션 목적으로 사용하지 않아야 합니다.
## X 서비스 측정
벤치마킹이나 경쟁 목적으로 X의 가용성, 성능, 기능 또는 사용량을 측정하기 위해 X API를 사용하지 마세요. 예를 들어, X API를 사용하여 다음을 절대 수행해서는 안 됩니다:
* 총 활성 사용자 수 또는 계정 수 등의 X 사용자 지표 집계 계산
* 하루 총 게시물 수, 사용자 참여 수 또는 계정 참여 수 등의 X 게시물 지표 집계 계산
* [X 규칙](https://help.x.com/en/rules-and-policies/twitter-rules)에서 허용된 경우를 제외하고 X의 스팸이나 보안 측정 또는 분석
## 감시, 개인정보 보호 및 사용자 보호
X에서는 사용자의 개인정보를 보호하고 방어하는 것이 회사의 핵심 DNA에 내재되어 있으며 — 당사의 개발자 및 데이터 제품은 그러한 약속을 반영합니다. 우리는 X 데이터가 세상에 강력한 선의 힘이 될 수 있다고 믿습니다 — 자카르타 홍수 시 인명을 구조하는 것부터 지진을 추적하기 위해 USGS를 지원하고, 지속가능한 개발 목표를 달성하기 위해 UN과 협력하는 것까지 말입니다. 그러나 우리는 감시 목적으로, 또는 사용자의 합리적인 개인정보 보호 기대에 반하는 방식으로 어떠한 개체가 X 데이터와 X API를 사용하는 것을 금지합니다. 이상.
당사는 [개발자 계약](/developer-terms/agreement)에서 X 사용자 또는 그들의 콘텐츠에 대한 조사 또는 추적, 민감한 이벤트(항의, 집회, 커뮤니티 조직 회의 등)에 대한 추적, 알림 또는 모니터링 금지 등을 포함한 당사 데이터 및 개발자 제품의 금지된 용도를 설명합니다.
이러한 약관에 따라 금지되는 활동의 다른 범주에는 다음이 포함됩니다(이에 국한되지 않음):
* 노동조합이나 활동가 그룹과 같은 민감한 그룹 및 조직에 대한 조사 또는 추적
* 신원 조회 또는 어떤 형태의 극단적 심사
* 신용 또는 보험 위험 분석
* 개인 프로파일링 또는 심리 분석적 세그멘테이션
* 얼굴 인식
이러한 정책은 당사 API의 모든 사용자에게 적용됩니다. 이러한 목적을 위한 X API의 오용은 접근 정지 및 해지를 포함할 수 있는 집행 조치의 대상이 됩니다.
X 계정에 관한 정보를 요청하는 법 집행 기관을 위한 추가 정보는 [https://t.co/le](https://t.co/le) 를 방문하세요.
또한, 현재 X는 [Grok](https://help.x.com/en/using-x/about-grok)을 제외하고 파운데이션 모델 또는 프론티어 모델을 파인튜닝하거나 훈련시키기 위해 X API 및/또는 X 콘텐츠를 사용하는 것을 금지합니다.
# Enterprise API 소개 — firehose, 스트림, webhook
Source: https://docs.x.com/ko/enterprise-api/getting-started/about-x-api
전체 firehose 액세스, Decahose 및 좋아요 볼륨 스트림, Account Activity webhook, 맞춤형 속도 제한, 전담 지원과 SLA를 포함한 X Enterprise API 개요로, 각 제품이 제공하는 실시간 및 히스토리 데이터 기능을 정리합니다.
Enterprise API는 X 데이터에 대한 최상위 티어 액세스를 제공합니다. 표준 X API에서 사용할 수 있는 모든 기능과 함께 독점적인 대용량 엔드포인트, Filtered Stream을 위한 semantic embedding 연산자, 맞춤형 속도 제한, 대규모로 X 데이터를 필요로 하는 조직을 위한 전담 계정 관리가 포함됩니다.
***
## 할 수 있는 작업
표준 X API의 모든 기능에 더해:
| 기능 | 설명 |
| :------------------------- | :--------------------------------------------------------------------------------- |
| **전체 firehose 스트리밍** | 볼륨 스트림으로 100%의 공개 게시물에 실시간 액세스 |
| **모든 좋아요 스트리밍** | 전체 및 샘플 좋아요 스트림을 실시간으로 |
| **고급 필터링 스트리밍** | Powerstream(저지연 키워드 필터링) |
| **semantic embedding 연산자** | Filtered Stream에서 `embedding:`을 사용해 의미(키워드가 아닌)로 게시물 매칭(Enterprise + Embedding 티어) |
| **심층 참여도 분석** | 대규모 게시물 및 미디어 참여도 지표 |
| **account activity 이벤트** | 사용자 이벤트(게시물, DM, 좋아요, 팔로우)에 대한 실시간 구독 |
| **Webhook 전달** | webhook을 통한 filtered stream 데이터 수신 |
| **맞춤형 속도 제한** | 처리량 요구 사항에 맞는 상향 한도 |
| **전담 지원** | 지정된 계정 관리자 및 우선 문제 해결 |
***
## Enterprise 전용 엔드포인트
이러한 엔드포인트는 Enterprise 액세스에서만 사용할 수 있습니다:
완전한 실시간 커버리지를 위한 전체 firehose 및 언어별 스트림입니다.
플랫폼 전반의 모든 좋아요 또는 샘플 좋아요를 스트리밍합니다.
고급 연산자를 사용한 고성능 필터링 스트리밍입니다.
심층 참여도 인사이트를 위한 게시물 및 미디어 분석입니다.
사용자 활동에 대한 실시간 이벤트 구독입니다.
webhook을 통한 filtered stream 전달입니다.
***
## 사용 가능한 모든 리소스
Enterprise 액세스에는 X API 리소스의 전체 세트가 포함됩니다:
게시물 검색, 조회, 생성, 삭제. 타임라인, 스레드, 인용 게시물에 액세스합니다.
프로필 조회, 관계 관리, 팔로워 데이터에 액세스합니다.
라이브 오디오 대화와 참여자를 찾으세요.
사용자 간 비공개 메시지를 송수신합니다.
큐레이션된 계정 리스트를 만들고 관리합니다.
위치별 트렌드 주제에 액세스합니다.
***
## API 주요 기능
필요한 데이터만 요청하세요. `fields` 매개변수로 특정 속성을 선택하고 `expansions`로 관련 객체를 포함시킵니다.
```bash theme={null}
curl "https://api.x.com/2/tweets/123?tweet.fields=created_at,public_metrics&expansions=author_id&user.fields=username" \
-H "Authorization: Bearer $TOKEN"
```
[fields에 대해 자세히 알아보기 →](/x-api/fundamentals/fields)
게시물에는 사람, 장소, 제품, 주제를 식별하는 의미론적 주석이 포함됩니다. 주제별로 스트림과 검색을 필터링할 수 있습니다.
[주석에 대해 자세히 알아보기 →](/x-api/fundamentals/post-annotations)
Enterprise 고객은 표준 공개 지표 이상의 대규모 심층 분석을 제공하는 게시물 및 미디어 전용 참여도 지표 엔드포인트에 액세스할 수 있습니다.
[지표에 대해 자세히 알아보기 →](/x-api/fundamentals/metrics)
`conversation_id`를 사용해 전체 대화 스레드를 재구성합니다. 스레드 전체에서 답글을 추적할 수 있습니다.
[대화 추적에 대해 자세히 알아보기 →](/x-api/fundamentals/conversation-id)
이전 버전 및 편집 메타데이터를 포함한 게시물의 편집 기록에 액세스합니다.
[게시물 편집에 대해 자세히 알아보기 →](/x-api/fundamentals/edit-posts)
***
## 가격
Enterprise 플랜은 조직의 요구 사항에 맞게 맞춤화됩니다. 가격은 데이터 볼륨, 엔드포인트 사용량, 지원 요구 사항을 기준으로 책정됩니다.
| 기능 | 세부 정보 |
| :--------------- | :------------------------ |
| **맞춤형 패키지** | 특정 데이터 및 처리량 요구 사항에 맞게 조정 |
| **장기 계약** | 약정 사용량 계약을 통한 예측 가능한 가격 |
| **게시물 읽기 상한 없음** | 맞춤형 또는 무제한 게시물 읽기 볼륨 |
| **전담 지원** | 모든 Enterprise 플랜에 포함 |
[가격에 대해 영업팀에 문의](/forms/enterprise-api-interest)
***
## 다음 단계
영업팀에 문의하여 요구 사항을 논의하세요.
Enterprise 전용 엔드포인트를 포함한 모든 사용 가능한 엔드포인트를 둘러보세요.
# Enterprise 액세스 받기
Source: https://docs.x.com/ko/enterprise-api/getting-started/getting-access
X Enterprise API 액세스를 신청하는 방법을 안내합니다. 전담 계정 팀과 함께 진행하는 온보딩, API 키와 액세스 토큰 발급, 엔드포인트 설정, 조직의 데이터 볼륨과 지원 요구 사항에 맞춘 맞춤 플랜 구성까지의 절차를 단계별로 설명합니다.
Enterprise 액세스에는 신청 및 온보딩 절차가 필요합니다. 전담 계정 팀이 자격 증명 설정과 액세스 구성을 도와드립니다.
***
## 1단계: Enterprise 액세스 신청
[Enterprise 관심 양식을 작성](/forms/enterprise-api-interest)하여 조직과 사용 사례에 대한 세부 정보를 제공합니다.
영업팀이 연락하여 데이터 볼륨, 엔드포인트 요구 사항 및 지원 요구를 파악합니다.
사용 사례에 맞게 설계된 가격, 속도 제한 및 액세스 수준이 포함된 맞춤형 플랜을 받습니다.
***
## 2단계: 온보딩 진행
Enterprise 플랜이 마련되면 전담 계정 관리자가 다음 항목 설정을 지원합니다:
[Developer Console](https://console.x.com)에서 Enterprise 수준 액세스로 App을 설정합니다.
계정 관리자가 속도 제한, 엔드포인트 액세스 및 맞춤 설정 구성을 지원합니다.
인증에 사용할 API 키와 토큰을 생성합니다.
***
## 3단계: 자격 증명 저장
인증 요구 사항에 따라 여러 자격 증명을 받게 됩니다:
| 자격 증명 | 용도 |
| :------------------------ | :------------------------------------------- |
| **API Key & Secret** | App을 식별합니다. 토큰 생성 및 OAuth 1.0a 요청 서명에 사용합니다. |
| **Bearer Token** | 공개 데이터 읽기를 위한 App 전용 인증. |
| **Access Token & Secret** | 본인의 계정을 대신하여 요청합니다 (OAuth 1.0a). |
| **Client ID & Secret** | 사용자 컨텍스트 요청을 위한 OAuth 2.0 인증. |
**즉시 저장하세요.** 자격 증명은 한 번만 표시됩니다. 비밀번호 관리자나 보안 금고에 보관하세요. 분실하면 재생성해야 하며 (재생성 시 이전 자격 증명은 무효화됩니다).
***
## 어떤 자격 증명이 필요한가요?
공개 데이터에 대한 간단한 읽기 전용 액세스에는 **Bearer Token**을 사용하세요.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
적합한 용도: 게시물 검색, 사용자 조회, 트렌드 읽기.
사용자를 대신하여 동작하려면 **OAuth 2.0** (권장) 또는 **OAuth 1.0a**를 사용하세요.
OAuth 2.0은 세분화된 스코프를 제공하므로 필요한 권한만 요청할 수 있습니다.
적합한 용도: 게시, 좋아요, 팔로우, DM 액세스.
[OAuth 2.0 가이드 →](/resources/fundamentals/authentication/oauth-2-0/overview)
본인 계정으로 요청하려면 **Access Token & Secret**을 사용하세요.
이 토큰은 App을 소유한 계정을 나타냅니다.
적합한 용도: 테스트, 개인용 봇, 본인의 자동화.
***
## 자격 증명 보안 모범 사례
자격 증명을 소스 코드에 하드코딩하지 마세요.
자격 증명 파일을 `.gitignore`에 추가하세요.
보안 조치로 자격 증명을 주기적으로 재생성하세요.
App에 필요한 OAuth 권한만 요청하세요.
***
## 다음 단계
새 자격 증명으로 API를 호출합니다.
OAuth 1.0a와 OAuth 2.0을 이해합니다.
# 중요 리소스
Source: https://docs.x.com/ko/enterprise-api/getting-started/important-resources
온보딩 가이드, 전담 계정 관리자, 지원 연락처, 상태 페이지, 공식 SDK와 샘플 코드를 포함한 X Enterprise API 고객을 위한 필수 리소스 모음입니다. 통합 준비부터 프로덕션 운영, 장애 대응까지 필요한 링크를 한곳에 모았습니다.
X API 개발을 위한 필수 리소스를 북마크하세요.
***
## 문서
매개변수와 예제가 포함된 완전한 엔드포인트 문서입니다.
게시물, 사용자, 미디어 등에 대한 객체 스키마입니다.
OAuth 1.0a 및 OAuth 2.0 구현 가이드입니다.
엔드포인트별 제한 및 모범 사례입니다.
***
## 도구
| 도구 | 설명 |
| :------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |
| [Developer Console](https://console.x.com) | 앱, 자격 증명 및 결제 관리 |
| [Postman Collection](https://www.postman.com/xapidevelopers/x-api-public-workspace/collection/34902927-2efc5689-99c6-4ab6-8091-996f35c2fd80) | 대화형 API 테스트 |
| [Python SDK](/xdks/python/overview) | 공식 Python 라이브러리 |
| [TypeScript SDK](/xdks/typescript/overview) | 공식 TypeScript 라이브러리 |
| [OpenAPI Spec](https://api.x.com/2/openapi.json) | 머신 판독 가능한 API 명세 |
***
## 학습
일반적인 사용 사례에 대한 단계별 가이드입니다.
예제 앱 및 코드 샘플입니다.
프로젝트에 대한 아이디어와 영감입니다.
v1.1에서 v2로 업그레이드하세요.
***
## 커뮤니티 및 지원
커뮤니티와 함께 질문하고 솔루션을 공유하세요.
FAQ, 문제 해결, 연락처 옵션입니다.
공식 업데이트 및 공지 사항입니다.
API 관련 뉴스 및 팁입니다.
***
## 최신 정보 받기
| 리소스 | 얻을 수 있는 것 |
| :------------------------------------------------------------------- | :------------------ |
| [Changelog](/changelog) | 모든 플랫폼 변경 사항 및 업데이트 |
| [Newsletter](/newsletter) | 뉴스 및 기능에 대한 월간 정리 |
| [Forum Announcements](https://devcommunity.x.com/c/announcements/22) | 중요한 플랫폼 공지 |
| [API Status](/status) | 실시간 서비스 가용성 |
[@XDevelopers](https://x.com/XDevelopers)를 팔로우하고 알림을 켜서 주요 변경 사항과 새로운 기능을 놓치지 마세요.
***
## 빠른 참조
### 응답 구조
모든 v2 응답은 다음 구조를 따릅니다:
```json theme={null}
{
"data": { ... }, // Primary object(s)
"includes": { ... }, // Expanded objects (if requested)
"meta": { ... }, // Pagination info
"errors": [ ... ] // Partial errors (if any)
}
```
### 일반적인 매개변수
| 매개변수 | 사용 |
| :----------------- | :------------- |
| `tweet.fields` | 특정 게시물 필드 요청 |
| `user.fields` | 특정 사용자 필드 요청 |
| `expansions` | 관련 객체 포함 |
| `max_results` | 페이지당 결과 제한 |
| `pagination_token` | 다음/이전 페이지 가져오기 |
### 인증 방법
| 방법 | 사용 사례 |
| :----------- | :------------------ |
| Bearer Token | 읽기 전용 공개 데이터 |
| OAuth 2.0 | 세분화된 스코프를 가진 사용자 작업 |
| OAuth 1.0a | 사용자 작업(레거시, 전체 권한) |
[전체 인증 가이드 →](/resources/fundamentals/authentication/overview)
# 첫 요청 보내기
Source: https://docs.x.com/ko/enterprise-api/getting-started/make-your-first-request
인증 설정, 엔드포인트 선택, 샘플 cURL 명령, 응답 처리 팁을 포함하여 첫 X Enterprise API 요청을 보내는 방법을 안내합니다. Basic authentication 자격 증명 준비부터 PowerTrack, Search API 호출 예제까지 단계별로 확인하세요.
이 가이드는 첫 X API 요청을 보내는 과정을 안내합니다. 시작하기 전에 [앱 자격 증명이 있는 개발자 계정](/x-api/getting-started/getting-access)이 필요합니다.
***
## cURL로 빠르게 시작하기
API를 테스트하는 가장 빠른 방법은 cURL입니다. 사용자를 조회해 봅시다:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
`$BEARER_TOKEN`을 실제 Bearer Token으로 바꾸세요. 다음과 같은 응답을 받게 됩니다:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## 단계별 가이드
[Developer Console](https://console.x.com)에서 앱으로 이동해 Bearer Token을 복사하세요.
다음 입문자 친화적인 엔드포인트 중 하나로 시작하세요:
| 엔드포인트 | 기능 |
| :------------------------------------------------ | :----------------------- |
| [User lookup](/x-api/users/lookup/introduction) | 사용자명 또는 ID로 사용자 프로필 가져오기 |
| [Post lookup](/x-api/posts/lookup/introduction) | ID로 게시물 가져오기 |
| [Recent search](/x-api/posts/search/introduction) | 최근 7일간의 게시물 검색 |
cURL, Postman 또는 선호하는 HTTP 클라이언트를 사용하세요:
```bash theme={null}
# Look up a user by username
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
응답은 JSON 형식입니다. 기본 데이터는 `data` 필드에 있습니다:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## fields로 더 많은 데이터 요청하기
기본적으로 엔드포인트는 최소한의 필드만 반환합니다. 추가 데이터를 요청하려면 `fields` 매개변수를 사용하세요:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers?user.fields=created_at,description,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
응답:
```json 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 Platform",
"public_metrics": {
"followers_count": 570842,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
[fields에 대해 자세히 알아보기 →](/x-api/fundamentals/fields)
***
## 더 많은 예제
```bash theme={null}
curl "https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=from:xdevelopers&tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/tweets?max_results=5" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## cURL 대신 코드 사용하기
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/users/by/username/xdevelopers"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers)
print(response.json())
```
```javascript theme={null}
const bearerToken = "YOUR_BEARER_TOKEN";
const url = "https://api.x.com/2/users/by/username/xdevelopers";
fetch(url, {
headers: { Authorization: `Bearer ${bearerToken}` }
})
.then(res => res.json())
.then(data => console.log(data));
```
프로덕션 환경에서는 공식 SDK 사용을 권장합니다:
* [Python SDK](/xdks/python/overview)
* [TypeScript SDK](/xdks/typescript/overview)
인증, 페이지네이션, 속도 제한을 자동으로 처리합니다.
***
## 테스트 도구
컬렉션으로 시각적 API 테스트를 수행합니다.
여러 언어로 된 예제입니다.
전체 엔드포인트 문서입니다.
***
## 문제 해결
* Bearer Token이 올바른지 확인하세요
* 토큰이 재발급되지 않았는지 확인하세요
* `Authorization` 헤더 형식을 확인하세요: `Bearer YOUR_TOKEN`
* 앱에 이 엔드포인트 액세스 권한이 없을 수 있습니다
* 일부 엔드포인트는 사용자 컨텍스트 인증(OAuth 1.0a 또는 2.0)이 필요합니다
* Developer Console에서 앱의 권한을 확인하세요
* 속도 제한에 도달했습니다
* 재시도 시점을 확인하려면 `x-rate-limit-reset` 헤더를 확인하세요
* 코드에 지수 백오프를 구현하세요
[전체 오류 레퍼런스 →](/x-api/fundamentals/response-codes-and-errors)
***
## 다음 단계
사용자 컨텍스트 요청을 위한 OAuth를 이해하세요.
무엇을 만들 수 있는지 알아보세요.
공식 라이브러리로 더 빠르게 개발하세요.
무엇을 만들지에 대한 아이디어입니다.
# Enterprise API 요금제와 맞춤형 플랜
Source: https://docs.x.com/ko/enterprise-api/getting-started/pricing
X Enterprise API 요금제는 조직의 데이터 볼륨, 사용 엔드포인트, SLA, 운영 지원 요구 사항에 맞춰 개별 설계됩니다. 대용량 데이터, 전용 액세스, 맞춤형 계약에 대한 가격 정보와 견적은 X 영업팀에 직접 문의하시기 바랍니다.
Enterprise 플랜은 조직의 요구사항에 맞게 맞춤형으로 제공됩니다. 전담 어카운트 팀과 협력하여 데이터 볼륨, 엔드포인트 사용, 지원 요구사항에 부합하는 패키지를 구성하세요.
***
## Enterprise 요금 작동 방식
데이터 볼륨, 엔드포인트 요구사항, 처리량 요구사항에 맞춰 가격이 책정됩니다.
장기 계약과 약정 사용량을 통해 예측 가능한 비용을 제공합니다.
사용량 기반 플랜의 월 200만 건 한도를 훨씬 넘어서는 맞춤형 또는 무제한 post 읽기 볼륨을 제공합니다.
모든 Enterprise 플랜에는 전담 어카운트 매니저와 우선 기술 지원이 포함됩니다.
***
## 포함된 기능
모든 Enterprise 플랜에는 전체 X API와 Enterprise 전용 엔드포인트가 포함됩니다:
| 기능 | 세부 정보 |
| :--------------------- | :------------------------------------------------------------------ |
| **모든 표준 엔드포인트** | 사용량 기반 X API에서 제공하는 모든 기능 |
| **Volume streams** | 전체 firehose 및 언어별 스트림 |
| **Likes streams** | 실시간 전체 및 샘플링된 likes |
| **Powerstream** | 고급 필터링 스트리밍 |
| **시맨틱 embedding 연산자** | Filtered Stream 전용 시맨틱 매칭을 위한 `embedding:` 연산자(Embedding 티어 액세스 필요) |
| **Engagement metrics** | Post 및 미디어 분석 엔드포인트 |
| **Account Activity** | 실시간 사용자 이벤트 구독 |
| **Stream webhooks** | 웹훅을 통한 필터링된 스트림 전송 |
| **맞춤형 rate limit** | 요구사항에 맞춘 상향된 한도 |
| **전담 지원** | 전담 어카운트 매니저 및 우선 문제 해결 |
***
## Enterprise vs. 사용량 기반
| | 사용량 기반 | Enterprise |
| :--------------------- | :---------------- | :------------------------------------------------------- |
| **요금 모델** | 크레딧 기반, 사용한 만큼 지불 | 맞춤형 계약 |
| **월 Post 한도** | 200만 건 읽기 | 맞춤형 / 무제한 |
| **Volume streams** | 제공되지 않음 | 전체 firehose 및 언어 스트림 |
| **Likes streams** | 제공되지 않음 | 전체 및 샘플링된 likes |
| **시맨틱 embedding 연산자** | 제공되지 않음 | Filtered Stream 전용 `embedding:` 연산자(Embedding 티어 액세스 필요) |
| **Engagement metrics** | 제공되지 않음 | Post 및 미디어 분석 |
| **Rate limits** | 표준 | 맞춤형 / 상향 |
| **지원** | 커뮤니티 포럼 | 전담 어카운트 매니저 |
| **약정** | 없음 | 계약 기반 |
***
## 사용량 모니터링
[Usage 엔드포인트](/x-api/usage/introduction)를 사용하여 API 사용량을 프로그래밍 방식으로 추적할 수 있습니다:
```bash theme={null}
curl "https://api.x.com/2/usage/tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
이는 일일 Post 소비량을 반환하여 다음과 같은 작업에 도움이 됩니다:
* 계약 한도 대비 소비량 추적
* 이해관계자를 위한 사용량 보고서 생성
* 소비량이 높은 엔드포인트 식별
* 어카운트 팀과 함께 용량 계획 수립
***
## 시작하기
[Enterprise 액세스를 신청](/forms/enterprise-api-interest)하고 사용 사례와 데이터 요구사항을 알려주세요.
영업팀이 요구사항과 예산에 맞는 패키지를 구성해 드립니다.
전담 어카운트 매니저가 자격 증명 설정, 액세스 구성 및 개발 시작을 도와드립니다.
***
## 다음 단계
영업팀에 문의하여 시작하세요.
사용량을 프로그래밍 방식으로 모니터링하세요.
# Enterprise API
Source: https://docs.x.com/ko/enterprise-api/introduction
전담 기술 지원과 맞춤형 가격으로 X firehose, Decahose 볼륨 스트림, 전체 아카이브 검색, PowerTrack, Account Activity API에 대한 엔터프라이즈급 액세스를 제공합니다. 대용량 실시간 데이터와 SLA 요구가 있는 팀을 위한 솔루션입니다.
X API Enterprise 플랜은 X 데이터에 대한 최고 수준의 액세스를 제공합니다. 전체 firehose 커버리지, 볼륨 스트림, Filtered Stream을 위한 semantic embedding 연산자, 전담 계정 관리, 대규모로 X 데이터에 의존하는 조직을 위해 설계된 맞춤형 속도 제한을 받으세요.
전담 계정 팀이 있는 Enterprise 액세스를 신청하세요.
Enterprise 전용 엔드포인트를 포함한 모든 사용 가능한 엔드포인트를 살펴보세요.
공식 Python 및 TypeScript 라이브러리입니다.
***
## Enterprise를 선택해야 하는 이유
Enterprise 액세스에는 사용량 기반 X API 플랜의 모든 기능과 함께 독점적인 대용량 엔드포인트, 전담 지원, 요구 사항에 맞춤화된 패키지가 포함됩니다.
100%의 공개 게시물을 실시간으로 스트리밍합니다. 샘플링 없음, 제한 없음. 모든 게시물을 발생하는 대로 받으세요.
영어, 일본어, 한국어, 포르투갈어 firehose를 포함한 전체 볼륨 및 언어별 스트림에 액세스합니다.
전담 계정 관리자, 맞춤형 기술 지원, 우선 문제 해결을 받으세요.
처리량 요구 사항에 맞는 더 높은 속도 제한과 맞춤형 패키지입니다.
대규모 데이터셋 전반에 걸친 심층 참여도 인사이트를 위해 게시물 및 미디어 분석 엔드포인트에 액세스합니다.
게시물, 사용자, 좋아요에 대한 실시간 컴플라이언스 이벤트 스트림으로 컴플라이언스를 유지하세요.
Filtered Stream에서 `embedding:` 연산자를 사용하여 키워드가 아닌 개념적 의미로 게시물을 매칭하세요(Embedding 티어 필요).
***
## Enterprise 전용 엔드포인트
이러한 엔드포인트는 Enterprise 플랜에서만 사용할 수 있습니다:
전체 firehose, 언어별 스트림, 샘플 스트림입니다.
모든 좋아요 또는 샘플 좋아요를 실시간으로 스트리밍합니다.
낮은 지연 시간의 고성능 필터링 스트리밍(키워드 연산자)입니다.
게시물 및 미디어 참여도에 대한 심층 분석입니다.
게시물, DM, 좋아요, 팔로우를 포함한 실시간 사용자 활동 이벤트를 구독합니다.
영구 연결 대신 webhook을 통해 filtered stream 데이터를 받습니다.
***
## 무엇을 만들 수 있나요
Enterprise 액세스는 X에서 가장 까다로운 사용 사례를 지원합니다.
게시물 검색, 조회, 게시. 타임라인, 스레드, 인용 게시물에 액세스합니다.
사용자를 조회하고 팔로우, 차단, 뮤트를 관리합니다.
라이브 오디오 대화와 참여자를 찾으세요.
비공개 메시지를 송수신합니다.
큐레이션된 계정 리스트를 만들고 관리합니다.
위치별 트렌드 주제에 액세스합니다.
***
## 주요 기능
### 완전한 실시간 커버리지
100%의 공개 게시물을 발생하는 대로 스트리밍하세요. 샘플링도, 누락도 없습니다. Enterprise firehose 액세스는 X의 공개 대화에 대한 완전한 그림을 제공합니다.
사용 가능한 스트림:
* **모든 게시물** - 모든 공개 게시물을 실시간으로
* **영어 게시물** - 모든 영어 게시물
* **일본어 게시물** - 모든 일본어 게시물
* **한국어 게시물** - 모든 한국어 게시물
* **포르투갈어 게시물** - 모든 포르투갈어 게시물
* **샘플 스트림** - 1% 및 10% 무작위 샘플
[볼륨 스트림에 대해 자세히 알아보기](/x-api/posts/volume-streams/introduction)
### 풍부한 데이터 객체
게시물, 사용자, 미디어 등에 대한 상세하고 구조화된 데이터에 액세스합니다:
* **게시물**: 전체 텍스트, 지표, 엔티티, 주석, 대화 스레드
* **사용자**: 프로필, 팔로워 수, 인증 상태
* **미디어**: 이미지, 비디오, 메타데이터가 있는 GIF
* **설문조사**: 옵션 및 투표 수
[fields](/x-api/fundamentals/fields) 및 [expansions](/x-api/fundamentals/expansions)로 응답을 맞춤 설정하여 필요한 데이터만 정확하게 받으세요.
### Filtered stream
게시물이 게시되는 대로 실시간으로 전달받으세요. Enterprise는 더 높은 규칙 제한과 의미(키워드가 아닌)로 게시물을 매칭하는 semantic `embedding:` 연산자(Filtered Stream 전용)를 추가합니다.
```bash theme={null}
# Add a rule
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $TOKEN" \
-d '{"add": [{"value": "from:xdevelopers"}]}'
# Connect to stream
curl "https://api.x.com/2/tweets/search/stream" \
-H "Authorization: Bearer $TOKEN"
```
[filtered stream에 대해 자세히 알아보기](/x-api/posts/filtered-stream/introduction)
### Full-archive search
2006년까지 거슬러 올라가는 공개 게시물의 전체 기록을 검색하세요. 사용자, 키워드, 날짜 등에 대한 연산자로 쿼리를 빌드하세요.
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?query=AI%20lang:en" \
-H "Authorization: Bearer $TOKEN"
```
### 참여도 지표
노출수, 좋아요, 리포스트, 답글, 비디오 조회수, 미디어 수준 지표를 포함한 심층 참여도 분석에 액세스합니다.
[검색에 대해 자세히 알아보기](/x-api/posts/search/introduction)
***
## Enterprise vs. 사용량 기반
| 기능 | 사용량 기반 | Enterprise |
| :------------------- | :----------- | :------------------------------------------------------------ |
| **게시물 검색** | 최근 및 전체 아카이브 | 최근 및 전체 아카이브 |
| **Filtered stream** | 최대 1,000개 규칙 | 5,000개 이상의 규칙 + semantic `embedding:` 연산자(Filtered Stream 전용) |
| **볼륨 스트림** | - | 전체 firehose 및 언어 스트림 |
| **Likes 스트림** | - | 전체 및 샘플 좋아요 |
| **Powerstream** | - | 고급 필터링 스트리밍 |
| **참여도 지표** | - | 게시물 및 미디어 분석 |
| **Account Activity** | - | 실시간 사용자 이벤트 구독 |
| **월별 게시물 상한** | 200만 읽기 | 맞춤형 / 무제한 |
| **속도 제한** | 표준 | 맞춤형 / 상향 |
| **지원** | 커뮤니티 포럼 | 전담 계정 관리자 |
***
## 시작하기
[영업팀에 문의](/forms/enterprise-api-interest)하여 요구 사항을 논의하고 맞춤형 패키지를 받으세요.
전담 계정 관리자가 자격 증명 설정 및 액세스 구성을 도와드립니다.
동일한 최신 v2 API 엔드포인트와 Enterprise 전용 엔드포인트를 통합에 사용하세요.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## 도구 & 라이브러리
비동기 지원이 있는 공식 Python 라이브러리입니다.
공식 TypeScript/JavaScript 라이브러리입니다.
대화형 API 탐색기입니다.
[모든 라이브러리 둘러보기](/tools-and-libraries)
***
## 지원
Enterprise 고객은 기술 및 계정 지원을 위한 전담 담당자를 받습니다.
커뮤니티와 X 팀의 도움을 받으세요.
# Ads API 액세스 양식
Source: https://docs.x.com/ko/forms/ads-api-access
X Ads API 액세스 신청 양식입니다. 사용 사례, 개발자 앱 정보, 회사 정보, 전환 API 활용 계획 등 필요한 세부 정보를 제출하여 X 담당 팀의 검토와 승인 절차를 거쳐 광고 데이터 접근과 Ads API 사용을 시작하세요.
# 결제 지원 양식
Source: https://docs.x.com/ko/forms/billing-support
청구서, 결제 수단, 구독 변경, 환불, 요금제 업그레이드 및 계정 관련 결제 문제에 대해 X API 결제 지원팀에 문의하세요.
Self-serve 및 Enterprise API 구독에 대한 결제 지원을 받으세요.
# Enterprise 액세스 양식
Source: https://docs.x.com/ko/forms/enterprise-api-interest
회사 정보, 사용 목적, 예상 데이터 볼륨 및 연락처 정보를 제출하여 X Enterprise API에 대한 액세스를 신청하세요.
# 정부 최종 사용자 요청 양식
Source: https://docs.x.com/ko/forms/government-end-user-request
정부 및 공공 부문에서 X API 액세스를 요청하기 위한 양식으로, 기관 정보, 사용 목적 및 컴플라이언스 정보를 제공합니다.
# OAuth API 레퍼런스 인덱스
Source: https://docs.x.com/ko/fundamentals/authentication/api-reference
OAuth 1.0a 및 OAuth 2.0에 걸친 X 인증 엔드포인트의 레퍼런스 인덱스로, 요청 토큰, 인증, 액세스 토큰, 토큰 취소를 포함합니다.
### OAuth 1.0a
| | |
| :------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------- |
| **목적** | 메서드 |
| 3-legged OAuth flow 및 Sign in with X의 1단계 Consumer 애플리케이션이 사용자 인증을 요청하기 위한 OAuth Request Token을 얻을 수 있게 합니다. | [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) |
| 3-legged OAuth flow 및 Sign in with X의 2단계 Consumer 애플리케이션이 사용자 인증을 요청하기 위해 OAuth Request Token을 사용할 수 있게 합니다. | [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) |
| 3-legged OAuth flow 및 Sign in with X의 2단계 Consumer 애플리케이션이 사용자 인증을 요청하기 위해 OAuth Request Token을 사용할 수 있게 합니다. | [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) |
| 3-legged OAuth flow 및 Sign in with X의 3단계 Consumer 애플리케이션이 OAuth Request Token을 OAuth Access Token으로 교환할 수 있게 합니다. | [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) |
| 등록된 애플리케이션이 발급된 OAuth Access Token을 취소할 수 있게 합니다. | [POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth-invalidate-token) |
### OAuth 2.0 Bearer Token
| | |
| :-------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
| **목적** | 메서드 |
| 등록된 App이 사용자 컨텍스트 없이 App을 대신하여 API 요청을 수행하는 데 사용할 수 있는 OAuth 2 app-only Bearer Token을 생성할 수 있게 합니다. | [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) |
| 등록된 App이 발급된 OAuth 2 app-only Bearer Token을 취소할 수 있게 합니다. | [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) |
### POST oauth/request\_token
Consumer 애플리케이션이 사용자 인증을 요청하기 위한 OAuth Request Token을 얻을 수 있게 합니다. 이 메서드는 [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9)의 [Section 6.1](https://oauth.net/core/1.0/#auth_step1)을 충족합니다.
**모든 OAuth 인증 단계에서 HTTPS 사용이 요구됩니다.**
**사용 참고사항:** `oauth_nonce`에는 ASCII 값만 허용됩니다.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/request_token`
**Resource 정보[](#resource-information "Permalink to this headline")**
| | |
| :----- | :--- |
| 응답 형식 | JSON |
| 인증 필요? | 아니요 |
| 속도 제한? | 예 |
**매개변수[](#parameters "Permalink to this headline")**
| 이름 | 필수 여부 | 설명 | 예시 |
| :-------------------- | :---- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------- |
| oauth\_callback | 필수 | OAuth 1.0a 규정 준수를 위해 이 매개변수는 **필수**입니다. 여기에 지정한 값은 사용자가 애플리케이션의 계정 액세스를 승인한 경우 리다이렉트될 URL로 사용됩니다. out-of-band pin 모드의 경우 `oob`로 설정하세요. 이는 데스크톱/모바일 애플리케이션에서 사용할 사용자 정의 콜백을 지정하는 방법이기도 합니다. 사전에 콜백을 등록했는지 여부와 관계없이 이 단계에서는 항상 `oauth_callback`을 보내십시오.
이 엔드포인트와 함께 사용되는 콜백 URL은 developer.x.com의 App 설정 내에서 구성되어야 합니다.\* | `http://themattharris.local/auth.php` `twitterclient://callback` |
| x\_auth\_access\_type | 선택 | 애플리케이션이 사용자 계정에 대해 요청하는 액세스 수준을 재정의합니다. 지원되는 값은 `read` 또는 `write`입니다. 이 매개변수는 개발자가 read/write 애플리케이션을 등록하되 적절한 경우 read only 액세스를 요청할 수 있도록 하기 위한 것입니다. | |
콜백 URL을 승인하는 방법은 [이 페이지](/resources/fundamentals/developer-apps#callback-urls)에서 자세히 알아보세요.
**참고** - developer.x.com에서 X 계정으로 로그인한 경우 [X 앱 대시보드](https://developer.x.com/en/apps)를 통해 기존 [X 앱](/resources/fundamentals/developer-apps)을 보고 편집할 수 있습니다.
**예시 요청[](#example-request "Permalink to this headline")**
요청 URL: `POST https://api.x.com/oauth/request_token`
요청 POST 본문: *해당 없음*
Authorization 헤더: `OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw", oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1300228849", oauth_consumer_key="OqEqJeafRSF11jBMStrZz", oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", oauth_version="1.0"`
응답: `oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik&oauth_token_secret=Kd75W4OQfb2oJTV0vzGzeXftVAwgMnEK9MumzYcM&oauth_callback_confirmed=true`
### GET oauth/authorize
Consumer 애플리케이션이 사용자 인증을 요청하기 위해 OAuth Request Token을 사용할 수 있게 합니다. 이 메서드는 [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9)의 [Section 6.2](http://oauth.net/core/1.0/#auth_step2)를 충족합니다. 데스크톱 애플리케이션은 이 메서드를 사용해야 하며 ([GET oauth / authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate)는 사용할 수 없습니다).
**사용 참고사항:** `oauth_callback`은 이 메서드에 절대 전송되지 않으며, 대신 [POST oauth / request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token)에 제공해야 합니다.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authorize`
**Resource 정보[](#resource-information "Permalink to this headline")**
| | |
| :----- | :--- |
| 응답 형식 | JSON |
| 인증 필요? | 예 |
| 속도 제한? | 예 |
**매개변수[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :---- | :------------------------------------------ | :-- | :- |
| 이름 | 필수 여부 | 설명 | 기본값 | 예시 |
| force\_login | 선택 | 사용자가 올바른 계정으로 인증되도록 자격 증명을 입력하도록 강제합니다. | | |
| screen\_name | 선택 | OAuth 로그인 화면의 사용자 이름 입력 상자에 지정된 값을 미리 채웁니다. | | |
**예시 요청[](#example-request "Permalink to this headline")**
oauth\_token 매개변수를 포함하여 웹 브라우저에서 `oauth/authorize` 단계로 사용자를 보내세요:
`https://api.x.com/oauth/authorize?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### GET oauth/authenticate
Consumer 애플리케이션이 사용자 인증을 요청하기 위해 OAuth `request_token`을 사용할 수 있게 합니다.
이 메서드는 콜백 인증 흐름을 사용하는 애플리케이션에 대한 [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9)의 [Section 6.2](http://oauth.net/core/1.0/#auth_step2)를 대체합니다. `force_login` 매개변수가 `true`로 설정되지 않은 한, 이 메서드는 현재 로그인한 사용자를 액세스 인증 계정으로 사용합니다.
이 메서드는 [GET oauth / authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize)와 달리, 사용자가 이미 애플리케이션 권한을 부여한 경우 사용자가 다시 애플리케이션을 승인하지 않고도 리다이렉트가 발생합니다. 이 동작을 구현하려면 [애플리케이션 레코드](https://developer.x.com/apps)에서 *Use Sign in with X* 설정을 활성화해야 합니다.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/authenticate`
**Resource 정보[](#resource-information "Permalink to this headline")**
| | |
| :----- | :--- |
| 응답 형식 | JSON |
| 인증 필요? | 예 |
| 속도 제한? | 예 |
**매개변수[](#parameters "Permalink to this headline")**
| | | | | |
| :----------- | :---- | :------------------------------------------ | :-- | :----- |
| 이름 | 필수 여부 | 설명 | 기본값 | 예시 |
| force\_login | 선택 | 사용자가 올바른 계정으로 인증되도록 자격 증명을 입력하도록 강제합니다. | | *true* |
| screen\_name | 선택 | OAuth 로그인 화면의 사용자 이름 입력 상자에 지정된 값을 미리 채웁니다. | | |
**예시 요청[](#example-request "Permalink to this headline")**
oauth\_token 매개변수를 포함하여 웹 브라우저에서 `oauth/authenticate` 단계로 사용자를 보내세요:
`https://api.x.com/oauth/authenticate?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik`
### POST oauth/access\_token
Consumer 애플리케이션이 OAuth Request Token을 OAuth Access Token으로 교환할 수 있게 합니다. 이 메서드는 [OAuth 1.0 authentication flow](http://oauth.net/core/1.0/#anchor9)의 [Section 6.3](http://oauth.net/core/1.0/#auth_step3)을 충족합니다.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth/access_token`
**Resource 정보[](#resource-information "Permalink to this headline")**
| | |
| :----- | :--- |
| 응답 형식 | JSON |
| 인증 필요? | 예 |
| 속도 제한? | 예 |
**매개변수[](#parameters "Permalink to this headline")**
| | | | | |
| :-------------- | :---- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-- | :- |
| 이름 | 필수 여부 | 설명 | 기본값 | 예시 |
| oauth\_token | 필수 | 여기의 oauth\_token은 request\_token 단계에서 반환된 oauth\_token과 동일해야 합니다. | | |
| oauth\_verifier | 필수 | OAuth web-flow를 사용하는 경우, 이 매개변수를 콜백 URL에 반환된 *oauth\_verifier* 값으로 설정하세요. out-of-band OAuth를 사용하는 경우 이 값을 pin-code로 설정하세요. OAuth 1.0a 규정 준수를 위해 이 매개변수는 **필수**입니다. OAuth 1.0a는 엄격하게 시행되며 \_oauth\_verifier\_를 사용하지 않는 애플리케이션은 OAuth 흐름을 완료하지 못합니다. | | |
**예시 요청[](#example-request "Permalink to this headline")**
`POST https://api.x.com/oauth/access_token?oauth_token=qLBVyoAAAAAAx72QAAATZxQWU6P&oauth_verifier=ghLM8lYmAxDbaqL912RZSRjCCEXKDIzx`
PIN 기반: `POST https://api.x.com/oauth/access_token?oauth_token=9Npq8AAAAAAAx72QBRABZ4DAfY9&oauth_verifier=4868795`
**예시 응답[](#example-response "Permalink to this headline")**
`oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG5ly3sR3XjE0IBSnlQu4ZrUzPiYTmrkVU&user_id=6253282&screen_name=xapi`
### POST oauth/invalidate\_token
등록된 애플리케이션이 클라이언트 자격 증명을 제시하여 발급된 OAuth access\_token을 취소할 수 있게 합니다. access\_token이 무효화되면 새 생성 시도에서 다른 Access Token이 생성되며 무효화된 토큰의 사용은 더 이상 허용되지 않습니다.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/1.1/oauth/invalidate_token`
**Resource 정보[](#resource-information "Permalink to this headline")**
| | |
| :----- | :--------------------------------- |
| 응답 형식 | JSON |
| 인증 필요? | 예 - 무효화하려는 액세스 토큰이 있는 User context |
| 속도 제한? | 예 |
**예시 요청[](#example-request "Permalink to this headline")**
```bash theme={null}
curl --request POST
--url 'https://api.x.com/1.1/oauth/invalidate_token.json'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**예시 응답[](#example-response "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 127
...
{"access_token":"ACCESS_TOKEN"}
```
**토큰이 무효화된 후 예시 오류 응답[](#example-error-response-after-token-has-been-invalidated "Permalink to this headline")**
```bash theme={null}
HTTP/1.1 401 Authorization Required
...
{"errors": [{
"code": 89,
"message": "Invalid or expired token."}
]}
```
### POST oauth2/token
등록된 애플리케이션이 사용자 컨텍스트 없이 애플리케이션 자체를 대신하여 API 요청을 수행하는 데 사용할 수 있는 OAuth 2 Bearer Token을 얻을 수 있게 합니다. 이를 [Application-only authentication](/resources/fundamentals/authentication/oauth-2-0/application-only)이라고 합니다.
Bearer Token은 oauth2/invalidate\_token을 사용하여 무효화할 수 있습니다. Bearer Token이 무효화되면 새 생성 시도에서 다른 Bearer Token이 생성되며 이전 토큰의 사용은 더 이상 허용되지 않습니다.
애플리케이션당 하나의 bearer token만 미해결 상태로 존재할 수 있으며, 이 메서드에 반복적으로 요청하면 무효화될 때까지 이미 존재하는 동일한 토큰이 생성됩니다.
성공 응답에는 부여된 Bearer Token을 설명하는 JSON 구조가 포함됩니다.
이 메서드로 받은 토큰은 캐시되어야 합니다. 너무 자주 시도하면 요청이 code 99와 함께 HTTP 403으로 거부됩니다.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/token`
**Resource 정보[](#resource-information "Permalink to this headline")**
| | |
| :----- | :---------------------------------------------------- |
| 응답 형식 | JSON |
| 인증 필요? | 예 - API 키를 사용자 이름으로, API 키 시크릿을 비밀번호로 사용하는 Basic auth |
| 속도 제한? | 예 |
**매개변수[](#parameters "Permalink to this headline")**
| | | | | |
| :---------- | :---- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-- | :-------------------- |
| 이름 | 필수 여부 | 설명 | 기본값 | 예시 |
| grant\_type | 필수 | 애플리케이션이 요청하는 grant 유형을 지정합니다. 현재는 \_client\_credentials\_만 허용됩니다. 자세한 내용은 [Application-Only Authentication](/resources/fundamentals/authentication/oauth-2-0/application-only)을 참조하세요. | | *client\_credentials* |
**예시 요청[](#example-request "Permalink to this headline")**
```bash theme={null}
POST /oauth2/token HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=client_credentials
```
**예시 응답:**
```bash theme={null}
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
```
### POST oauth2/invalidate\_token
등록된 애플리케이션이 클라이언트 자격 증명을 제시하여 발급된 oAuth 2.0 Bearer Token을 취소할 수 있게 합니다. Bearer Token이 무효화되면 새 생성 시도에서 다른 Bearer Token이 생성되며 무효화된 토큰의 사용은 더 이상 허용되지 않습니다.
성공 응답에는 취소된 Bearer Token을 설명하는 JSON 구조가 포함됩니다.
**Resource URL[](#resource-url "Permalink to this headline")**
`https://api.x.com/oauth2/invalidate_token`
**Resource 정보[](#resource-information "Permalink to this headline")**
| | |
| :----- | :-------------------------------------------------------------------------------------------------------------------------------- |
| 응답 형식 | JSON |
| 인증 필요? | 예 - 애플리케이션의 consumer API 키와 애플리케이션 소유자의 액세스 토큰 및 액세스 토큰 시크릿을 사용하는 [oAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a) |
| 속도 제한? | 예 |
**매개변수[](#parameters "Permalink to this headline")**
| 이름 | 필수 여부 | 설명 |
| :------------ | :---- | :--------------------- |
| access\_token | 필수 | 무효화하려는 bearer token의 값 |
**예시 요청[](#example-request "Permalink to this headline")**
```
curl --request POST
--url 'https://api.x.com/oauth2/invalidate_token?access_token=AAAA%2FAAA%3DAAAAAAAA'
--header 'authorization: OAuth oauth_consumer_key="CLIENT_KEY",
oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP",
oauth_token="ACCESS_TOKEN", oauth_version="1.0"'
```
**예시 응답[](#example-response "Permalink to this headline")**
```
Status: 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 135
...
{
"access_token": "AAAA%2FAAA%3DAAAAAAAA"
}
```
# Basic authentication
Source: https://docs.x.com/ko/fundamentals/authentication/basic-auth
HTTP Basic authentication을 사용하여 PowerTrack, Decahose, 전체 아카이브 Search 같은 X 엔터프라이즈 API에 HTTPS를 통해 이메일과 비밀번호를 전송하여 액세스하는 방법과 자격 증명 안전한 저장, 헤더 구성 예제를 안내합니다.
## Basic authentication
X의 많은 엔터프라이즈 API는 HTTP Basic Authentication 사용을 요구합니다. Basic Authentication이 필요한 API에 성공적으로 요청을 보내려면 유효한 이메일 주소와 비밀번호 조합을 각 요청의 인증 헤더로 전달해야 합니다. 이 이메일과 비밀번호 조합은 [엔터프라이즈 API 콘솔](https://console.gnip.com/)에 액세스할 때 사용하는 것과 동일하며 이 콘솔 내에서 편집할 수 있습니다.
Basic Authentication을 사용해 요청을 빌드할 때는 HTTPS를 통해 인코딩된 자격 증명과 함께 Authentication: Basic HTTP 헤더를 추가하세요.
다음 cURL 요청 예시에서는 요청을 보내기 전에 ``와 ``를 자격 증명으로 교체합니다:
```bash theme={null}
curl -v --compressed -u:
"https://gnip-api.x.com/search/30day/accounts//prod/counts.json?query=from%3Axdevelopers"
```
**basic authentication이 필요한 API:**
* [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) enterprise
* [Decahose stream API](http://localhost:3000/x-api/enterprise-gnip-2.0/fundamentals/decahose-api) enterprise
* [30-Day Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Full-Archive Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) enterprise
* [Usage API](/x-api/enterprise-gnip-2.0/fundamentals/usage) enterprise
# OAuth FAQ
Source: https://docs.x.com/ko/fundamentals/authentication/faq
X API 작업 시 OAuth 1.0a와 OAuth 2.0의 차이, 액세스 토큰과 refresh token, 권한 스코프, PKCE, bearer token, 콜백 URL 및 인증 오류 해결에 대한 개발자들의 일반적인 질문에 답하는 FAQ입니다.
## 일반
OAuth는 사용자가 비밀번호를 공유하지 않고도 애플리케이션이 자신을 대신해 행동하도록 승인할 수 있는 인증 프로토콜입니다. 자세한 정보는 [oauth.net](http://oauth.net/)에서 확인할 수 있습니다.
액세스 토큰을 생성하려면 [X 앱](/resources/fundamentals/developer-apps)이 있어야 합니다. 액세스 토큰에 대해 [여기](/resources/fundamentals/authentication#oauth-1-0a-2)에서 자세히 알아보세요.
[X 앱](/resources/fundamentals/developer-apps)을 만들려면 [개발자 계정](/resources/fundamentals/developer-portal)이 있어야 합니다. [여기](https://developer.x.com/en/portal/petition/essential/basic-info)에서 가입할 수 있습니다.
developer.x.com에서 X 계정에 로그인한 상태이면 [X 앱 대시보드](https://developer.x.com/content/developer-twitter/en/apps)에서 앱을 보고 편집할 수 있습니다.
## 기술
액세스 토큰은 명시적으로 만료되지 않습니다. 사용자가 X 계정 설정에서 애플리케이션을 명시적으로 취소하거나 X가 애플리케이션을 정지하면 액세스 토큰이 무효화됩니다. 애플리케이션이 정지된 경우 [X 앱](/resources/fundamentals/developer-apps) 대시보드에 정지되었음을 알리는 메모가 표시됩니다.
사용자의 액세스 토큰은 *언제든지* 무효화될 수 있다고 가정하세요. 이런 일이 발생하면 사용자에게 애플리케이션을 다시 승인하도록 안내하세요. 이러한 상황을 우아하게 처리하는 것은 좋은 사용자 경험을 위해 중요합니다.
많은 사용자가 애플리케이션이 자신의 정보를 읽는 것은 신뢰하지만 사용자 프로필 정보를 변경하거나 새 상태를 게시하는 것은 반드시 그렇지 않습니다. X API를 통해 정보를 업데이트하는 것 — 이름, 위치 또는 새 상태 추가 — 은 HTTP POST가 필요합니다. HTTP POST가 필요한 모든 API 메서드는 쓰기 메서드로 간주되며 읽기 & 쓰기 액세스가 필요합니다.
# 모범 사례
Source: https://docs.x.com/ko/fundamentals/authentication/guides/authentication-best-practices
API 키와 토큰은 매우 신중하게 보호해야 합니다. 이 자격 증명은 개발자 App과 이를 승인한 X 계정에 직접 연결되어 있습니다.
API 키와 토큰은 매우 신중하게 보호해야 합니다.
이러한 자격 증명은 [개발자 App](/resources/fundamentals/developer-apps) 및 개발자를 대신하여 요청을 보낼 수 있도록 승인한 X 계정에 직접 연결되어 있습니다. 키가 유출되면 악의적인 행위자가 이를 사용하여 개발자 App 또는 승인된 사용자를 대신하여 X 엔드포인트에 요청할 수 있으며, 이는 예상치 못한 rate limit에 도달하거나, 유료 액세스 할당량을 소진하거나, 심지어 개발자 App이 정지될 수 있음을 의미합니다.
다음 섹션에는 API 키와 토큰을 관리할 때 고려해야 할 모범 사례가 포함되어 있습니다.
## API 키 및 토큰 재생성
API 키가 노출되었다고 판단되는 경우, 다음 단계에 따라 API 키를 재생성해야 합니다:
1. [Developer Console의 "Apps" 페이지](https://developer.x.com/en/portal/projects-and-apps.html)로 이동합니다.
2. 해당 App 옆에 있는 "Keys and tokens" 아이콘(🗝)을 클릭합니다.
3. 재생성하려는 키 및 토큰 세트 옆에 있는 "Regenerate" 버튼을 클릭합니다.
Access Token 또는 Bearer Token을 프로그래밍 방식으로 재생성하려면 인증 엔드포인트를 사용할 수 있습니다.
* Access Token을 재생성하려면 [POST oauth/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) 엔드포인트를 사용하여 토큰을 무효화한 다음 [3-legged OAuth flow](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)를 사용하여 토큰을 재생성해야 합니다.
* Bearer Token을 재생성하려면 [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) 엔드포인트를 사용하여 토큰을 무효화한 다음 [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) 엔드포인트를 사용하여 토큰을 재생성해야 합니다.
## 시크릿을 위한 중앙 파일 사용
시크릿을 포함하기 위해 .ENV 파일이나 다른 종류의 .yaml 파일을 사용하는 것은 도움이 될 수 있는 옵션이지만, 이러한 파일을 실수로 git 저장소에 커밋하는 것을 방지하는 강력한 .gitignore 파일을 반드시 준비해야 합니다.
## 환경 변수
환경 변수를 활용하는 코드를 작성하는 것이 도움이 될 수 있습니다.
다음은 Python으로 작성된 예제입니다:
```python theme={null}
import os
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")
```
터미널 내에서 다음과 같이 작성하시면 됩니다:
```bash theme={null}
export CONSUMER_KEY='xxxxxxxxxxxxxxxxxxx'
export CONSUMER_SECRET='xxxxxxxxxxxxxxxxxxxxxxx'
```
## 소스 코드 및 버전 관리
개발자가 가장 흔하게 저지르는 보안 실수는 GitHub 및 BitBucket과 같이 접근 가능한 버전 관리 시스템의 소스 코드에 API 키와 토큰을 커밋하는 것입니다. 이러한 코드 저장소 중 상당수는 공개적으로 접근 가능합니다. 이 실수는 공개 코드 저장소에서 매우 자주 발생하기 때문에 API 키를 스크레이핑하는 수익성 있는 봇이 존재할 정도입니다.
* 서버 환경 변수를 사용하세요. API 키를 환경 변수에 저장하면 코드와 버전 관리에서 제외됩니다. 또한 환경별로 서로 다른 키를 쉽게 사용할 수 있습니다.
* 소스 관리에서 제외된 구성 파일을 사용하세요. 파일 이름을 [.gitignore](https://git-scm.com/docs/gitignore) 파일에 추가하여 파일이 버전 관리에 의해 추적되지 않도록 하세요.
* 버전 관리를 사용한 후 코드에서 API 키를 제거하더라도, 이전 버전의 코드베이스에 액세스하여 API 키에 접근할 수 있을 가능성이 큽니다. 다음 섹션에서 설명한 대로 API 키를 재생성하세요.
## 데이터베이스
액세스 토큰을 데이터베이스에 저장해야 하는 경우 다음 사항에 유의하세요:
* 액세스 토큰이 토큰 소유자만 읽을 수 있도록 데이터베이스에 대한 액세스를 제한하세요.
* 액세스 토큰용 데이터베이스 테이블에 대한 편집/쓰기 권한을 제한하세요 - 이는 키 관리 시스템으로 자동화되어야 합니다.
* 데이터 저장소에 저장하기 전에 액세스 토큰을 암호화하세요.
## 비밀번호 관리 도구
1password 또는 Last Pass와 같은 비밀번호 관리 도구는 키와 토큰을 안전한 장소에 보관하는 데 도움이 될 수 있습니다. 팀 공유 비밀번호 관리 도구 내에서 이를 공유하는 것은 피하는 것이 좋습니다.
## 웹 스토리지 및 쿠키
웹 스토리지에는 LocalStorage와 SessionStorage 두 가지 유형이 있습니다. 이는 쿠키 저장소보다 웹 스토리지의 저장 용량이 훨씬 크기 때문에 쿠키 사용에 대한 개선책으로 만들어졌습니다. 그러나 각 스토리지 옵션에는 서로 다른 장단점이 있습니다.
**웹 스토리지: LocalStorage**
로컬 웹 스토리지에 저장된 모든 것은 영구적입니다. 이는 데이터가 명시적으로 삭제될 때까지 지속됨을 의미합니다. 프로젝트의 필요에 따라 이를 긍정적으로 볼 수도 있습니다. 그러나 데이터에 대한 모든 변경/추가가 해당 웹페이지의 향후 방문 시 사용 가능하기 때문에 LocalStorage 사용에 주의해야 합니다. 일반적으로 LocalStorage 사용을 권장하지 않지만 몇 가지 예외가 있을 수 있습니다. LocalStorage를 사용하기로 결정한 경우, 동일 출처 정책을 지원하므로 여기에 저장된 모든 데이터는 동일한 출처를 통해서만 사용할 수 있다는 점을 알아두면 좋습니다. LocalStorage 사용의 추가적인 성능 이점은 모든 HTTP 요청에 대해 데이터를 서버로 다시 보낼 필요가 없기 때문에 클라이언트-서버 트래픽이 감소한다는 것입니다.
**웹 스토리지: SessionStorage**
SessionStorage는 LocalStorage와 유사하지만, 주요 차이점은 SessionStorage가 영구적이지 않다는 점입니다. SessionStorage에 쓰기 위해 사용된 창(사용 중인 브라우저에 따라 탭)이 닫히면 데이터가 손실됩니다. 이는 사용자 세션 내에서 토큰에 대한 읽기 액세스를 제한하는 데 유용합니다. 보안 측면에서 생각할 때 SessionStorage를 사용하는 것이 일반적으로 LocalStorage보다 더 바람직합니다. LocalStorage와 마찬가지로 동일 출처 정책 지원 및 클라이언트-서버 트래픽 감소의 이점이 SessionStorage에도 적용됩니다.
**쿠키**
쿠키는 세션 데이터를 저장하는 보다 전통적인 방법입니다. 각 쿠키에 대해 만료 시간을 설정할 수 있으므로 취소 및 액세스 제한이 용이합니다. 그러나 데이터가 모든 HTTP 요청에 대해 서버로 다시 전송되기 때문에 쿠키를 사용하면 클라이언트-서버 트래픽이 확실히 증가합니다. 쿠키를 사용하기로 결정한 경우 세션 하이재킹으로부터 보호해야 합니다. 기본적으로 쿠키는 HTTP를 통해 일반 텍스트로 전송되며, 이로 인해 패킷 스니핑 및/또는 공격자가 트래픽을 수정할 수 있는 중간자 공격에 그 내용이 취약해집니다. 데이터를 전송 중에 보호하려면 항상 HTTPS를 적용해야 합니다. 이는 기밀성, (데이터의) 무결성 및 인증을 제공합니다. 그러나 웹 애플리케이션이나 사이트가 HTTP와 HTTPS 모두를 통해 사용 가능한 경우 쿠키에 'Secure' 플래그도 사용하는 것이 좋습니다. 이렇게 하면 공격자가 사용자에게 사이트의 HTTP 버전 링크를 보내고 결과 HTTP 요청을 도청하는 것을 방지할 수 있습니다.
쿠키를 사용할 때 세션 하이재킹에 대한 또 다른 보조 방어책은 영향력이 큰 작업이 수행되기 전에 사용자의 신원을 다시 확인하는 것입니다. 쿠키의 보안을 개선하기 위해 고려해야 할 또 다른 플래그는 'HttpOnly' 플래그입니다. 이 플래그는 브라우저에 해당 쿠키가 지정된 서버에서만 액세스 가능하도록 지시합니다. 클라이언트 측 스크립트의 모든 시도는 이 플래그에 의해 금지되므로 대부분의 크로스 사이트 스크립팅(XSS) 공격으로부터 보호하는 데 도움이 됩니다.
# X로 로그인
Source: https://docs.x.com/ko/fundamentals/authentication/guides/log-in-with-x
OAuth 1.0a request token 흐름을 사용하여 웹사이트와 모바일 앱에서 Sign in with X를 구현하고 사용자를 인증하여 액세스 토큰을 얻습니다.
Sign in with X라고도 알려진 Log in with X를 사용하면 X 사용자가 단 한 번의 클릭만으로 등록된 사용자 계정의 혜택을 누릴 수 있는 버튼을 사이트나 애플리케이션에 배치할 수 있습니다. 이는 웹사이트, iOS, 모바일 및 데스크톱 애플리케이션에서 작동합니다.
## 기능
* 사용 편의성 - 사이트를 처음 방문한 방문자는 처음 로그인하기 위해 두 번의 버튼 클릭만 하면 됩니다.
* X 통합 - Log in with X 흐름은 사용자를 대신하여 X API를 사용할 수 있는 권한을 부여할 수 있습니다.
* OAuth 기반 - 다양한 클라이언트 라이브러리와 예제 코드가 Log in with X API와 호환됩니다.
## 사용 가능 대상
* 브라우저 - 사용자가 브라우저에 접근할 수 있다면 Log in with X와 통합할 수 있습니다. 브라우저 로그인 흐름에 대해 알아보세요.
* 모바일 기기 - 웹에 연결된 모든 모바일 기기에서 Log in with X를 활용할 수 있습니다. 모바일 로그인 흐름에 대해 알아보세요.
## Log in with X 구현하기
Log in with X의 브라우저 및 모바일 웹 구현은 OAuth를 기반으로 합니다. 이 페이지는 로그인 흐름을 위한 액세스 토큰을 얻는 데 필요한 요청을 보여줍니다.
"Log in with X" 흐름을 사용하려면 [X 앱 설정](/resources/fundamentals/developer-apps)으로 이동하여 *"Allow this app to be used to Sign in with X?"* 옵션이 활성화되어 있는지 확인하세요.
이 페이지는 독자가 OAuth 1.0a 프로토콜을 사용하여 요청에 서명하는 방법을 알고 있다고 가정합니다. 요청에 서명하는 방법을 알고 싶으면 [요청 승인](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request) 페이지를 읽어보세요.
이 페이지의 요청 서명을 확인하려면 사용된 consumer secret은 다음과 같습니다: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg. 이 값은 테스트 목적이며 실제 요청에는 작동하지 않습니다.
request token 얻기, 사용자 리다이렉트, request token을 access token으로 변환하기를 통해 Log in with X를 구현하는 세 단계는 아래와 같습니다.
### 1단계: request token 얻기
로그인 흐름을 시작하려면 [X 앱](/resources/fundamentals/developer-apps)이 [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token)에 서명된 메시지를 보내 request token을 얻어야 합니다. 이 요청에서 유일한 매개변수는 oauth\_callback이며, 이는 사용자가 2단계를 완료할 때 리다이렉트되기를 원하는 URL의 URL 인코딩된 버전이어야 합니다. 나머지 매개변수는 OAuth 서명 프로세스에 의해 추가됩니다.
**참고:** [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) 엔드포인트와 함께 사용하는 [콜백 URL](/resources/fundamentals/developer-apps#callback-urls)은 [Developer Console](/resources/fundamentals/developer-portal)의 [X 앱 설정](/resources/fundamentals/developer-apps) 내에 등록되어야 합니다.
**예시 요청 (Authorization 헤더는 줄바꿈되어 있습니다):**
```
POST /oauth/request_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization:
OAuth oauth_callback="http%3A%2F%2Flocalhost%2Fsign-in-with-twitter%2F",
oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="ea9ec8429b68d6b77cd5600adbbb0456",
oauth_signature="F1Li3tvehgcraF8DMJ7OyxO4w9Y%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_version="1.0"
```
앱은 응답의 HTTP 상태를 확인해야 합니다. 200 이외의 값은 실패를 나타냅니다. 응답 본문에는 oauth\_token, oauth\_token\_secret 및 oauth\_callback\_confirmed 매개변수가 포함됩니다. 앱은 oauth\_callback\_confirmed가 true인지 확인하고 나머지 두 값을 다음 단계에서 사용하기 위해 저장해야 합니다.
**예시 응답 (응답 본문은 줄바꿈되어 있습니다):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:06 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 146
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI&
oauth_callback_confirmed=true
```
### 2단계: 사용자 리다이렉트
다음 단계는 아래 Browser sign-in flow에 설명된 대로 사용자가 적절한 흐름을 완료할 수 있도록 X로 사용자를 안내하는 것입니다. 사용자를 [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate)로 안내하고, 1단계에서 얻은 request token은 oauth\_token 매개변수로 전달되어야 합니다.
웹사이트에서 이를 구현하는 가장 매끄러운 방법은 원래의 "로그인" 요청에 대한 응답으로 HTTP 302 리다이렉트를 발행하는 것입니다. 모바일 및 데스크톱 앱은 새 브라우저 창을 열거나 임베디드 웹 뷰를 통해 URL로 안내해야 합니다.
**리다이렉트할 예시 URL:**
[https://api.x.com/oauth/authenticate?oauth\_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0](https://api.x.com/oauth/authenticate?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0)
로그인 엔드포인트는 사용자의 상태에 따라 다음 세 가지 방식 중 하나로 동작합니다:
1. **로그인되어 있고 승인됨**: 사용자가 x.com에 로그인되어 있고 이미 호출 애플리케이션을 승인한 경우, 즉시 인증되어 유효한 OAuth request token과 함께 콜백 URL로 반환됩니다. x.com으로의 리다이렉트는 사용자에게 명확하게 표시되지 않습니다.
2. **로그인되어 있지만 승인되지 않음**: 사용자가 x.com에 로그인되어 있지만 호출 애플리케이션을 승인하지 않은 경우, 호출 애플리케이션과 액세스를 공유하는 요청이 표시됩니다. 인증 요청을 수락한 후 사용자는 유효한 OAuth request token과 함께 콜백 URL로 리다이렉트됩니다.
3. **로그인되어 있지 않음**: 사용자가 x.com에 로그인되어 있지 않은 경우, 동일한 화면에서 자격 증명을 입력하고 애플리케이션이 정보에 액세스할 수 있는 권한을 부여하도록 요청됩니다. 로그인하면 사용자는 유효한 OAuth request token과 함께 콜백 URL로 반환됩니다.
인증에 성공하면 callback\_url은 oauth\_token과 oauth\_verifier 매개변수를 포함한 요청을 받게 됩니다. 애플리케이션은 토큰이 1단계에서 받은 request token과 일치하는지 확인해야 합니다.
**클라이언트의 리다이렉트에서 온 요청 (쿼리스트링 매개변수는 줄바꿈되어 있음):**
```
GET /sign-in-with-twitter/?
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.5 (KHTML, like Gecko) Chrome/16.0.891.1 Safari/535.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://localhost/sign-in-with-twitter/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
```
### 3단계: request token을 access token으로 변환
request token을 사용 가능한 access token으로 렌더링하려면 애플리케이션이 2단계에서 얻은 oauth\_verifier 값을 포함하여 [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) 엔드포인트에 요청해야 합니다. request token 역시 헤더의 oauth\_token 부분에 전달되지만, 이는 서명 프로세스에 의해 추가됩니다.
**예시 요청 (Authorization 헤더 줄바꿈됨):**
```
POST /oauth/access_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.x.com
Accept: */*
Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
oauth_version="1.0"
Content-Length: 57
Content-Type: application/x-www-form-urlencoded
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
```
성공 응답에는 oauth\_token과 oauth\_token\_secret 매개변수가 포함됩니다. 토큰과 토큰 시크릿은 저장되어 X API에 대한 향후 인증된 요청에 사용되어야 합니다. 사용자의 신원을 확인하려면 [GET account/verify\_credentials](https://dev.x.com/rest/reference/get/account/verify_credentials)를 사용하세요.
**예시 응답 (응답 본문은 줄바꿈되어 있습니다):**
```
HTTP/1.1 200 OK
Date: Thu, 13 Oct 2011 00:57:08 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 157
Pragma: no-cache
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Vary: Accept-Encoding
Server: tfe
oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4&
oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo
```
### Log in with X 리소스
#### 클라이언트 라이브러리
[X 라이브러리](/resources/tools-and-libraries)에 나열된 클라이언트 라이브러리는 Log in with X 구현에 도움이 됩니다. 이전 단계에서 설명한 대로 /oauth/authenticate 엔드포인트를 사용하세요.
#### Brand Toolkit
X는 애플리케이션이 일관된 브랜딩을 위해 공식 [X Brand Toolkit](https://about.x.com/en/who-we-are/brand-toolkit)을 사용하는 것을 선호합니다. 이러한 자산을 저장하고 'Login with X' 버튼을 만들 때 사용하세요.
브라우저 로그인 흐름은 웹 브라우저를 열거나 임베드할 수 있는 웹사이트와 애플리케이션에 적합합니다. 매우 상위 수준에서:
* 애플리케이션은 "Sign in with X" 링크 또는 버튼을 렌더링합니다.
* 사용자가 로그인 버튼을 클릭합니다.
* 현재 웹 브라우저가 X로 리다이렉트됩니다(또는 새 브라우저가 열리고 X로 안내됩니다).
* 필요한 경우 사용자는 X에서 로그인 및 인증 단계를 완료합니다.
* X는 사용자의 인증 정보를 전달하며 애플리케이션이 제어하는 URL로 다시 리다이렉트됩니다.
X는 인증을 추적하므로, 이미 X.com에 로그인되어 애플리케이션을 승인한 사용자에게는 UI가 표시되지 않습니다 - 대신 자동으로 애플리케이션으로 리다이렉트됩니다.
### 데스크톱 흐름
흐름을 설명하기 위해 위에 표시된 웹사이트("The greatest website ever created")가 이 API를 구현했다고 가정합니다. 랜딩 페이지의 Sign in with X 버튼이 그것을 보여줍니다.
사용자가 Sign in 버튼을 클릭하면 표시되는 페이지는 로그인 여부와 이전에 애플리케이션이 계정에 액세스하는 것을 허용했는지 여부에 따라 달라집니다.
사용자가 x.com에 로그인했지만 액세스 권한을 부여하지 않은 경우, 요청된 권한 목록과 Sign In 및 Cancel 버튼이 표시됩니다.
사용자가 x.com에 로그인하지 않은 경우 사용자 이름과 비밀번호에 대한 입력 필드가 표시됩니다. 사용자가 이미 애플리케이션에 액세스 권한을 부여한 경우에도 권한 목록은 여전히 표시됩니다.
사용자가 유효한 자격 증명(필요한 경우)을 입력하고 "Sign In"을 클릭하면, X는 로그인 흐름을 시작한 웹사이트로 사용자를 리다이렉트합니다.
사용자가 이미 x.com에 로그인되어 있고 웹사이트에 액세스 권한을 부여한 경우, 이 리다이렉트는 즉시 발생합니다.
모바일 웹 브라우저의 UI 흐름은 Browser sign in flow와 정확히 동일하게 작동하지만 모바일 브라우저에 최적화되어 있습니다.
아래는 로그인, 로그아웃 및 리다이렉트 화면의 스크린샷입니다:
# TLS를 사용한 X API 연결
Source: https://docs.x.com/ko/fundamentals/authentication/guides/tls
TLS 1.2를 통해 X API에 안전하게 연결하는 방법과 신뢰할 수 있는 루트 스토어, 인증서 취소 확인, HTTPS 검증 관행에 대한 가이드입니다.
X API 엔드포인트에 액세스하려면 TLS 연결이 필요합니다. TLS를 통한 통신은 정보가 공용 인터넷을 이동할 때 사용자와 X API 간의 정보를 보호함으로써 사용자의 개인 정보와 보안을 유지합니다. X API 연결에는 TLS 버전 1.2가 필요합니다.
## 검증
### 최신 루트 스토어 사용
애플리케이션이나 라이브러리가 X 인증서를 검증할 때 신뢰할 수 있고 최신인 루트 스토어를 사용하는 것이 중요합니다. 가능하다면 운영 체제에서 제공하는 루트 스토어를 사용하는 것이 가장 간단한 접근 방식일 수 있습니다. 또는 [Mozilla (NSS) 루트 스토어](https://www.mozilla.org/en-US/about/governance/policies/security-group/certs/)는 공개적이고 투명한 방식으로 잘 유지 관리되고 있습니다. Curl 역시 [PEM 형식으로 된 버전](https://curl.haxx.se/docs/caextract.html)을 제공합니다.
X는 현재 대부분의 인증서를 [DigiCert High Assurance EV Root CA](https://www.digicert.com/digicert-root-certificates.htm)에서 발급받지만, X와 관련된 100%의 인증서가 그런 것은 아니며 앞으로도 계속 그럴 것이라고 보장할 수 없습니다. 따라서 현재 사용되는 Digicert 루트만 신뢰하면 향후 앱에 문제가 발생할 수 있습니다.
### CRL 및 OCSP 상태 확인[](#check-crls-and-the-ocsp-status "Permalink to this headline")
많은 애플리케이션이 반환된 인증서에 대해 인증서 취소 목록(Certificate Revocation List)을 확인하지 않거나 운영 체제에 이 작업을 맡깁니다. X의 인증서를 수락하기 전에 애플리케이션이나 TLS 라이브러리가 CRL 및 OCSP(Online Certificate Status Protocol) 검증을 강제하도록 구성되어 있는지 확인하세요.
### CDN[](#cdns "Permalink to this headline")
미디어가 포함된 Tweet을 표시할 때는 이미지를 표시할 때 사용할 HTTPS URL로 `media_url_https` 속성을 사용하세요. 향후 API 엔드포인트에서 제공되는 모든 URL은 HTTPS 경로를 제공하게 될 것입니다.
## 보안 상태 표시 제공
가능하다면 애플리케이션과 X 사이의 현재 상태를 나타내는 표시를 표시해야 합니다. 일부 웹 브라우저는 자물쇠 아이콘을 제공하여 이를 나타내며, 다른 브라우저는 설명 메시지와 함께 현재 연결 상태를 나타냅니다.
# X API v2 인증 매핑
Source: https://docs.x.com/ko/fundamentals/authentication/guides/v2-authentication-mapping
다음 차트는 어떤 v2 엔드포인트가 어떤 인증 방법에 매핑되는지 보여줍니다. v2 인증을 다루는 X 개발자 플랫폼 문서입니다.
다음 차트는 어떤 v2 엔드포인트가 어떤 인증 방법에 매핑되는지 보여줍니다.
| | | | |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **엔드포인트** | **OAuth 1.0a User Context** | **OAuth 2.0** **App Only ** | **OAuth 2.0 Authorization Code with PKCE** |
| [Tweet lookup](/x-api/posts/lookup/introduction)
Scope |
# API Key 및 Secret
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-1-0a/api-key-and-secret
X API Key와 Secret(consumer key 및 secret)이 무엇인지, Developer Portal에서 이를 생성하는 방법, 그리고 재생성 또는 회전하는 방법을 알아보세요.
### API Key 및 Secret
API Key와 Secret(Consumer Key와 Secret이라고도 함)은 X API에 액세스하는 데 필요한 가장 기본적인 자격 증명입니다. 이 자격 증명은 X App에 대한 사용자 이름과 비밀번호 역할을 하며, X API가 어떤 App에서 요청이 오는지 이해하는 데 사용됩니다.
이 자격 증명은 [인증 엔드포인트](/resources/fundamentals/authentication/api-reference)에서 [사용자 Access Token 및 Secret](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret) 및 [Bearer Token](/resources/fundamentals/authentication/oauth-2-0/bearer-tokens)과 같은 추가 자격 증명을 생성하는 데 사용될 수 있습니다. 또한 OAuth 1.0a User Context 인증이 필요한 [요청을 승인](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request)하기 위해 Access Token 및 기타 승인 매개변수와 함께 이 자격 증명을 사용해야 합니다.
#### API Key 및 Secret을 얻는 방법
X API Key와 Secret을 얻으려면 다음 단계를 따르세요:
1. [X 개발자 계정에 가입](https://developer.x.com/en/apply-for-access)합니다.
2. [Developer Console](/resources/fundamentals/developer-portal) 내에서 [X App](/resources/fundamentals/developer-apps)을 생성합니다. [X API v2](/x-api/introduction)를 사용하려면 개발자 App의 키와 토큰을 사용해야 합니다.
X App을 생성할 때 API Key와 Secret이 Bearer Token과 함께 표시됩니다. 이 자격 증명은 한 번만 표시되므로 비밀번호 관리자나 안전한 곳에 반드시 저장해두세요.
키와 토큰을 처리하는 방법에 대한 추가 권장 사항은 자격 증명이 유출된 경우 어떻게 해야 하는지에 대한 세부 정보를 포함하여 [인증 모범 사례](/resources/fundamentals/authentication/guides/authentication-best-practices) 페이지에서 확인할 수 있습니다.
#### App 생성 후 API Key와 Secret을 찾고 재생성하는 방법
이미 App을 생성했고 API Key와 Secret을 찾거나 재생성해야 하는 경우 다음 단계를 따르세요:
1. Developer Console로 이동합니다.
2. 사이드 네비게이션의 'Apps' 드롭다운을 확장합니다.
3. 찾거나 재생성하려는 API Key 및 Secret과 연결된 App을 엽니다.
4. Keys and tokens 탭으로 이동합니다.
여기에서 App과 관련된 모든 자격 증명을 찾을 수 있습니다.
#### API Key 및 Secret 사용 방법
X Developer Platform을 처음 살펴보는 경우, 플랫폼에서 사용 가능한 것을 확인하기 위해 [도구 또는 라이브러리](/resources/tools-and-libraries)를 사용하는 것을 권장합니다. 이러한 도구는 인증을 자연스럽게 처리하며, 많은 시간과 번거로움을 절약할 수 있습니다. 초보 개발자에게는 [Postman으로 시작하기](/tutorials/postman-getting-started) 또는 [Insomnia](https://insomnia.rest/)를 특별히 권장합니다.
처음부터 요청을 구성하는 데 관심이 있는 경우 [OAuth 1.0a 요청 승인](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request) 가이드를 읽어보세요.
# 요청 승인
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-1-0a/authorizing-a-request
consumer key, nonce, signature, timestamp, token 및 version 필드를 포함하여 X API 요청에 서명하기 위한 OAuth 1.0a Authorization 헤더를 구성합니다.
### 요청 승인
이 문서의 목적은 X API에 승인된 요청을 보내기 위해 HTTP 요청을 수정하는 방법을 보여주는 것입니다.
X의 모든 API는 HTTP 프로토콜을 기반으로 합니다. 이는 X의 API를 사용하는 소프트웨어가 구조화된 메시지 시리즈를 X 서버로 전송한다는 것을 의미합니다. 예를 들어, "**Hello Ladies + Gentlemen, a signed OAuth request!**" 텍스트를 Tweet으로 게시하는 요청은 다음과 같이 보일 것입니다:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
모든 HTTP 라이브러리는 위의 요청을 최소한의 어려움으로 생성하고 발행할 수 있어야 합니다. 그러나 위의 요청은 다음을 알 방법이 없기 때문에 유효하지 않은 것으로 간주됩니다:
1. 어떤 애플리케이션이 요청을 하고 있는지
2. 요청이 어떤 사용자를 대신하여 게시되고 있는지
3. 사용자가 애플리케이션에 자신을 대신하여 게시할 수 있는 권한을 부여했는지 여부
4. 요청이 전송 중에 제3자에 의해 조작되었는지 여부
애플리케이션이 이 정보를 제공할 수 있도록, X의 API는 [OAuth 1.0a 프로토콜](http://tools.ietf.org/html/rfc5849)에 의존합니다. 매우 단순화된 수준에서, X의 구현은 승인이 필요한 요청이 위에 나열된 질문에 답할 수 있는 충분한 정보를 포함하는 추가 HTTP Authorization 헤더를 포함해야 합니다. 이 헤더를 포함하도록 수정된 위에 표시된 HTTP 요청의 버전은 다음과 같습니다(일반적으로 Authorization 헤더는 한 줄에 있어야 하지만 여기서는 가독성을 위해 줄바꿈되어 있습니다):
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth\_consumer\_key="xvz1evFS4wEEPTGEFPHBog",
oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth\_signature\_method="HMAC-SHA1",
oauth_timestamp="1318622958",
oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
oauth_version="1.0"
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
이 요청이 생성되었을 때, X API에 의해 유효한 것으로 승인되었을 것입니다.
이 서명 프로세스가 통합의 범위를 벗어난다고 느껴진다면, OAuth를 사용하지 않고도 X API와 상호 작용할 수 있는 [Web Intents](https://dev.x.com/web/intents)를 사용하는 것을 고려해보세요.
**매개변수 수집**
헤더에 7개의 키/값 쌍이 포함되어 있으며, 모든 키가 "oauth\_" 문자열로 시작한다는 것을 확인할 수 있습니다. 주어진 X API 요청에 대해 이 7개의 값을 수집하고 유사한 헤더를 생성하면 요청에 대한 승인을 지정할 수 있습니다. 각 값이 생성된 방법은 아래에 설명되어 있습니다:
**Consumer key**
oauth\_consumer\_key는 요청을 하는 애플리케이션을 식별합니다. [Developer Console](/resources/fundamentals/developer-portal)의 [X 앱](/resources/fundamentals/developer-apps) 설정 페이지에서 이 값을 얻을 수 있습니다.
| | |
| :------------------- | :--------------------- |
| oauth\_consumer\_key | xvz1evFS4wEEPTGEFPHBog |
**Nonce**
oauth\_nonce 매개변수는 애플리케이션이 각 고유 요청에 대해 생성해야 하는 고유 토큰입니다. X는 이 값을 사용하여 요청이 여러 번 제출되었는지 확인합니다. 이 요청의 값은 32바이트의 무작위 데이터를 base64 인코딩하고 모든 비단어 문자를 제거하여 생성되었지만, 상대적으로 무작위한 영숫자 문자열을 생성하는 어떤 접근 방식도 여기에 적합합니다.
| | |
| :----------- | :----------------------------------------- |
| oauth\_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
**Signature**
oauth\_signature 매개변수는 다른 모든 요청 매개변수와 두 개의 시크릿 값을 서명 알고리즘에 실행하여 생성되는 값을 포함합니다. 서명의 목적은 X가 요청이 전송 중에 수정되지 않았는지 확인하고, 요청을 보내는 애플리케이션을 확인하며, 애플리케이션이 사용자 계정과 상호 작용할 수 있는 권한을 가지고 있는지 확인할 수 있도록 하기 위함입니다.
이 요청에 대한 oauth\_signature를 계산하는 프로세스는 [Signature 생성](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature)에 설명되어 있습니다.
| | |
| :--------------- | :--------------------------- |
| oauth\_signature | tnnArxj06cWHq44gCs1OSKk/jLY= |
**Signature method**
X에서 사용하는 oauth\_signature\_method는 HMAC-SHA1입니다. 이 값은 X API에 전송되는 모든 승인된 요청에 사용되어야 합니다.
| | |
| :----------------------- | :-------- |
| oauth\_signature\_method | HMAC-SHA1 |
**Timestamp**
oauth\_timestamp 매개변수는 요청이 생성된 시간을 나타냅니다. 이 값은 요청이 생성된 시점의 Unix epoch 이후 초 수여야 하며, 대부분의 프로그래밍 언어에서 쉽게 생성될 수 있어야 합니다. X는 과거에 너무 오래 전에 생성된 요청을 거부하므로 요청을 생성하는 컴퓨터의 시계를 NTP와 동기화하는 것이 중요합니다.
| | |
| :--------------- | :--------- |
| oauth\_timestamp | 1318622958 |
**Token**
oauth\_token 매개변수는 일반적으로 사용자가 애플리케이션에 자신의 계정 액세스를 공유할 수 있는 권한을 나타냅니다. 이 값이 전달되지 않거나 다른 형태의 토큰인 몇 가지 인증 요청이 있지만, 이는 [access token 얻기](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)에서 자세히 다룹니다. 대부분의 일반적인 요청의 경우 **access token**이라고 부르는 것을 사용합니다.
[Developer Console](/resources/fundamentals/developer-portal)의 [X 앱](/resources/fundamentals/developer-apps) 설정 페이지에서 계정에 대한 유효한 [access token](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)을 생성할 수 있습니다.
| | |
| :----------- | :------------------------------------------------- |
| oauth\_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
**Version**
oauth\_version 매개변수는 X API에 전송되는 모든 요청에 대해 항상 1.0이어야 합니다.
| | |
| :------------- | :-- |
| oauth\_version | 1.0 |
#### 헤더 문자열 구성하기
헤더 문자열을 구성하려면 DST라는 이름의 문자열에 쓴다고 상상해보세요.
1. "OAuth " 문자열(끝 공백 포함)을 DST에 추가합니다.
2. 위에 나열된 7개 매개변수의 각 키/값 쌍에 대해:
1. 키를 [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)하고 DST에 추가합니다.
2. 등호 문자 '='를 DST에 추가합니다.
3. 큰따옴표 '"'를 DST에 추가합니다.
4. 값을 [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)하고 DST에 추가합니다.
5. 큰따옴표 '"'를 DST에 추가합니다.
6. 남은 키/값 쌍이 있는 경우, 쉼표 ','와 공백 ' '를 DST에 추가합니다.
이 문자열을 구성할 때 값의 퍼센트 인코딩에 특히 주의하세요. 예를 들어, tnnArxj06cWHq44gCs1OSKk/jLY= 값을 가진 oauth\_signature는 tnnArxj06cWHq44gCs1OSKk%2FjLY%3D로 인코딩되어야 합니다.
위에서 수집한 매개변수에 대해 이러한 단계를 수행하면 다음 문자열이 생성됩니다:
```
OAuth oauth\_consumer\_key="xvz1evFS4wEEPTGEFPHBog", oauth\_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg", oauth\_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth\_signature\_method="HMAC-SHA1", oauth\_timestamp="1318622958", oauth\_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0"
```
이 값은 요청의 Authorization 헤더로 설정되어야 합니다.
# Signature 생성
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-1-0a/creating-a-signature
매개변수를 수집하고, signature base string을 구성한 후, 키로 서명하여 X API 요청용 OAuth 1.0a HMAC-SHA1 서명을 생성합니다.
### Signature 생성
이 페이지에서는 HTTP 요청에 대한 OAuth 1.0a HMAC-SHA1 서명을 생성하는 방법을 설명합니다. 이 서명은 [요청 승인](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request)에 설명된 대로 승인된 요청의 일부로 X API에 전달하기에 적합합니다.
서명을 시연하는 데 사용된 요청은 [https://api.x.com/1.1/statuses/update.json에](https://api.x.com/1.1/statuses/update.json에) 대한 POST입니다. 원시 요청은 다음과 같습니다:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
**요청 메서드 및 URL 수집**
서명을 생성하려면 먼저 요청의 HTTP 메서드와 URL을 결정합니다. 이 둘은 요청을 생성할 때 알려져 있으므로 얻기 쉽습니다.
X API 요청의 요청 메서드는 거의 항상 GET 또는 POST가 됩니다.
| | |
| :------- | :--- |
| HTTP 메서드 | POST |
base URL은 쿼리 문자열이나 해시 매개변수를 제외한 요청이 지시되는 URL입니다. 여기서 올바른 프로토콜을 사용하는 것이 중요하므로 URL의 "https\://" 부분이 API로 전송된 실제 요청과 일치하는지 확인하세요.
| | |
| :------- | :--------------------------------------------------------------------------------------- |
| Base URL | [https://api.x.com/1.1/statuses/update.json](https://api.x.com/1.1/statuses/update.json) |
#### 매개변수 수집
다음으로, 요청에 포함된 모든 매개변수를 수집합니다. 이러한 추가 매개변수에는 두 가지 위치가 있습니다 - URL(쿼리 문자열의 일부) 및 요청 본문. 예시 요청에는 두 위치 모두에 단일 매개변수가 포함되어 있습니다:
```
POST /1.1/statuses/update.json?include_entities=true HTTP/1.1
Accept: */*
Connection: close
User-Agent: OAuth gem v0.4.4
Content-Type: application/x-www-form-urlencoded
Content-Length: 76
Host: api.x.com
status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21
```
HTTP 요청에는 URL 인코딩된 매개변수가 있지만, 원시 값을 수집해야 합니다. 요청 매개변수 외에도 모든 oauth\_\* 매개변수가 서명에 포함되어야 하므로 이러한 것도 수집합니다. 다음은 [요청 승인](/resources/fundamentals/authentication/oauth-1-0a/authorizing-a-request)의 매개변수입니다:
| | |
| :----------------------- | :------------------------------------------------- |
| status | Hello Ladies + Gentlemen, a signed OAuth request! |
| include\_entities | true |
| oauth\_consumer\_key | xvz1evFS4wEEPTGEFPHBog |
| oauth\_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
| oauth\_signature\_method | HMAC-SHA1 |
| oauth\_timestamp | 1318622958 |
| oauth\_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
| oauth\_version | 1.0 |
이 값들은 나중에 사용될 단일 문자열로 인코딩되어야 합니다. 문자열을 구성하는 프로세스는 매우 구체적입니다:
1. 서명될 모든 키와 값을 [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters)합니다.
2. 인코딩된 키 [\[2\]](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature)를 기준으로 매개변수 목록을 알파벳순으로 [\[1\]](/resources/fundamentals/authentication/oauth-1-0a/creating-a-signature) 정렬합니다.
3. 각 키/값 쌍에 대해:
4. 인코딩된 키를 출력 문자열에 추가합니다.
5. '=' 문자를 출력 문자열에 추가합니다.
6. 인코딩된 값을 출력 문자열에 추가합니다.
7. 남은 키/값 쌍이 더 있는 경우 '&' 문자를 출력 문자열에 추가합니다.
\[1] OAuth 명세는 사전순으로 정렬하도록 지시하며, 이는 많은 라이브러리의 기본 알파벳 정렬입니다.
\[2] 동일한 인코딩된 키를 가진 두 개의 매개변수가 있는 경우, OAuth 명세는 값을 기준으로 정렬을 계속하도록 지시합니다. 그러나 X는 API 요청에서 중복된 키를 허용하지 않습니다.
**Parameter string**
위에서 수집한 매개변수로 이러한 단계를 반복하면 다음 \_parameter string\_이 생성됩니다:
| status | Hello Ladies + Gentlemen, a signed OAuth request! |
| :----------------------- | :------------------------------------------------- |
| `include_entities` | true |
| `oauth_consumer_key` | xvz1evFS4wEEPTGEFPHBog |
| `oauth_nonce` | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
| `oauth_signature_method` | HMAC-SHA1 |
| `oauth_timestamp` | 1318622958 |
| `oauth_token` | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
| `oauth_version` | 1.0 |
#### Signature base string 생성
지금까지 수집한 세 개의 값은 서명이 생성될 단일 문자열로 결합되어야 합니다. 이를 OAuth 명세에서는 **signature base string**이라고 합니다.
HTTP 메서드, base URL 및 parameter string을 단일 문자열로 인코딩하려면:
1. HTTP 메서드를 대문자로 변환하고 출력 문자열을 이 값과 동일하게 설정합니다.
2. '&' 문자를 출력 문자열에 추가합니다.
3. URL을 [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters)하고 출력 문자열에 추가합니다.
4. '&' 문자를 출력 문자열에 추가합니다.
5. parameter string을 [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters)하고 출력 문자열에 추가합니다.
이렇게 하면 다음 \_signature base string\_이 생성됩니다:
```
POST&https%3A%2F%2Fapi.x.com%2F1.1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521
```
parameter string을 반드시 퍼센트 인코딩하세요. signature base string에는 정확히 2개의 앰퍼샌드 '&' 문자가 포함되어야 합니다. parameter string의 퍼센트 '%' 문자는 signature base string에서 %25로 인코딩되어야 합니다.
#### 서명 키 얻기
수집해야 할 마지막 데이터는 요청을 하는 [X 앱](/resources/fundamentals/developer-apps)과 요청이 대신하는 사용자를 식별하는 시크릿입니다. 이러한 값은 매우 민감하며 절대 아무와 공유해서는 안 된다는 점에 유의하는 것이 매우 중요합니다.
X에 앱을 식별하는 값은 **consumer secret**이라고 하며 [Developer Console](/resources/fundamentals/developer-portal)에서 [앱 세부 정보 페이지](/resources/fundamentals/developer-apps)를 통해 찾을 수 있습니다. 이 값은 X 앱이 보내는 모든 요청에 대해 동일합니다.
| | |
| :-------------- | :------------------------------------------ |
| Consumer secret | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw |
애플리케이션이 대신하여 작동하는 계정을 식별하는 값을 **OAuth token secret**이라고 합니다. 이 값은 여러 가지 방법으로 얻을 수 있으며, 모두 [access token 얻기](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)에 설명되어 있습니다.
| | |
| :----------------- | :---------------------------------------- |
| OAuth token secret | LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
다시 한번, 이러한 값을 애플리케이션에 비공개로 유지하는 것이 매우 중요합니다. 값이 유출되었다고 느껴진다면 토큰을 재생성하세요(이 페이지의 토큰은 실제 요청에 대해 유효하지 않은 것으로 표시되어 있습니다).
이 두 값을 결합하여 서명을 생성하는 데 사용될 **서명 키**를 만들어야 합니다. 서명 키는 단순히 [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters)된 token secret입니다:
[request token 얻기](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)와 같이 token secret이 아직 알려지지 않은 일부 흐름이 있습니다. 이 경우 서명 키는 [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters)된 **consumer secret** 뒤에 앰퍼샌드 문자 '&'로 구성되어야 합니다.
| | |
| :--- | :------------------------------------------------------------------------------------- |
| 서명 키 | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw\&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
#### 서명 계산
마지막으로, signature base string과 서명 키를 HMAC-SHA1 해싱 알고리즘에 전달하여 서명이 계산됩니다. 알고리즘의 세부 사항은 hash\_hmac 함수로 설명됩니다.
HMAC 서명 함수의 출력은 이진 문자열입니다. 이는 서명 문자열을 생성하기 위해 base64 인코딩되어야 합니다. 예를 들어, 이 페이지에서 제공된 base string과 서명 키에 대한 출력은 2E CF 77 84 98 99 6D 0D DA 90 5D C7 17 7C 75 07 3F 3F CD 4E입니다. 그 값을 base64로 변환한 것이 이 요청에 대한 OAuth 서명입니다:
| | |
| :------- | :--------------------------- |
| OAuth 서명 | Ls93hJiZbQ3akF3HF3x1Bz8/zU4= |
# OAuth Echo
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-1-0a/oauth-echo
x-auth-service-provider 및 verify-credentials 헤더를 사용하여 업로드를 위해 X 인증을 제3자 미디어 제공자에게 안전하게 위임하려면 OAuth Echo를 사용하세요.
### OAuth Echo
OAuth Echo는 API와 상호 작용하면서 제3자에게 OAuth 승인을 안전하게 위임하는 수단입니다.
이 상호 작용에는 네 개의 당사자가 관련됩니다:
* **User** - 특정 승인된 X 애플리케이션을 통해 X를 사용하는 사람
* **Consumer** - 제3자 미디어 제공자(예: 사진 공유 사이트)와 상호 작용하려는 X 애플리케이션
* **Delegator** - 제3자 미디어 제공자
* **Service Provider** - X 자체
기본적으로 delegator가 애플리케이션과 사용자를 대신하여 X API로 보낼 요청을 준비합니다. 그렇지 않으면 서명된 OAuth 요청이 될 것을 HTTP 헤더에 추가하고, 중간 작업을 완료한 후 delegator에게 해당 요청을 X로 보내도록 요청합니다.
예를 들어: User가 사진을 업로드하려고 합니다. Consumer는 POST로 Delegator에서 upload를 호출할 것입니다. POST에는 이미지가 포함되어야 하지만, HTTP 헤더로 두 가지 추가 항목도 포함되어야 합니다:
* `x-auth-service-provider` — 사실상 이는 신원 위임이 전송되어야 하는 realm입니다 — X의 경우 이를 [https://api.x.com/1.1/account/verify\_credentials.json으로](https://api.x.com/1.1/account/verify_credentials.json으로) 설정합니다. iOS5 기반 X 통합에서는 이 URL에 추가 application\_id 매개변수를 추가하며, 이는 x-verify-credentials-authorization에서 사용되는 oauth\_signature를 계산하는 데에도 사용됩니다.
* `x-verify-credentials-authorization` — Consumer는 HTTP 헤더에서 OAuth를 사용하여 [https://api.x.com/1.1/account/verify\_credentials.json을](https://api.x.com/1.1/account/verify_credentials.json을) 호출할 수 있도록 필요한 모든 OAuth 매개변수를 생성해야 합니다(예: OAuth oauth\_consumer\_key="...", oauth\_token="...", oauth\_signature\_method="...", oauth\_signature="...", oauth\_timestamp="...", oauth\_nonce="...", oauth\_version="..." 처럼 보여야 합니다).
전체 트랜잭션 기간이 `oauth_timestamp`가 여전히 유효한 시간 내에 발생해야 한다는 점을 명심하세요.
또는 헤더에서 이 두 매개변수를 보내는 대신, POST에서 x\_auth\_service\_provider 및 x\_verify\_credentials\_authorization으로 보낼 수 있습니다 — 이 경우, 매개변수를 이스케이프하고 OAuth signature base string에 포함해야 함을 기억하세요 — 어떤 요청에서든 매개변수 인코딩과 유사합니다. 작업을 가능한 한 분리된 상태로 유지하기 위해 HTTP 헤더를 사용하는 것이 가장 좋습니다.
이 시점에서 Delegator의 목표는 미디어를 저장하기 전에 User가 자신이 주장하는 사람인지 확인하는 것입니다. Delegator가 업로드 메서드를 통해 위의 모든 데이터를 받으면 이미지를 임시로 저장한 다음, x-verify-credentials-authorization 헤더에서 Consumer가 제공한 동일한 OAuth 인증 헤더를 사용하여 x-auth-service-provider 헤더에 지정된 엔드포인트(이 경우 [https://api.x.com/1.1/account/verify\_credentials.json)에](https://api.x.com/1.1/account/verify_credentials.json\)에) 대한 호출을 구성해야 합니다.
#### OAuth Echo 모범 사례
하드코딩된 값이 *아닌*, `x-auth-service-provider`가 제공한 URL을 사용하여 조회를 수행하세요. 예를 들어, Apple iOS는 모든 OAuth 요청에 추가 application\_id 매개변수를 추가하며, OAuth Echo의 각 단계에서 그 존재가 유지되어야 합니다.
OAuth 승인 부분의 경우, x-verify-credentials-authorization의 헤더 값을 가져와 service provider에 대한 호출을 위한 자체 Authorization 헤더에 배치합니다. 확실하게 하기 위해 `x-auth-service-provider`의 값이 예상되는 값인지 확인하세요.
* Service Provider가 HTTP 200을 반환하면 좋습니다. Delegator는 이미지를 영구적으로 저장하고 URL을 생성하여 반환해야 합니다.
* Service Provider가 HTTP 200을 반환하지 않으면 이미지를 폐기한 다음 Consumer에게 오류를 반환하세요.
# 3-legged OAuth flow를 사용하여 Access Token 얻기
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens
request_token, authorize 및 access_token 엔드포인트를 사용하여 X API용 사용자 액세스 토큰을 얻기 위한 3-legged OAuth 1.0a 흐름을 진행합니다.
### 3-legged OAuth flow를 사용하여 액세스 토큰 얻기
다른 사용자를 대신하여 작업을 수행하려면 해당 사용자의 액세스 토큰을 얻어야 합니다. 액세스 토큰은 요청이 대신 이루어지는 X 계정을 지정하므로, 이러한 토큰을 얻으려면 먼저 사용자가 액세스 권한을 부여해야 합니다. 이 토큰은 만료되지 않지만 언제든지 사용자가 취소할 수 있습니다.
X는 3-legged OAuth flow를 통해 사용자 액세스 토큰을 얻을 수 있게 해줍니다. 이는 애플리케이션이 사용자를 X로 리다이렉트하고 사용자가 애플리케이션을 승인하도록 함으로써 **access token**과 access token secret을 얻을 수 있게 합니다. 이 흐름은 [Log in with X 구현](/resources/fundamentals/authentication/guides/log-in-with-x)에 설명된 흐름과 거의 동일하지만, 두 가지 예외가 있습니다:
* [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) 대신 [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize) 엔드포인트가 사용됩니다.
* 이전에 액세스가 부여되었더라도 사용자는 **항상** 애플리케이션에 대한 액세스를 승인하도록 프롬프트됩니다.
시작하기 전에 [애플리케이션의](/resources/fundamentals/developer-apps) 권한을 확인하고 consumer 키와 콜백 URL을 알아야 합니다. 콜백 URL이나 공개적으로 액세스 가능한 UI가 없는 경우, 승인 후 사용자를 리다이렉트하기 위해 웹 브라우저에 액세스하거나 임베드할 수 없는 애플리케이션을 위한 [PIN 기반 승인](/resources/fundamentals/authentication/oauth-1-0a/pin-based-oauth)을 사용하는 것을 고려하세요.
3-legged 로그인 상호 작용의 가능한 상태는 다음 순서도에 나와 있습니다:

#### 프로세스 개요
상위 수준에서 3-Legged OAuth 프로세스는 다음을 수행합니다:
1. consumer 애플리케이션이 request token을 얻기 위한 요청을 생성합니다.
2. 사용자가 인증하도록 하고 consumer 애플리케이션에 request token을 전송합니다.
3. request token을 사용 가능한 사용자 액세스 토큰으로 변환합니다.
**용어 설명**
아래 가이드에서는 같은 것을 지칭하는 다양한 용어를 볼 수 있습니다.
**클라이언트 자격 증명:**
* App Key === API Key === Consumer API Key === Consumer Key === Customer Key === `oauth_consumer_key`
* App Key Secret === API Secret Key === Consumer Secret === Consumer Key === Customer Key === `oauth_consumer_secret`
* Callback URL === `oauth_callback`
**임시 자격 증명:**
* Request Token === `oauth_token`
* Request Token Secret === `oauth_token_secret`
* oauth\_verifier
**토큰 자격 증명:**
* Access token === Token === 결과 `oauth_token`
* Access token secret === Token Secret === 결과 `oauth_token_secret`
#### 단계별 안내
**1단계: [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token)**
consumer 애플리케이션이 request token을 얻기 위한 요청을 생성합니다.
이 요청에서 유일한 매개변수는 oauth\_callback이며, 이는 2단계를 완료할 때 사용자가 리다이렉트되기를 원하는 URL의 [URL 인코딩](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters)된 버전이어야 합니다. 나머지 매개변수는 OAuth 서명 프로세스에 의해 추가됩니다.
참고 - [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) 엔드포인트와 함께 사용하는 콜백 URL은 Developer Console의 앱 세부 정보 페이지에서 [개발자 App의](/resources/fundamentals/developer-apps) 설정 내에 구성되어야 합니다.
**요청 포함 항목:**
`oauth_callback="https%3A%2F%2FyourCallbackUrl.com"`
`oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w" `
앱은 응답의 HTTP 상태를 확인해야 합니다. 200 이외의 값은 실패를 나타냅니다. 응답 본문에는 `oauth_token`, `oauth_token_secret`, `oauth_callback_confirmed` 매개변수가 포함됩니다. 앱은 `oauth_callback_confirmed`가 true인지 확인하고 다음 단계에서 사용하기 위해 나머지 두 값을 저장해야 합니다.
**응답 포함 항목**
`oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
`oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI`
`oauth_callback_confirmed=true`
**2단계: [GET oauth/authorize](/resources/fundamentals/authentication/api-reference#get-oauth-authorize)**
사용자가 인증하도록 하고 consumer 애플리케이션에 request token을 전송합니다.
**사용자를 리다이렉트할 예시 URL:**
`https://api.x.com/oauth/authorize?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
인증에 성공하면 `callback_url`은 `oauth_token`과 `oauth_verifier` 매개변수를 포함한 요청을 받게 됩니다. 애플리케이션은 토큰이 1단계에서 받은 request token과 일치하는지 확인해야 합니다.
**클라이언트의 리다이렉트로부터의 요청:**
`https://yourCallbackUrl.com?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY`
**3단계: [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token)**
request token을 사용 가능한 access token으로 변환합니다.
request token을 사용 가능한 access token으로 렌더링하려면 애플리케이션이 2단계에서 얻은 `oauth_verifier` 값을 포함하여 [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token) 엔드포인트에 요청해야 합니다. request token 역시 헤더의 `oauth_token` 부분에 전달되지만, 이는 서명 프로세스에 의해 추가됩니다.
**요청 포함 항목:**
`POST /oauth/access_token`
`oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w`
`oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0`
`oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY`
성공 응답에는 `oauth_token`, `oauth_token_secret` 매개변수가 포함됩니다. 토큰과 토큰 시크릿은 저장되어 X API에 대한 향후 인증된 요청에 사용되어야 합니다. 사용자의 신원을 확인하려면 [GET account/verify\_credentials](/resources/fundamentals/authentication/api-reference)를 사용하세요.
**응답 포함 항목:**
`oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4`
`oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo`
**OAuth 1.0a(application-user)가 필요한 요청에 이러한 자격 증명 사용**
이제 사용자 액세스 토큰을 얻었습니다. 이를 사용하여 사용자를 대신해 Tweet을 생성하는 [POST statuses/update](/x-api/posts/manage-tweets/introduction)와 같은 특정 API에 액세스할 수 있습니다.
**요청 포함 항목:**
`POST statuses/update.json`
`oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w`
`oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4`
#### 예시 사용 사례
표준 흐름은 웹 기반이며 3-legged 승인 OAuth 흐름을 사용합니다. 여기에 나와 있는 스크린샷은 [https://github.com/xdevplatform/twauth-web](https://github.com/xdevplatform/twauth-web)에서 소스를 볼 수 있는 샘플의 일부입니다.
애플리케이션의 어느 시점에서 애플리케이션을 승인하기 위해 X로 리다이렉트하고자 할 것입니다.
request token으로 X로 리다이렉트하면 사용자에게 애플리케이션을 승인하도록 프롬프트됩니다.
애플리케이션을 승인하면 사용자는 request token을 생성할 때 제공한 콜백 URL로 리다이렉트됩니다. 이를 사용하여 이 사용자에 대한 영구 액세스 토큰을 얻고 로컬에 저장합니다.
# 매개변수 퍼센트 인코딩
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters
X API 요청의 OAuth 1.0a 매개변수에 RFC 3986 퍼센트 인코딩을 적용하며, 예약 문자에 대한 규칙과 URL 인코딩 예시가 포함되어 있습니다.
### 매개변수 퍼센트 인코딩
X API의 일부, 특히 OAuth 서명을 다루는 부분은 [RFC 3986, Section 2.1](http://tools.ietf.org/html/rfc3986#section-2.1)에 따라 문자열을 인코딩해야 합니다. URL 인코딩 알고리즘의 많은 구현이 RFC 3986과 완전히 호환되지 않기 때문에 잘못된 인코딩은 많은 OAuth 서명 오류의 원인입니다. 이러한 이유로 사용할 정확한 서명 알고리즘이 이 페이지에서 다루어집니다.
이 페이지에서는 [RFC 3986, Section 2.1](http://tools.ietf.org/html/rfc3986#section-2.1)에 설명된 URL 인코딩 프로세스를 다룹니다. 모호함이나 이 문서와의 충돌이 있는 경우 해당 명세를 참조하는 것이 좋습니다.
#### 문자열 인코딩
다음 알고리즘은 문자열 SRC의 값을 바이트 단위로 문자열 DST에 복사하여 인코딩한다고 가정합니다.
**1단계: SRC에 읽지 않은 바이트가 있는 동안 SRC에서 다음 바이트(8비트)를 읽습니다.** 일반적으로 이는 문자로 간주되지만, 문자가 두 바이트 이상일 수 있는 인코딩(예: UTF-8)의 경우 첫 번째 바이트만 읽습니다.
**2단계: 읽은 바이트가 다음 ASCII 등가물 중 하나와 일치하는지 확인합니다.** 다음 표는 가독성을 위해 행으로 나누어져 있지만, 특정 행이 아니라 읽은 바이트가 표에 존재하는지 여부만 확인하면 됩니다.
| 이름 | ASCII 문자 | 등가 바이트 값 |
| :---- | :------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
| 숫자 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' | 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 |
| 대문자 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' | 0x41, 0x42, 0x43, 0x44, 0x45,0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51,0x52, 0x53, 0x54, 0x55, 0x56, 0x57,0x58, 0x59, 0x5A |
| 소문자 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' | 0x61, 0x62, 0x63, 0x64, 0x65,0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B,0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71,0x72, 0x73, 0x74, 0x75, 0x76, 0x77,0x78, 0x79, 0x7A |
| 예약 문자 | '-', '.', '\_', '\~' | 0x2D, 0x2E, 0x5F, 0x7E |
**2b단계: 바이트가 위 표에 나열되지 않은 경우 계속 진행합니다.** 다른 모든 값은 인코딩되어야 합니다. **2a단계: 바이트가 위 표에 나열되어 있으면 DST에 복사하고 1단계로 돌아갑니다.** 위 표에 나열된 문자는 이스케이프할 필요가 없으므로 바이트를 직접 복사하기만 하면 됩니다.
**3단계: DST에 '%' 문자를 씁니다.** 퍼센트 문자 '%'(또는 16진수로 0x25, 2진수로 00100101)는 다음 두 바이트가 인코딩된 바이트를 나타낼 것임을 나타냅니다.
**4단계: 현재 바이트의 대문자 ASCII 인코딩된 16진수 값을 나타내는 두 문자를 DST에 씁니다.** 이는 다소 혼란스러울 수 있으므로 예를 들어 설명하겠습니다. 현재 바이트가 0xE6(이진수로 11100110)라고 가정합시다. 이는 'æ'의 UTF-8 인코딩된 값에 해당합니다. 이 값을 인코딩하려면 'E' 문자(위 표에서 0x45)와 그 다음 '6' 문자(0x36)를 DST에 씁니다. 마지막에 쓴 세 문자는 "%E6"이어야 합니다. A, B, C, D, E 또는 F와 같은 문자를 쓸 때는 대문자를 사용해야 합니다.
**5단계: 1단계로 돌아갑니다.** SRC의 전체가 DST로 복사될 때까지 계속 진행합니다.
#### 예시
다음 예시는 자신의 코드 출력과 비교하는 데 도움이 될 수 있습니다. 차이가 있으면 오류로 간주해야 합니다. 공백이 "+" 문자로 인코딩되는 것은 잘못된 인코딩의 예입니다.
| 원본 문자열 | 인코딩된 문자열 |
| :----------------- | :-------------------------- |
| Ladies + Gentlemen | Ladies%20%2B%20Gentlemen |
| An encoded string! | An%20encoded%20string%21 |
| Dogs, Cats & Mice | Dogs%2C%20Cats%20%26%20Mice |
| ☃ | %E2%98%83 |
# PIN 기반 승인
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-1-0a/pin-based-oauth
CLI 도구 및 게임 콘솔과 같이 브라우저를 임베드할 수 없는 X 앱을 위해 숫자 PIN을 oauth_verifier로 입력하여 PIN 기반 OAuth 흐름을 사용하세요.
### PIN 기반 승인
PIN 기반 OAuth 흐름은 [3-legged OAuth](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) 프로세스의 버전이며 승인 후 사용자를 리다이렉트하기 위해 웹 브라우저에 액세스하거나 임베드할 수 없는 애플리케이션을 위한 것입니다. 이러한 애플리케이션의 예로는 명령줄 애플리케이션, 임베디드 시스템, 게임 콘솔 및 특정 유형의 모바일 앱이 있습니다.
PIN 기반 OAuth 흐름은 앱이 `oauth_callback`을 `oob`로 설정한 `request_token`에서 시작됩니다. `oob`라는 용어는 out-of-band OAuth를 의미합니다. 사용자는 여전히 X를 방문하여 로그인하거나 앱을 승인하지만, 액세스 승인 시 애플리케이션으로 자동으로 리다이렉트되지 않습니다. 대신, 애플리케이션으로 돌아가서 이 값을 입력하라는 지시와 함께 숫자 PIN 코드를 보게 됩니다.
**참고:** PIN 기반 인증을 사용하는 경우에도 X 앱 설정 내의 `callback_url`은 여전히 필수입니다.
#### PIN 기반 OAuth 흐름 구현하기
PIN 기반 흐름은 [3-legged 승인](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens) (및 [Sign in with X](/resources/fundamentals/authentication#log-in-with-x))과 동일한 방식으로 구현되지만 다음과 같은 차이점이 있습니다:
1. [POST oauth/request\_token](/resources/fundamentals/authentication/api-reference#post-oauth-request-token) 호출 중에 `oauth_callback` 값은 `oob`로 설정되어야 합니다.
2. 사용자가 [GET oauth/authenticate](/resources/fundamentals/authentication/api-reference#get-oauth-authenticate) 또는 [GET oauth/authorize URL](/resources/fundamentals/authentication/api-reference#get-oauth-authorize)을 사용하여 앱을 승인하기 위해 X로 전송된 후, `callback_url`로 리다이렉트되지 않고 대신 애플리케이션 이름에 PIN을 입력하라는 지시와 함께 X가 생성한 약 7자리 PIN이 표시되는 화면을 보게 됩니다.
3. 사용자가 이 PIN을 애플리케이션에 입력하면, 애플리케이션은 access\_token을 얻기 위해 PIN 번호를 [POST oauth/access\_token](/resources/fundamentals/authentication/api-reference#post-oauth-access-token)에서 `oauth_verifier`로 사용합니다.
**참고:** PIN 번호는 재사용할 수 없으며, 얻은 `access_token`은 application-user 요청에 사용되어야 합니다.
# App only 인증 및 OAuth 2.0 Bearer Token
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-2-0/application-only
사용자 컨텍스트 없이 공개 데이터에 대한 서버 간 읽기 전용 액세스를 위해 OAuth 2.0 App-Only Bearer Token으로 X API 요청을 인증합니다.
### App only 인증 및 OAuth 2.0 Bearer Token
X는 애플리케이션이 특정 사용자를 대신하는 것이 아니라 애플리케이션 자체를 대신하여 인증된 요청을 발행할 수 있는 기능을 제공합니다. X의 구현은 [OAuth 2 명세](http://tools.ietf.org/html/rfc6749)의 [Client Credentials Grant](http://tools.ietf.org/html/rfc6749#section-4.4) 흐름을 기반으로 합니다.
Application-only 인증은 사용자 컨텍스트를 포함하지 않으며 애플리케이션이 자체적으로 API 요청을 하는 인증 형식입니다. 이 방법은 공개 정보에 대한 읽기 전용 액세스만 필요한 개발자를 위한 것입니다.
앱의 consumer API 키를 사용하거나 App only Access Token(Bearer Token)을 사용하여 application-only 인증을 수행할 수 있습니다. 이는 X API에 할 수 있는 요청이 인증된 사용자를 요구하지 않아야 함을 의미합니다.
application-only 인증을 사용하여 다음과 같은 작업을 수행할 수 있습니다:
* 사용자 타임라인 가져오기
* 어떤 계정의 친구 및 팔로워에 액세스
* 리스트 리소스에 액세스
* Tweet 검색
사용자를 대신하여 요청을 발행하려면 [OAuth 1.0a](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret) 또는 PKCE가 포함된 [OAuth 2.0 Authorization Code Flow](/resources/fundamentals/authentication/oauth-2-0/authorization-code)만 필요합니다. [API 레퍼런스](/resources/fundamentals/authentication/api-reference) 페이지는 API 사용에 필요한 인증 방법을 설명합니다. 다음을 수행하려면 [액세스 토큰](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)과 함께 user-authentication, user-context가 필요합니다:
* Tweet 또는 기타 리소스 게시
* 사용자 검색
* geo 엔드포인트 사용
* Direct Message 또는 계정 자격 증명 액세스
* 사용자의 이메일 주소 검색
#### Auth Flow
이 방법을 사용하려면 [App only Access Token](/resources/fundamentals/authentication/oauth-2-0/application-only)([Bearer Token](/resources/fundamentals/authentication/oauth-2-0/bearer-tokens)이라고도 함)을 사용해야 합니다. [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) 엔드포인트를 통해 consumer 키와 시크릿을 전달하여 App only Access Token(Bearer Token)을 생성할 수 있습니다.
application-only 인증 흐름은 다음 단계를 따릅니다:
* 애플리케이션은 consumer 키와 시크릿을 특별히 인코딩된 자격 증명 세트로 인코딩합니다.
* 애플리케이션은 이러한 자격 증명을 [App only Access Token](/resources/fundamentals/authentication/oauth-2-0/application-only)과 교환하기 위해 [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) 엔드포인트에 요청합니다.
* REST API에 액세스할 때 애플리케이션은 App only Access Token을 사용하여 인증합니다.
요청에 서명할 필요가 없기 때문에 이 접근 방식은 표준 OAuth 1.0a 모델보다 훨씬 간단합니다.
#### application-only 인증에 대하여
**토큰은 비밀번호입니다**
consumer 키 & 시크릿 및 App only Access Token(Bearer Token) 자체는 애플리케이션을 대신하여 요청할 수 있는 액세스를 부여한다는 점을 명심하세요. 이러한 값은 비밀번호만큼 민감한 것으로 간주되어야 하며 신뢰할 수 없는 당사자와 공유하거나 배포해서는 안 됩니다.
**SSL 필수**
모든 요청(토큰을 얻고 사용하는 데 모두)은 HTTPS 엔드포인트를 사용해야 *합니다*. [TLS를 사용한 X API 연결](/resources/fundamentals/authentication/guides/tls)에 자세히 설명된 모범 사례를 따르세요 — 피어는 **항상** 검증되어야 합니다.
**사용자 컨텍스트 없음**
application-only 인증을 사용하여 요청을 발행할 때는 "현재 사용자"라는 개념이 없습니다. 따라서 [POST statuses/update](/x-api/posts/creation-of-a-post)와 같은 엔드포인트는 application-only 인증으로 작동하지 않습니다. 사용자를 대신하여 요청을 발행하는 방법에 대한 자세한 내용은 [OAuth 사용](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)을 참조하세요.
**Rate limiting**
애플리케이션에는 두 종류의 rate limiting 풀이 있습니다.
user-context라고도 알려진 액세스 토큰을 사용하여 사용자를 대신하여 이루어진 요청은 application-only 인증에 사용되는 rate limiting 컨텍스트와 다른 컨텍스트에서 소진됩니다. 즉, 사용자를 대신하여 이루어진 요청은 app-only 인증을 통해 사용 가능한 rate limit을 소진하지 않으며, app-only 인증을 통해 이루어진 요청은 사용자 기반 인증에 사용되는 rate limit을 소진하지 않습니다.
[API Rate Limiting](/x-api/fundamentals/rate-limits)에 대해 자세히 알아보고 [제한을 검토](https://developer.x.com/en/portal/products)하세요.
#### application-only 요청 발행
**1단계: consumer 키와 시크릿 인코딩**
Bearer Token을 얻기 위해 애플리케이션의 consumer 키와 시크릿을 자격 증명 세트로 인코딩하는 단계는 다음과 같습니다:
1. [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt)에 따라 consumer 키와 consumer 시크릿을 URL 인코딩합니다. 작성 시점에서 이는 실제로 consumer 키와 시크릿을 변경하지 않지만, 이러한 값의 형식이 향후 변경될 경우를 대비하여 이 단계는 여전히 수행되어야 합니다.
2. 인코딩된 consumer 키, 콜론 문자 ":" 및 인코딩된 consumer 시크릿을 단일 문자열로 연결합니다.
3. 이전 단계의 문자열을 [Base64 인코딩](http://en.wikipedia.org/wiki/Base64)합니다.
아래는 이 알고리즘의 결과를 보여주는 예시 값입니다. 이 페이지에서 사용된 consumer 시크릿은 테스트 목적이며 실제 요청에는 작동하지 않습니다.
| | |
| :------------------------------------------------- | :------------------------------------------------------------------------------------------ |
| Consumer key | xvz1evFS4wEEPTGEFPHBog |
| Consumer secret | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| RFC 1738 인코딩된 consumer
secret (변경되지 않음) | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| Bearer Token 자격 증명 | xvz1evFS4wEEPTGEFPHBog:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
| Base64 인코딩된 Bearer Token 자격 증명 | :: eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw== |
**2단계: App only Access Token(Bearer Token) 얻기**
1단계에서 계산된 값은 [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token)에 요청을 발행하여 App only Access Token으로 교환되어야 합니다:
* 요청은 HTTP POST 요청이어야 합니다.
* 요청에는 `Basic <1단계의 base64 인코딩된 값>` 값의 `Authorization` 헤더가 포함되어야 합니다.
* 요청에는 `application/x-www-form-urlencoded;charset=UTF-8` 값의 `Content-Type` 헤더가 포함되어야 합니다.
* 요청 본문은 `grant_type=client_credentials`이어야 합니다.
**예시 요청 (Authorization 헤더는 줄바꿈되어 있습니다):**
```json theme={null}
POST /oauth2/token HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant\_type=client\_credentials
```
요청이 올바르게 포맷되었다면 서버는 JSON 인코딩된 페이로드로 응답합니다:
**예시 응답:**
```json theme={null}
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token\_type":"bearer","access\_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
```
애플리케이션은 반환된 객체의 `token_type` 키와 연결된 값이 `bearer`인지 확인해야 합니다. `access_token` 키와 연결된 값이 App only Access Token(Bearer Token)입니다.
한 번에 하나의 App only Access Token만 애플리케이션에 유효합니다. 동일한 자격 증명으로 `/oauth2/token`에 다른 요청을 발행하면 무효화될 때까지 동일한 토큰이 반환됩니다.
**3단계: App only Access Token(Bearer Token)으로 API 요청 인증**
App only Access Token(Bearer Token)은 application-only 인증을 지원하는 API 엔드포인트에 요청을 발행하는 데 사용될 수 있습니다. App Access Token을 사용하려면 일반 HTTPS 요청을 구성하고 `Bearer <2단계의 base64 bearer token 값>` 값의 `Authorization` 헤더를 포함하세요. 서명은 필요하지 않습니다.
**예시 요청 (Authorization 헤더는 줄바꿈되어 있습니다):**
```
GET /1.1/statuses/user\_timeline.json?count=100&screen\_name=twitterapi HTTP/1.1
Host: api.x.com
User-Agent: My X App v1.0.23
Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAA
AAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Accept-Encoding: gzip
```
**App only Access Token(Bearer Token) 무효화**
App only Access Token이 유출되거나 어떤 이유로든 무효화되어야 하는 경우 [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token)에 호출을 발행하세요.
**예시 요청 (Authorization 헤더는 줄바꿈되어 있습니다):**
```bash theme={null}
POST /oauth2/invalidate_token HTTP/1.1
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==
User-Agent: My X App v1.0.23
Host: api.x.com
Accept: */*
Content-Length: 119
Content-Type: application/x-www-form-urlencoded
access_token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
```
**예시 응답:**
```json theme={null}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 127
...
{"access_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
```
#### 일반적인 오류 사례
이 섹션에서는 Bearer Token의 협상 및 사용과 관련된 몇 가지 일반적인 실수를 설명합니다. 여기에 다뤄진 모든 오류 응답이 다루어진 것은 아니라는 점에 유의하세요 - 처리되지 않은 오류 코드와 응답을 주의 깊게 관찰하세요.
**App only Access Token을 얻거나 취소하기 위한 잘못된 요청**
다음 시도:
* 잘못된 요청으로 App only Access Token(Bearer Token) 얻기 (예: `grant_type=client_credentials` 누락).
* 잘못되거나 만료된 앱 자격 증명으로 App only Access Token(Bearer Token) 얻기 또는 취소하기.
* 잘못되었거나 취소된 App only Access Token(Bearer Token) 무효화.
* 단기간에 너무 자주 App only Access Token(Bearer Token) 얻기.
는 다음 결과가 발생합니다:
```json theme={null}
HTTP/1.1 403 Forbidden
Content-Length: 105
Content-Type: application/json; charset=utf-8
...
{"errors":\[{"code":99,"label":"authenticity\_token\_error","message":"Unable to verify your credentials"}\]}
```
#### API 요청에 잘못된 App only Access Token(Bearer Token)이 포함됨
잘못되거나 취소된 Access Token을 사용하여 API 요청을 하면 다음 결과가 발생합니다:
```json theme={null}
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 61
...
{"errors":\[{"message":"Invalid or expired token","code":89}\]}
```
#### application-only 인증을 지원하지 않는 엔드포인트에 사용된 App only Access Token(Bearer Token)
App only Access Token(Bearer Token)으로 사용자 컨텍스트가 필요한 엔드포인트(예: `statuses/home_timeline`)를 요청하면 다음이 생성됩니다:
```json theme={null}
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 91
...
{"errors":\[{"message":"Your credentials do not allow access to this resource","code":220}\]}
```
# OAuth 2.0 Authorization Code Flow with PKCE
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-2-0/authorization-code
스코프, refresh token, confidential client 및 access token 수명을 다루는 X OAuth 2.0 Authorization Code Flow with PKCE에 대한 레퍼런스입니다.
### OAuth 2.0 Authorization Code Flow with PKCE
#### 소개
OAuth 2.0은 애플리케이션의 스코프에 대한 더 큰 제어와 여러 디바이스에 걸친 승인 흐름을 허용하는 산업 표준 승인 프로토콜입니다. OAuth 2.0을 사용하면 사용자를 대신하여 특정 권한을 부여하는 세분화된 스코프를 선택할 수 있습니다.
앱에서 OAuth 2.0을 활성화하려면 Developer Console의 앱 설정 섹션에서 찾을 수 있는 앱의 인증 설정에서 활성화해야 합니다.
#### 자격 증명이 얼마나 오래 유효한가요?
기본적으로 Authorization Code Flow with PKCE를 통해 생성하는 액세스 토큰은 `offline.access` 스코프를 사용하지 않는 한 두 시간 동안만 유효합니다.
#### Refresh token
Refresh token을 사용하면 애플리케이션이 refresh token 흐름을 통해 사용자에게 프롬프트하지 않고 새 액세스 토큰을 얻을 수 있습니다.
`offline.access` 스코프가 적용되면 OAuth 2.0 refresh token이 발급됩니다. 이 refresh token으로 액세스 토큰을 얻을 수 있습니다. 이 스코프가 전달되지 않으면 refresh token이 생성되지 않습니다.
새 액세스 토큰을 얻기 위해 refresh token을 사용하는 요청의 예는 다음과 같습니다:
```bash theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ
```
#### 앱 설정
앱의 인증 설정을 OAuth 1.0a 또는 OAuth 2.0으로 선택할 수 있습니다. 또한 앱이 OAuth 1.0a와 OAuth 2.0 모두에 액세스하도록 활성화할 수 있습니다.
OAuth 2.0은 X API v2에서만 사용할 수 있습니다. OAuth 2.0을 선택한 경우 앱의 Keys and Tokens 섹션에서 Client ID를 볼 수 있습니다.
#### Confidential client
[Confidential client](https://datatracker.ietf.org/doc/html/rfc6749#section-2.1)는 자격 증명을 승인되지 않은 당사자에게 노출하지 않고 안전한 방식으로 보유할 수 있으며, 승인 서버와 안전하게 인증하여 client secret을 안전하게 유지합니다. Public client는 일반적으로 브라우저나 모바일 디바이스에서 실행되고 client secret을 사용할 수 없습니다. Confidential client인 앱 유형을 선택하면 client secret이 제공됩니다.
Developer Console에서 confidential client인 클라이언트 유형을 선택한 경우, Client Secret도 볼 수 있습니다. 옵션은 Native App, Single page App, Web App, Automated App 또는 bot입니다. Native App과 Single page App은 public client이고 Web App과 Automated App 또는 bot은 confidential client입니다.
유효한 Authorization Header가 있는 confidential client의 경우 client id가 필요하지 않습니다. public client의 요청에는 여전히 요청 본문에 Client Id를 포함해야 합니다.
#### 스코프
스코프를 사용하면 앱에 대한 세분화된 액세스를 설정할 수 있으므로 앱은 필요한 권한만 가집니다. 어떤 스코프가 어떤 엔드포인트에 매핑되는지 자세히 알아보려면 [인증 매핑 가이드](/resources/fundamentals/authentication/guides/v2-authentication-mapping)를 확인하세요.
| | |
| :------------------- | :----------------------------------------------------- |
| **스코프** | **설명** |
| tweet.read | 보호된 계정의 Tweet을 포함하여 볼 수 있는 모든 Tweet. |
| tweet.write | 나를 대신하여 Tweet 및 Retweet. |
| tweet.moderate.write | 내 Tweet에 대한 답글 숨기기 및 숨기기 해제. |
| users.email | 인증된 사용자의 이메일. |
| users.read | 보호된 계정을 포함하여 볼 수 있는 모든 계정. |
| follows.read | 나를 팔로우하는 사람들과 내가 팔로우하는 사람들. |
| follows.write | 나를 대신하여 사람을 팔로우 및 언팔로우. |
| offline.access | 액세스를 취소할 때까지 계정에 연결 상태 유지. |
| space.read | 볼 수 있는 모든 Space. |
| mute.read | 뮤트한 계정. |
| mute.write | 나를 대신하여 계정 뮤트 및 뮤트 해제. |
| like.read | 좋아요를 누른 Tweet과 볼 수 있는 좋아요. |
| like.write | 나를 대신하여 Tweet 좋아요 및 좋아요 취소. |
| list.read | 내가 만들거나 멤버인 리스트, 리스트 멤버, 리스트 팔로워(비공개 리스트 포함). |
| list.write | 나를 대신하여 리스트 생성 및 관리. |
| block.read | 차단한 계정. |
| block.write | 나를 대신하여 계정 차단 및 차단 해제. |
| bookmark.read | 인증된 사용자로부터 북마크한 Tweet 가져오기. |
| bookmark.write | Tweet에서 북마크 추가 및 제거. |
| dm.read | 보호된 계정의 Direct Message를 포함하여 볼 수 있는 모든 Direct Message. |
| dm.write | 나를 대신하여 Direct Message 전송 및 관리. |
| media.write | 미디어 업로드. |
#### Rate limit
대부분의 경우, rate limit은 Tweet lookup과 Users lookup을 제외하고 OAuth 1.0a로 인증하는 것과 동일합니다. Tweet lookup과 user lookup에 OAuth 2.0을 사용할 때 App당 제한을 15분당 300에서 900 요청으로 늘리고 있습니다. 자세히 알아보려면 [rate limits 문서](/resources/fundamentals/rate-limits)를 확인하세요.
#### Grant types
이 초기 런칭에 대해 지원되는 [grant types](https://oauth.net/2/grant-types/)로 [PKCE](https://oauth.net/2/pkce/)가 있는 [authorization code](https://oauth.net/2/grant-types/authorization-code/)와 [refresh token](https://oauth.net/2/grant-types/refresh-token/)만 제공합니다. 향후 더 많은 grant type을 제공할 수 있습니다.
#### OAuth 2.0 흐름
OAuth 2.0은 현재 OAuth 1.0a에 사용하는 것과 유사한 흐름을 사용합니다. [이 주제에 대한 문서](/resources/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)에서 다이어그램과 자세한 설명을 확인할 수 있습니다.
#### 용어집
| | |
| :---------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **용어** | **설명** |
| Grant types | OAuth 프레임워크는 다양한 사용 사례에 대한 여러 grant type과 새로운 grant type을 만들기 위한 프레임워크를 지정합니다. 예로는 authorization code, client credentials, device code, refresh token이 있습니다. |
| Confidential client | 승인 서버와 안전하게 인증할 수 있는 클라이언트로, 예를 들어 등록된 client secret을 안전하게 유지합니다. |
| Public client | 브라우저나 모바일 디바이스에서 실행되는 애플리케이션과 같이 등록된 client secret을 사용할 수 없는 클라이언트입니다. |
| Authorization code flow | authorization code를 액세스 토큰으로 교환하기 위해 confidential 및 public 클라이언트 모두가 사용합니다. |
| PKCE | 여러 공격을 방지하고 public client에서 안전하게 OAuth 교환을 수행할 수 있도록 하는 authorization code flow의 확장입니다. |
| Client ID | Developer Console의 keys and tokens 섹션에서 "Client ID" 헤더 아래에서 찾을 수 있습니다. 표시되지 않으면 팀에 직접 문의하세요. authorize URL을 생성하는 데 Client ID가 필요합니다. |
| Redirect URI | 콜백 URL입니다. [정확한 일치 검증](https://datatracker.ietf.org/doc/html/rfc6749#section-10.6)이 필요합니다. |
| Authorization code | 애플리케이션이 사용자를 대신하여 API에 액세스할 수 있게 합니다. auth\_code라고도 합니다. auth\_code는 App 소유자가 사용자로부터 승인된 auth\_code를 받은 후 30초의 시간 제한이 있습니다. 30초 이내에 access token으로 교환해야 하며, 그렇지 않으면 auth\_code가 만료됩니다. |
| Access token | Access token은 애플리케이션이 사용자를 대신하여 API 요청을 하는 데 사용하는 토큰입니다. |
| Refresh token | 애플리케이션이 refresh token 흐름을 통해 사용자에게 프롬프트하지 않고 새 액세스 토큰을 얻을 수 있게 합니다. |
| Client Secret | Confidential client인 앱 유형을 선택한 경우 앱의 keys and tokens 섹션의 "Client ID" 아래에 "Client Secret"이 제공됩니다. |
#### 매개변수
OAuth 2.0 authorize URL을 구성하려면 authorization URL에 다음 매개변수가 있는지 확인해야 합니다.
| | |
| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **매개변수** | **설명** |
| response\_type | 이것이 "code"라는 단어로 코드임을 지정해야 합니다. |
| client\_id | Developer Console의 "Client ID" 헤더 아래에서 찾을 수 있습니다. |
| redirect\_uri | 콜백 URL입니다. 이 값은 앱 설정에서 정의된 콜백 URL 중 하나와 일치해야 합니다. OAuth 2.0의 경우, 콜백 URL에 대한 [정확한 일치 검증](https://datatracker.ietf.org/doc/html/rfc6749#section-10.6)이 필요합니다. |
| state | [CSRF 공격](https://auth0.com/docs/protocols/state-parameters)에 대해 검증하기 위해 제공하는 임의의 문자열입니다. 이 문자열의 길이는 최대 500자까지 가능합니다. |
| code\_challenge | [PKCE](https://www.oauth.com/oauth2-servers/pkce/authorization-request/) 매개변수로, 요청할 때마다 임의의 시크릿입니다. |
| code\_challenge\_method | 요청을 하는 데 사용하는 방법을 지정합니다(S256 또는 plain). |
#### Authorize URL
OAuth 2.0을 사용하면 authorize URL을 생성하여, X의 "Sign In"과 유사한 인증 흐름을 통해 사용자가 인증할 수 있도록 할 수 있습니다.
생성하는 URL의 예는 다음과 같습니다:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20account.follows.read%20account.follows.write&state=state&code_challenge=challenge&code_challenge_method=plain
```
이 URL이 작동하려면 적절한 인코딩이 필요하며, [퍼센트 인코딩](/resources/fundamentals/authentication/oauth-1-0a/percent-encoding-parameters)에 대한 문서를 반드시 확인하세요.
# app-only Bearer Token 사용 및 생성
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-2-0/bearer-tokens
oauth2/token 엔드포인트에 curl 요청을 통해 X API OAuth 2.0 application-only 인증을 위한 app-only Bearer Token을 생성하고 사용합니다.
### app-only Bearer Token 사용 및 생성
bearer token을 사용하면 개발자가 X API를 사용하기 위한 더 안전한 진입점을 가질 수 있으며, OAuth 2.0의 핵심 기능 중 하나입니다.
Bearer Token을 사용하는 인증은 application-only 인증이라고도 합니다. Bearer Token은 curl 명령과 같은 스크립트를 사용하여 생성하는 지정되지 않은 형식의 바이트 배열입니다. App 설정의 keys and tokens 섹션 내부에 있는 Developer Console에서도 Bearer Token을 얻을 수 있습니다. 이 기능에 대한 자세한 내용은 [OAuth 공식 문서](https://oauth.net/2/bearer-tokens/)에서 확인할 수 있습니다.
#### 언제 사용되나요?
Bearer Token 사용이 필요한 제품은 다음과 같습니다:
* [Engagement API](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api)
* [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity)
* v2 및 Labs 엔드포인트와 같이 OAuth 2.0 Bearer Token 인증을 활용하는 기타 API.
#### 사전 요구 사항
[개발자 계정에 가입](https://developer.x.com/en/portal/petition/essential/basic-info)하고 [X App](/resources/fundamentals/developer-apps)을 생성해야 합니다. 이러한 것이 있으면 [Developer Console](/resources/fundamentals/developer-portal)에서 찾을 수 있는 API 키도 얻어야 합니다. 아래 단계를 따르세요:
1. developer.x.com에서 X 계정에 로그인하세요.
2. [X App 대시보드](https://developer.x.com/content/developer-twitter/en/apps)로 이동하여 액세스 토큰을 생성하려는 X App을 엽니다.
3. "keys and tokens" 페이지로 이동합니다.
4. 이 페이지에서 API 키, 사용자 Access Token 및 Bearer Token을 찾을 수 있습니다.
### Bearer Token 생성 방법
앱의 "Keys and Tokens"와 함께 Bearer Token을 찾을 수 있습니다.
[X App](/resources/fundamentals/developer-apps)에서 이전에 얻은 다음 consumer API 키에 대해 변경한 후 다음 cURL 요청을 명령줄에 복사하세요. 이 페이지에서 사용된 consumer API 키는 폐기되었으며 실제 요청에는 작동하지 않습니다.
* **API key** `` 예: `xvz1evFS4wEEPTGEFPHBog`
* **API secret key** `` 예: `L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg`
```bash theme={null}
curl -u "$API_KEY:$API_SECRET_KEY" \
--data 'grant_type=client_credentials' \
'https://api.x.com/oauth2/token'
```
다음은 API 키를 입력했을 때 curl 요청이 어떻게 보여야 하는지에 대한 예입니다:
```bash theme={null}
curl -u 'xvz1evFS4wEEPTGEFPHBog:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg' \
--data 'grant_type=client_credentials' \
'https://api.x.com/oauth2/token'
```
응답이 어떻게 보일지에 대한 예입니다. 이는 폐기된 Bearer Token이라는 점에 유의하세요:
`{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F"}`
OAuth 2.0을 사용하여 리소스에 인증하는 데 사용할 Bearer Token은 다음과 같습니다:
`AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F`
# OAuth 2.0
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-2-0/overview
OAuth 2.0 Bearer Token은 개발자 App을 대신하여 요청을 인증합니다. 이 방법은 App에 특정되므로 사용자를 포함하지 않습니다.
### Bearer Token (app-only라고도 함)
OAuth 2.0 Bearer Token은 [개발자 App](/resources/fundamentals/developer-apps)을 대신하여 요청을 인증합니다. 이 방법은 App에 특정되므로 사용자를 포함하지 않습니다. 이 방법은 일반적으로 공개 정보에 대한 읽기 전용 액세스가 필요한 개발자를 위한 것입니다.
이 인증 방법은 요청과 함께 Bearer Token을 전달해야 하며, 이는 개발자 App의 Keys and tokens 섹션에서 생성할 수 있습니다. 다음은 가짜 Bearer Token으로 요청이 어떻게 보이는지에 대한 예입니다:
```json theme={null}
curl "https://api.x.com/2/tweets?ids=1261326399320715264,1278347468690915330" \
-H "Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAFnz2wAAAAAAxTmQbp%2BIHDtAhTBbyNJon%2BA72K4%3DeIaigY0QBrv6Rp8KZQQLOTpo9ubw5Jt?WRE8avbi"
```
app-only 인증을 사용하는 API 호출은 App 수준에서 엔드포인트별로 [rate limit](/resources/fundamentals/rate-limits)이 있습니다.
이 방법을 사용하려면 Bearer Token이 필요하며, [POST oauth2/token](/resources/fundamentals/authentication/api-reference#post-oauth2-token) 엔드포인트를 통해 API Key 및 Secret을 전달하거나 [Developer Console](/resources/fundamentals/developer-portal)의 App 설정 "keys and token" 섹션에서 생성하여 이를 얻을 수 있습니다.
Bearer Token을 취소하려면 [POST oauth2/invalidate\_token](/resources/fundamentals/authentication/api-reference#post-oauth2-invalidate-token) 엔드포인트를 사용하거나 App 설정의 "keys and tokens" 섹션에서 Bearer Token 옆에 "revoke"라고 표시된 곳을 클릭할 수 있습니다.
### OAuth 2.0 Authorization Code Flow with PKCE
OAuth 2.0 Authorization Code Flow with PKCE를 사용하면 애플리케이션의 스코프에 대한 더 큰 제어와 여러 디바이스에 걸친 개선된 승인 흐름으로 다른 사용자를 대신하여 인증할 수 있습니다. 즉, X에서 사람들을 위한 애플리케이션을 만드는 개발자는 App이 사용자로부터 요청하는 정보를 더 많이 제어할 수 있으므로, 필요한 데이터와 정보만 최종 사용자에게 요청하면 됩니다.
이 최신 승인 프로토콜을 사용하면 최종 사용자에게 앱을 승인하기 위한 보다 간소화된 동의 흐름을 제공할 수 있으며, 이는 사용자에게 요청한 특정 스코프만 표시합니다. 이는 데이터 부담을 줄일 뿐만 아니라 최종 사용자의 신뢰를 높일 수도 있습니다.
# OAuth 2.0 Authorization Code Flow with PKCE
Source: https://docs.x.com/ko/fundamentals/authentication/oauth-2-0/user-access-token
authorize URL 및 토큰 교환을 포함한 OAuth 2.0 Authorization Code Flow with PKCE로 X API v2 엔드포인트에 사용자를 연결하는 단계별 가이드입니다.
### OAuth 2.0 Authorization Code Flow with PKCE를 사용하여 엔드포인트에 연결하는 방법
#### 엔드포인트에 연결하는 방법
사용자를 인증하려면 App이 승인 흐름을 구현해야 합니다. 이 승인 흐름을 사용하면 사용자를 X의 승인 대화 상자로 안내할 수 있습니다. 여기에서 기본 X 경험은 승인 대화 상자를 표시하고 App을 대신하여 승인을 처리합니다. 사용자는 App을 승인하거나 권한을 거부할 수 있습니다. 사용자가 선택한 후 X는 사용자를 App으로 리다이렉트하며, 여기서 authorization code를 액세스 토큰으로 교환하거나(사용자가 App을 승인한 경우) 거부를 처리할 수 있습니다(사용자가 App을 승인하지 않은 경우).
#### Confidential client 작업
confidential client로 작업하는 경우, 토큰 엔드포인트에 요청할 때 base64 인코딩을 사용하여 authorization 헤더를 생성하기 위해 [basic authentication](https://datatracker.ietf.org/doc/html/rfc2617#section-2) 스키마를 사용해야 합니다.
`userid`와 `password`는 자격 증명의 base64 인코딩된 문자열 내에서 단일 콜론(":") 문자로 구분됩니다.
예는 다음과 같습니다:
`-header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='`
user agent가 Client ID "Aladdin"과 비밀번호 "open sesame"을 보내고자 한다면 다음 헤더 필드를 사용합니다:
`Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==`
basic authorization 헤더를 생성하려면 [Developer Console](https://developer.x.com/en/portal/dashboard) 내부의 앱 "Keys and Tokens" 페이지에서 얻을 수 있는 Client ID와 Client Secret에 base64 인코딩이 필요합니다.
#### OAuth 2.0을 사용하여 연결하는 단계
**1단계: Authorize URL 구성**
App은 승인해야 하는 스코프를 나타내는 X에 대한 authorize URL을 구성해야 합니다. 예를 들어, App이 Tweet, 사용자를 조회하고 팔로우를 관리해야 하는 경우 다음 스코프를 요청해야 합니다:
`tweet.read%20users.read%20follows.read%20follows.write`
URL에는 다른 필수 매개변수 외에도 `code_challenge`와 state 매개변수가 포함됩니다. 프로덕션에서는 `code_challenge`에 임의의 문자열을 사용해야 합니다.
**2단계: GET oauth2/authorize**
사용자가 인증하도록 하고 애플리케이션에 authorization code를 전송합니다. App에서 OAuth 2.0을 활성화한 경우 앱의 "Keys and Tokens" 페이지에서 Client ID를 찾을 수 있습니다.
사용자를 리다이렉트할 예시 URL은 다음과 같습니다:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20follows.read%20follows.write&state=state&code_challenge=challenge&code_challenge_method=plain
```
offline\_access가 포함된 예시 URL은 다음과 같습니다:
```
https://x.com/i/oauth2/authorize?response_type=code&client_id=M1M5R3BMVy13QmpScXkzTUt5OE46MTpjaQ&redirect_uri=https://www.example.com&scope=tweet.read%20users.read%20follows.read%20offline.access&state=state&code_challenge=challenge&code_challenge_method=plain
```
인증에 성공하면 redirect\_uri는 auth\_code 매개변수를 포함한 요청을 받게 됩니다. 애플리케이션은 state 매개변수를 확인해야 합니다.
클라이언트의 리다이렉트로부터의 예시 요청은 다음과 같습니다:
```
https://www.example.com/?state=state&code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE
```
**3단계: POST oauth2/token - Access Token**
이 시점에서 authorization code를 사용하여 액세스 토큰과 refresh token을 생성할 수 있습니다(`offline.access` 스코프가 요청된 경우에만). 다음 엔드포인트에 POST 요청을 할 수 있습니다:
```
https://api.x.com/2/oauth2/token
```
헤더를 통해 `application/x-www-form-urlencoded`의 `Content-Type`을 전달해야 합니다. 또한, 요청에 `code`, `grant_type`, `client_id` 및 `redirect_uri`, 그리고 `code_verifier`가 있어야 합니다.
다음은 public client에 대한 예시 토큰 요청입니다:
```json theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ' \
--data-urlencode 'redirect_uri=https://www.example.com' \
--data-urlencode 'code_verifier=challenge'
```
다음은 confidential client를 사용하는 예시입니다:
```json theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'code=VGNibzFWSWREZm01bjN1N3dicWlNUG1oa2xRRVNNdmVHelJGY2hPWGxNd2dxOjE2MjIxNjA4MjU4MjU6MToxOmFjOjE' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'redirect_uri=https://www.example.com' \
--data-urlencode 'code_verifier=challenge'
```
**4단계: API에 연결**
이제 OAuth 2.0을 사용하여 엔드포인트에 연결할 준비가 되었습니다. 이렇게 하려면 [Bearer Token 인증](/resources/fundamentals/authentication/oauth-2-0/application-only)을 사용하는 것과 마찬가지로 API에 요청합니다. Bearer Token을 전달하는 대신 마지막 단계에서 생성한 액세스 토큰을 사용합니다. 응답으로 요청하는 엔드포인트에 해당하는 적절한 페이로드가 표시되어야 합니다. 이 요청은 public 및 confidential 클라이언트 모두에게 동일합니다.
예시 요청은 다음과 같습니다:
```json theme={null}
curl --location --request GET 'https://api.x.com/2/tweets?ids=1261326399320715264,1278347468690915330' \
--header 'Authorization: Bearer Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE'
```
**5단계: POST oauth2/token - refresh token**
Refresh token을 사용하면 애플리케이션이 사용자에게 프롬프트하지 않고 새 액세스 토큰을 얻을 수 있습니다. 다음 엔드포인트에 POST 요청을 하여 refresh token을 생성할 수 있습니다: [https://api.x.com/2/oauth2/token](https://api.x.com/2/oauth2/token) 헤더를 통해 `application/x-www-form-urlencoded`의 `Content-Type`을 추가해야 합니다. 또한 refresh\_token을 전달하고 grant\_type을 `refresh_token`으로 설정하며 `client_id`를 정의해야 합니다.
이 요청은 public client에서 작동합니다:
```json theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ'
```
다음은 confidential client에 대한 예시입니다:
```json theme={null}
POST 'https://api.x.com/2/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'refresh_token=bWRWa3gzdnk3WHRGU1o0bmRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE'\
--data-urlencode 'grant_type=refresh_token'
```
**6단계: POST oauth2/revoke - Token 취소**
Revoke token은 액세스 토큰이나 refresh token을 무효화합니다. 이는 클라이언트에서 "log out" 기능을 활성화하는 데 사용되며, 더 이상 필요하지 않을 수 있는 승인 흐름과 관련된 보안 자격 증명을 정리할 수 있게 합니다. Revoke token은 App이 사용자가 아닌 토큰을 취소하기 위한 것입니다. App이 부여된 액세스를 프로그래밍 방식으로 취소하려는 경우 다음 URL에 POST 요청을 하여 revoke token 요청을 생성할 수 있습니다:
```
https://api.x.com/2/oauth2/revoke
```
헤더를 통해 `application/x-www-form-urlencoded`의 `Content-Type`, 토큰 및 client\_id를 전달해야 합니다.
경우에 따라 사용자가 App에 부여한 액세스를 취소하려는 경우 [연결된 앱 페이지](https://x.com/settings/connected_apps)를 방문하여 액세스를 취소할 수 있습니다.
```bash theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/revoke' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE' \
--data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ'
```
이 요청은 confidential client에서 작동합니다:
```bash theme={null}
curl --location --request POST 'https://api.x.com/2/oauth2/revoke' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='\
--data-urlencode 'token=Q0Mzb0VhZ0V5dmNXSTEyNER2MFNfVW50RzdXdTN6STFxQlVkTGhTc1lCdlBiOjE2MjIxNDc3NDM5MTQ6MToxOmF0OjE'
```
# 인증
Source: https://docs.x.com/ko/fundamentals/authentication/overview
X API는 엄청난 양의 데이터를 처리하며, 인증은 이 데이터를 개발자와 사용자 모두를 위해 보호하는 핵심 방법입니다. OAuth 1.0a, OAuth 2.0, bearer token, PKCE 등 X API가 지원하는 인증 방식의 개요와 선택 기준을 소개합니다.
X API는 엄청난 양의 데이터를 처리하며, 인증은 개발자와 사용자 모두를 위해 그 데이터를 보호합니다. 아래 나열된 여러 인증 방법 중에서 선택할 수 있습니다.
대부분의 개발자는 인증의 복잡성을 직접 처리할 필요가 없습니다 — 클라이언트 라이브러리가 자동으로 처리합니다.
사용 가능한 클라이언트 라이브러리 목록은 [도구 및 라이브러리](/resources/tools-and-libraries) 페이지에서 확인할 수 있습니다.
## 인증 방법
OAuth 1.0a를 통해 승인된 X 개발자 앱이 비공개 계정 정보에 액세스하거나 X 계정을 대신하여 X 작업을 수행할 수 있습니다.
[**자세히 알아보기**](/resources/fundamentals/authentication/oauth-1-0a/api-key-and-secret)
App only Access Token을 통해 X 개발자 앱이 X에서 공개적으로 사용 가능한 정보에 액세스할 수 있습니다.
[**자세히 알아보기**](/resources/fundamentals/authentication/oauth-2-0/overview)
X의 많은 엔터프라이즈 API는 HTTP Basic Authentication 사용을 요구합니다.
[**자세히 알아보기**](/resources/fundamentals/authentication/basic-auth)
OAuth 2.0 User Context를 사용하면 애플리케이션 스코프에 대한 더 큰 제어와 여러 디바이스에 걸친 인증 흐름으로 다른 계정을 대신하여 인증할 수 있습니다.
[**자세히 알아보기**](/resources/fundamentals/authentication/oauth-2-0/authorization-code)
**참고:**
[Developer Console](/resources/fundamentals/developer-portal)의 [X 개발자 앱](/resources/fundamentals/developer-apps) 섹션에서 앱의 API Key, App-only Access Token, 개인 Access Token 및 Access Token Secret을 얻을 수 있습니다.
**다른 사용자를 대신하여 요청을 보내려면** [3-legged OAuth flow](https://developer.x.com/resources/fundamentals/authentication/obtaining-user-access-tokens)를 사용해 해당 사용자에 대한 별도의 Access Token 세트를 생성한 다음, 해당 사용자의 토큰을 OAuth 1.0a User Context 또는 OAuth 2.0 user context 요청과 함께 전달하세요.
## 추가 리소스
통합 가이드를 사용해 토큰을 생성하고 요청을 인증하는 방법을 알아보세요.
인증 엔드포인트에 대한 레퍼런스 가이드를 검토하세요.
자신을 보호하고 키와 토큰을 저장하는 모범 사례를 확실히 이해하세요.
질문이 있으신가요? FAQ를 확인하세요.
# 글자 수 계산
Source: https://docs.x.com/ko/fundamentals/counting-characters
280자 제한, 가중치 코드 포인트, t.co URL 단축, 이모지와 Unicode 처리, 결합 문자 및 엣지 케이스를 포함하여 X가 게시물의 글자 수를 계산하는 방식을 설명하고, 클라이언트에서 정확한 길이를 검증하기 위한 라이브러리도 안내합니다.
X의 게시물은 최대 **280자**를 포함할 수 있습니다. 그러나 모든 문자가 동일하게 계산되지는 않습니다 — 이모지, URL 및 특정 Unicode 범위에는 특별한 계산 규칙이 적용됩니다.
***
## 문자 가중치
X는 가중치가 적용된 문자 계산 시스템을 사용합니다. 대부분의 문자는 1로 계산되지만 일부는 2로 계산됩니다:
| 문자 유형 | 가중치 | 최대 글자 수 |
| :------------------ | :----- | :------- |
| Latin, 구두점, 일반 기호 | 1 | 280 |
| 이모지 | 2 | 이모지 140개 |
| CJK (중국어, 일본어, 한국어) | 2 | 글자 140개 |
| 기타 Unicode | 2 (기본) | 다양함 |
오픈 소스 [twitter-text](https://github.com/twitter/twitter-text) 라이브러리를 사용해 앱에서 정확하게 글자 수를 계산하세요.
***
## 이모지 계산
모든 이모지는 복잡도와 관계없이 **2자**로 계산됩니다:
| 이모지 | 표시 | 글자 수 | Unicode |
| :---------- | :------ | :--- | :--------------- |
| 👾 | 단일 이모지 | 2 | U+1F47E |
| 🙋🏽 | 피부톤 포함 | 2 | 🙋 + 🏽 modifier |
| 👨🎤 | ZWJ로 결합 | 2 | 👨 + ZWJ + 🎤 |
| 👨👩👧👦 | 가족 시퀀스 | 2 | 이모지 4개 + ZWJ 3개 |
Zero-width joiner(ZWJ)는 이모지를 시각적으로 결합하지만 글자 수에는 추가되지 않습니다.
***
## URL 처리
모든 URL은 `t.co` 단축기로 래핑되며 원래 길이와 관계없이 **23자**로 계산됩니다:
```
https://example.com → 23 characters
https://example.com/very/long/path → 23 characters
```
이는 게시물 텍스트에서 감지된 유효한 모든 URL에 적용됩니다.
***
## 특수 케이스
| 콘텐츠 | 계산 규칙 |
| :---------- | :----------------------------- |
| **답글의 @멘션** | 답글 시작 부분의 자동 채워진 @멘션은 계산되지 않음 |
| **신규 @멘션** | 수동으로 추가하는 @멘션은 일반적으로 계산됨 |
| **미디어** | (공식 클라이언트를 통한) 첨부 미디어는 0자로 계산됨 |
| **해시태그** | 일반적으로 계산됨(# + 태그 텍스트) |
***
## 텍스트 인코딩
X API는 **UTF-8** 인코딩을 요구합니다. 글자 길이는 Unicode Normalization Form C (NFC)를 사용하여 계산됩니다.
`café`의 예:
| 형식 | 바이트 | 글자 수 |
| :--------------- | :---------- | :--- |
| NFC (composed) | `c a f é` | 4 |
| NFD (decomposed) | `c a f e ́` | 5 |
X는 NFC로 정규화하므로 두 형식 모두 4자로 인코딩됩니다.
***
## 구현
정확한 글자 수 계산을 위해 공식 [twitter-text](https://github.com/twitter/twitter-text) 라이브러리를 사용하세요:
```javascript theme={null}
import { parseTweet } from 'twitter-text';
const result = parseTweet('Hello, world! 👋');
console.log(result.weightedLength); // 16
console.log(result.valid); // true
```
```python theme={null}
from twitter_text import parse_tweet
result = parse_tweet('Hello, world! 👋')
print(result.weightedLength) # 16
print(result.valid) # True
```
라이브러리는 이모지 시퀀스, URL 감지, Unicode 정규화를 포함한 모든 엣지 케이스를 처리합니다.
***
## 리소스
텍스트 파싱을 위한 공식 오픈 소스 라이브러리입니다.
문자 가중치 정의 및 Unicode 범위입니다.
# 앱
Source: https://docs.x.com/ko/fundamentals/developer-apps
X 개발자 앱을 만들고 구성하여 API 자격 증명을 발급받고, OAuth 1.0a 및 OAuth 2.0 권한 스코프를 설정하고, 콜백 URL과 웹사이트 URL을 관리하며, API 키와 액세스 토큰을 안전하게 회전하는 방법을 단계별로 안내합니다.
앱은 API 자격 증명을 담는 컨테이너입니다. 각 앱에는 고유한 키, 토큰 및 설정이 있습니다.
***
## 앱 자격 증명
앱을 만들면 다음 자격 증명을 생성할 수 있습니다:
| 자격 증명 | 사용 사례 |
| :------------------------ | :------------------------------------------------- |
| **API Key & Secret** | OAuth 1.0a로 인증합니다. 요청에 서명하거나 사용자 토큰을 생성하는 데 사용됩니다. |
| **Access Token & Secret** | 자신의 계정을 대신하여 요청을 보냅니다(OAuth 1.0a). |
| **Client ID & Secret** | OAuth 2.0으로 인증합니다. authorization code flow에 사용됩니다. |
| **Bearer Token** | 공개 데이터 엔드포인트를 위한 앱 전용 인증입니다. |
새 프로젝트에는 **OAuth 2.0**을 선택하세요. 세분화된 스코프를 제공하며 X API v2 사용자 컨텍스트 엔드포인트에 필수입니다.
***
## 앱 만들기
[console.x.com](https://console.x.com)으로 이동하여 로그인합니다.
앱의 이름, 설명 및 사용 사례를 입력합니다.
생성 후 필요한 키와 토큰을 생성합니다.
자격 증명은 한 번만 표시되므로 즉시 저장하세요.
***
## 앱 권한 (OAuth 1.0a)
OAuth 1.0a 앱에는 세 가지 권한 수준이 있습니다:
* 게시물, 사용자 및 공개 데이터 보기
* 게시, 좋아요 또는 무엇도 수정할 수 없음
* 다이렉트 메시지 액세스 불가
* 모든 읽기 권한
* 게시물 작성 및 삭제
* 사용자 팔로우/언팔로우
* 좋아요 및 리포스트
* 다이렉트 메시지 액세스 불가
* 모든 읽기 및 쓰기 권한
* 다이렉트 메시지 송수신
권한을 변경하려면 업데이트된 스코프로 새 토큰을 받기 위해 사용자가 앱을 다시 승인해야 합니다.
***
## OAuth 2.0 앱 유형
OAuth 2.0을 구성할 때 앱 유형을 선택하세요:
| 유형 | 클라이언트 | 사용 사례 |
| :---------------------- | :----------- | :----------------------------- |
| **Web App** | Confidential | 시크릿을 안전하게 저장할 수 있는 서버 측 애플리케이션 |
| **Automated App / Bot** | Confidential | 서버에서 실행되는 봇 및 자동화 서비스 |
| **Native App** | Public | 시크릿을 보호할 수 없는 모바일 또는 데스크톱 앱 |
| **Single Page App** | Public | 브라우저 기반 JavaScript 앱 |
**Confidential 클라이언트**는 Client Secret을 받습니다. **Public 클라이언트**는 PKCE만 사용합니다.
***
## 콜백 URL
콜백 URL(redirect URI)은 OAuth 흐름에 필수입니다. 사용자가 앱을 승인하면 인증 코드와 함께 콜백 URL로 리다이렉트됩니다.
### 요구 사항
* Developer Console에서 앱의 허용 목록에 콜백 URL을 추가하세요
* URL이 정확히 일치해야 합니다(후행 슬래시 포함)
* 앱당 최대 **10개의 콜백 URL**
* 프로덕션에서는 `https://` 사용
* 로컬 개발 시 `localhost`가 아닌 `http://127.0.0.1`을 사용하세요
### 허용되지 않는 프로토콜
다음 프로토콜은 사용할 수 없습니다: `javascript`, `data`, `file`, `ftp`, `mailto`, `telnet` 및 기타 비표준 스키마.
`vbscript`, `javascript`, `vbs`, `data`, `mocha`, `keyword`, `livescript`, `ftp`, `file`, `gopher`, `acrobat`, `callto`, `daap`, `itpc`, `itms`, `firefoxurl`, `hcp`, `ldap`, `mailto`, `mmst`, `mmsu`, `msbd`, `rtsp`, `mso-offdap`, `snews`, `news`, `nntp`, `outlook`, `stssync`, `rlogin`, `telnet`, `tn3270`, `shell`, `sip`
***
## 모범 사례
개발, 스테이징, 프로덕션을 위해 서로 다른 앱을 만드세요.
주기적으로 그리고 손상이 의심되는 경우 키를 재생성하세요.
앱이 실제로 필요한 권한만 요청하세요.
Developer Console을 정기적으로 확인하여 API 사용량을 추적하세요.
***
## 자동화 계정 라벨
앱이 봇 계정을 실행하는 경우 자동화로 라벨링할 수 있습니다:
1. 봇 계정의 **Settings**로 이동
2. **Your account** → **Automation** 선택
3. 관리 계정 연결
이는 사용자의 신뢰를 구축하고 봇을 스팸과 구별합니다.
***
## 문제 해결
콜백 URL이 프로토콜 및 후행 슬래시를 포함하여 Developer Console에 등록된 것과 정확히 일치하는지 확인하세요. 쿼리 매개변수로 전달할 때는 URL을 HTTP 인코딩하세요.
```json theme={null}
{
"errors": [{
"code": 415,
"message": "Callback URL not approved for this client application."
}]
}
```
앱이 정지된 것으로 표시되면 X 플랫폼 팀의 통지를 이메일에서 확인하세요. 항의하려면 [Platform Help Form](https://help.x.com/forms/platform)을 사용하세요.
# Developer Console
Source: https://docs.x.com/ko/fundamentals/developer-portal
X Developer Console(포털)을 사용하여 프로젝트와 앱을 관리하고, API 사용량과 요청 수를 모니터링하고, 자격 증명에 액세스하며, 팀 구성원을 초대하고, 액세스 티어 업그레이드와 결제 정보 및 인보이스를 확인하는 방법을 소개합니다.
[Developer Console](https://console.x.com)은 X API 액세스 관리를 위한 중앙 허브입니다. 앱 생성, 자격 증명 생성, 사용량 모니터링, 결제 관리를 한곳에서 할 수 있습니다.
***
## 할 수 있는 작업
API 자격 증명을 받기 위해 앱을 설정합니다. 인증, 권한, 콜백 URL을 구성하세요.
실시간으로 API 사용량을 추적합니다. 엔드포인트별 비용을 확인하고 크레딧 잔액을 관리하세요.
앱에 대한 API 키, 액세스 토큰 및 OAuth 자격 증명을 만드세요.
사용량 기반 결제를 위해 크레딧을 구매합니다. 구독이나 약정이 필요 없습니다.
***
## 시작하기
[console.x.com](https://console.x.com)으로 이동해 X 계정으로 로그인합니다. 개발자 계약에 동의하세요.
**New App**을 클릭하고 이름과 설명을 입력합니다. API 자격 증명이 생성됩니다.
API Key, API Secret 및 Access Token을 복사하여 안전하게 저장하세요. 다시 표시되지 않습니다.
자격 증명을 사용해 API 요청을 인증하세요. [빠른 시작 가이드](/x-api/getting-started/make-your-first-request)를 확인하세요.
**자격 증명을 안전하게 저장하세요.** API 키와 토큰은 생성 시 한 번만 표시됩니다. 비밀번호 관리자 또는 안전한 보관소를 사용하세요. 분실 시 재생성해야 하며, 기존 자격 증명은 무효화됩니다.
***
## 결제 & 크레딧
X API는 크레딧 기반 시스템과 사용량 기반 가격을 사용합니다:
| 기능 | 설명 |
| :------------ | :--------------------------------- |
| **월 요금 없음** | 사용한 만큼만 지불 — 구독 없음 |
| **크레딧 기반** | 크레딧을 미리 구매하고 API 사용 시 차감 |
| **실시간 추적** | 콘솔 대시보드에서 사용량 및 비용 모니터링 |
| **엔드포인트별 가격** | 엔드포인트마다 다른 비용 |
| **중복 제거** | 24시간 이내에 동일한 리소스를 두 번 요청해도 한 번만 과금 |
[Developer Console](https://console.x.com)에서 현재 가격을 확인하고 크레딧을 구매하세요.
[가격에 대해 자세히 알아보기 →](/x-api/getting-started/pricing)
***
## 팀 관리
팀 관리는 **Enterprise 계정**에서만 사용할 수 있습니다.
Enterprise 계정은 팀 구성원을 초대하여 협업할 수 있습니다:
| 역할 | 기능 |
| :---------------- | :--------------------------- |
| **Administrator** | 전체 액세스: 앱, 결제, 팀 구성원 및 역할 관리 |
| **Developer** | 자신의 앱 관리, 팀 앱에 대한 읽기 전용 액세스 |
팀 구성원을 초대하려면 콘솔의 Team 페이지로 이동해 X 핸들을 입력하세요.
***
## 다음 단계
앱 설정, 권한 및 자격 증명에 대해 알아보세요.
자격 증명을 사용해 API를 호출하세요.
# 속도 제한
Source: https://docs.x.com/ko/fundamentals/rate-limits
앱 수준과 사용자 수준 제한, 15분 창 재설정, 응답 헤더(x-rate-limit-*) 해석, 지수 백오프와 재시도 모범 사례를 포함하여 액세스 티어와 엔드포인트 전반의 X API v2 속도 제한을 이해하고 429 오류를 예방하는 방법을 안내합니다.
속도 제한은 주어진 기간 내에 보낼 수 있는 API 요청 수를 제어합니다. 이는 플랫폼 전반의 공정한 사용과 시스템 안정성을 보장합니다.
***
## 제품별 속도 제한
각 X API 제품은 고유한 속도 제한 방식을 가집니다:
15분 기준 윈도우에 기반한 엔드포인트별 제한입니다. 자세한 표와 복구 팁을 확인하세요.
엔터프라이즈 계약 및 데이터 패키지에 기반한 맞춤형 제한입니다.
광고 관리 및 분석 엔드포인트 전용 제한입니다.
***
## 속도 제한 작동 방식
| 개념 | 설명 |
| :---------- | :------------------------------------- |
| **시간 윈도우** | 대부분의 제한은 15분마다 재설정됩니다 |
| **사용자별 제한** | OAuth 1.0a 또는 OAuth 2.0 사용자 토큰 사용 시 적용 |
| **앱별 제한** | Bearer Token(앱 전용) 인증 사용 시 적용 |
| **엔드포인트별** | 각 엔드포인트마다 고유한 제한이 있습니다 |
***
## 제한 확인
모든 API 응답에는 현재 속도 제한 상태를 보여주는 헤더가 포함됩니다:
```
x-rate-limit-limit: 900
x-rate-limit-remaining: 847
x-rate-limit-reset: 1705420800
```
| 헤더 | 설명 |
| :----------------------- | :-------------------- |
| `x-rate-limit-limit` | 현재 윈도우에서 허용되는 최대 요청 수 |
| `x-rate-limit-remaining` | 현재 윈도우에서 남은 요청 수 |
| `x-rate-limit-reset` | 제한이 재설정되는 Unix 타임스탬프 |
***
## 속도 제한 오류
속도 제한을 초과하면 **429 Too Many Requests** 응답을 받습니다:
```json theme={null}
{
"errors": [{
"code": 88,
"message": "Rate limit exceeded"
}]
}
```
***
## 모범 사례
API 응답을 로컬에 저장하여 동일한 데이터에 대한 반복 요청을 줄이세요.
속도 제한에 걸리면 재시도 전 대기하세요. 각 재시도마다 대기 시간을 두 배로 늘리세요.
속도 제한 헤더를 모니터링하여 제한에 미리 대비하세요.
실시간 데이터의 경우 검색 엔드포인트 폴링 대신 filtered stream을 사용하세요.
***
## 다음 단계
엔드포인트별 자세한 속도 제한 표는 해당 API의 속도 제한 페이지를 참조하세요:
* [X API v2 속도 제한](/x-api/fundamentals/rate-limits)
* [X Ads API 속도 제한](/x-ads-api/fundamentals/rate-limiting)
# 보안
Source: https://docs.x.com/ko/fundamentals/security
자격 증명 저장, OAuth 토큰 처리, 정기적인 API 키 회전, 안전한 콜백 URL 구성, 취약점 공개 및 신고 절차, 최소 권한 스코프 원칙을 포함한 X API 개발자를 위한 보안 모범 사례로, 앱과 사용자 데이터를 안전하게 보호하는 방법을 안내합니다.
안전한 애플리케이션을 구축하면 사용자와 X 플랫폼 모두를 보호합니다. 이 가이드는 X API 개발자를 위한 필수 보안 관행을 다룹니다.
***
## 핵심 요구 사항
모든 API 요청은 HTTPS를 사용해야 합니다. 평문 HTTP는 거부됩니다.
API 키나 토큰을 클라이언트 측 코드, 로그 또는 저장소에 노출하지 마세요.
***
## 자격 증명 보호
API 키와 토큰은 앱의 핵심입니다. 안전하게 보관하세요:
자격 증명을 코드가 아닌 환경 변수에 저장하세요.
```bash theme={null}
export X_API_KEY="your-api-key"
export X_API_SECRET="your-api-secret"
```
자격 증명 파일을 `.gitignore`에 추가하세요. `git-secrets` 같은 도구를 사용해 실수로 커밋되는 것을 방지하세요.
키를 주기적으로 그리고 손상이 의심되는 경우 즉시 재생성하세요.
앱이 실제로 필요한 OAuth 스코프만 요청하세요.
### 자격 증명이 손상된 경우
1. [Developer Console](https://console.x.com)에서 **즉시 재생성**하세요
2. **기존 토큰 무효화** — 재생성하면 기존 자격 증명이 자동으로 무효화됩니다
3. **사용량 감사** — 무단 API 활동을 확인하세요
4. **앱 업데이트** — 모든 환경에 새 자격 증명을 배포하세요
***
## 애플리케이션 보안
### 입력 검증
사용자 입력을 절대 신뢰하지 마세요. 사용하기 전에 모든 데이터를 검증하고 정제하세요:
```python theme={null}
# Bad - vulnerable to injection
query = f"from:{user_input}"
# Good - validate input first
import re
if re.match(r'^[a-zA-Z0-9_]{1,15}$', user_input):
query = f"from:{user_input}"
```
### 출력 인코딩
XSS를 방지하기 위해 X API 데이터를 HTML에 표시하기 전에 이스케이프하세요:
```javascript theme={null}
// Bad - vulnerable to XSS
element.innerHTML = tweet.text;
// Good - escape HTML
element.textContent = tweet.text;
```
### 방지해야 할 일반적인 취약점
| 취약점 | 방지 |
| :----------------- | :--------------------------------------- |
| **XSS** | 렌더링 전에 사용자 생성 콘텐츠를 모두 이스케이프 |
| **CSRF** | 양식에 anti-CSRF 토큰 사용; OAuth state 매개변수 검증 |
| **SQL Injection** | 매개변수화된 쿼리 사용, 사용자 입력을 절대 연결하지 않음 |
| **Open redirects** | 허용 목록에 대해 콜백 URL 검증 |
***
## OAuth 보안
### state 매개변수
CSRF를 방지하기 위해 OAuth 흐름에서 항상 `state` 매개변수를 사용하세요:
```python theme={null}
import secrets
# Generate state before authorization
state = secrets.token_urlsafe(32)
session['oauth_state'] = state
# Verify state after callback
if request.args.get('state') != session.get('oauth_state'):
abort(403) # State mismatch - possible CSRF
```
### 토큰 저장
| 토큰 유형 | 저장 권장 사항 |
| :----------------- | :------------------------ |
| **Access tokens** | 암호화된 데이터베이스 또는 안전한 보관소 |
| **Refresh tokens** | 추가 액세스 제어가 있는 암호화된 데이터베이스 |
| **Bearer tokens** | 환경 변수 또는 안전한 구성 |
***
## 안전한 개발 관행
정기적인 보안 검토 및 침투 테스트를 수행하세요.
의존성을 최신 상태로 유지하세요. 취약한 패키지를 감지하기 위한 도구를 사용하세요.
보안 이벤트를 로깅하되 자격 증명이나 민감한 데이터는 절대 로깅하지 마세요.
비정상적인 API 사용 패턴에 대한 알림을 설정하세요.
***
## 보안 문제 보고
X에 영향을 미치는 보안 취약점을 발견한 경우:
**48시간 이내에 보고.** X Developer Platform 사용자는 보안 인시던트 의심 후 48시간 이내에 X에 알려야 합니다.
HackerOne을 통해 X 시스템의 취약점을 보고하세요.
X 데이터를 사용하는 앱이 침해된 경우 동일한 채널을 통해 보고하세요.
***
## 준수 체크리스트
* [ ] 모든 API 요청이 TLS/HTTPS 사용
* [ ] 자격 증명이 안전하게 저장됨(코드나 로그에 없음)
* [ ] 사용자 토큰이 저장 시 암호화됨
* [ ] 모든 사용자 제공 데이터에 대한 입력 검증
* [ ] XSS 방지를 위한 출력 인코딩
* [ ] OAuth 흐름에 CSRF 보호
* [ ] 보안 로깅 활성화(민감한 데이터 제외)
* [ ] 인시던트 대응 계획 문서화
* [ ] 의존성이 정기적으로 업데이트됨
* [ ] 최소 OAuth 스코프 요청
***
## 리소스
OAuth를 올바르게 구현하세요.
최소 필수 권한을 구성하세요.
# X ID
Source: https://docs.x.com/ko/fundamentals/x-ids
형식, 순서, ID 인플레이션, JavaScript 클라이언트에서 정수 정밀도 손실을 피하는 안전한 처리 방법을 포함하여 X API의 게시물 및 사용자에 대한 64비트 Snowflake ID를 이해하고, 항상 문자열 표현(id_str)을 사용하는 이유를 확인하세요.
X API의 모든 객체 — 게시물, 사용자, 리스트, DM, spaces — 에는 고유 ID가 있습니다. 이러한 ID가 어떻게 작동하는지 이해하면 안정적인 통합을 구축할 수 있습니다.
***
## ID 형식
X ID는 "Snowflake"라는 시스템을 사용해 생성된 **64비트 부호 없는 정수**입니다. 각 ID는 다음을 인코딩합니다:
* **타임스탬프** — 객체가 언제 생성되었는지
* **워커 번호** — 어떤 서버가 ID를 생성했는지
* **시퀀스 번호** — 해당 밀리초 내 순서
이는 ID가 대략 시간순으로 정렬됨을 의미합니다: 더 높은 ID는 일반적으로 더 새로운 객체를 나타냅니다.
ID는 단일 객체 유형 내에서만이 아니라 X 전체에서 전역적으로 고유합니다.
***
## 문자열 vs. 정수 표현
**코드에서는 항상 문자열 ID를 사용하세요.** 일부 프로그래밍 언어(예: JavaScript)는 64비트 정수를 정확하게 표현할 수 없습니다.
JavaScript에서 정수는 53비트로 제한됩니다. 이로 인해 큰 ID에서 정밀도가 손실됩니다:
```javascript theme={null}
// This loses precision!
const id = 10765432100123456789;
console.log(id.toString()); // "10765432100123458000" — wrong!
// Use strings instead
const id = "10765432100123456789";
console.log(id); // "10765432100123456789" — correct!
```
### API 버전
| 버전 | ID 형식 |
| :------------- | :--------------------------------------------- |
| **X API v2** | ID가 기본적으로 문자열로 반환됨 |
| **X API v1.1** | `id`(정수)와 `id_str`(문자열) 모두 반환 — 항상 `id_str` 사용 |
***
## ID 작업
### ID 저장
데이터베이스에 ID를 문자열 또는 64비트 정수로 저장하세요:
| 데이터베이스 | 권장 유형 |
| :--------- | :--------------------------------- |
| PostgreSQL | `BIGINT` 또는 `TEXT` |
| MySQL | `BIGINT UNSIGNED` 또는 `VARCHAR(20)` |
| MongoDB | String |
| SQLite | `TEXT` (SQLite 정수는 최대 63비트) |
### ID 비교
시간순으로 ID를 비교할 때:
```python theme={null}
# Python - safe for 64-bit integers
if int(id1) > int(id2):
print("id1 is newer")
# JavaScript - compare as strings (lexicographically works for same-length IDs)
# Or use BigInt
if (BigInt(id1) > BigInt(id2)) {
console.log("id1 is newer");
}
```
***
## 일반적인 ID 유형
| 객체 | 예시 ID | 비고 |
| :----------- | :-------------------- | :------------------- |
| Post (Tweet) | `1234567890123456789` | Tweet ID라고도 함 |
| User | `2244994945` | 오래된 계정은 더 짧은 ID를 가짐 |
| List | `1234567890` | |
| Space | `1YqGodQbNXDxv` | 영숫자, Snowflake 형식 아님 |
| DM Event | `1234567890123456789` | |
***
## 관련 리소스
각 객체 유형에 대한 ID 필드를 확인하세요.
ID로 게시물을 가져오세요.
# X 개발자 플랫폼 라이브 스트림
Source: https://docs.x.com/ko/livestreams
제품 워크스루, 기술적 심층 분석, AMA 세션 및 통합 튜토리얼을 포함한 X 개발자 플랫폼 라이브 스트림 녹화를 시청하세요.
개발자 커뮤니티가 우리 도구로 학습하고 구축할 수 있도록 설계된 X 개발자 플랫폼에 대한 이전 방송의 녹화 및 재생을 확인하세요.
여기에는 심층 분석, 시작 가이드 등이 포함됩니다.
## 과거 방송
# 첫 요청 보내기
Source: https://docs.x.com/ko/make-your-first-request
cURL 또는 Postman을 사용하여 인증 설정, 엔드포인트 선택, JSON 응답 파싱을 포함한 첫 X API v2 요청을 몇 분 안에 보내는 방법을 안내합니다. bearer token 준비부터 게시물 조회 예제까지 단계별로 확인하세요.
이 가이드는 첫 X API 요청을 보내는 과정을 안내합니다. 시작하기 전에 [앱 자격 증명이 있는 개발자 계정](/x-api/getting-started/getting-access)이 필요합니다.
***
## cURL로 빠르게 시작하기
API를 테스트하는 가장 빠른 방법은 cURL입니다. 사용자를 조회해 봅시다:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
`$BEARER_TOKEN`을 실제 Bearer Token으로 바꾸세요. 다음과 같은 응답을 받게 됩니다:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## 단계별 가이드
[Developer Console](https://console.x.com)에서 앱으로 이동해 Bearer Token을 복사하세요.
다음 입문자 친화적인 엔드포인트 중 하나로 시작하세요:
| 엔드포인트 | 기능 |
| :------------------------------------------------ | :----------------------- |
| [User lookup](/x-api/users/lookup/introduction) | 사용자명 또는 ID로 사용자 프로필 가져오기 |
| [Post lookup](/x-api/posts/lookup/introduction) | ID로 게시물 가져오기 |
| [Recent search](/x-api/posts/search/introduction) | 최근 7일간의 게시물 검색 |
cURL, Postman 또는 선호하는 HTTP 클라이언트를 사용하세요:
```bash theme={null}
# Look up a user by username
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
응답은 JSON 형식입니다. 기본 데이터는 `data` 필드에 있습니다:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## fields로 더 많은 데이터 요청하기
기본적으로 엔드포인트는 최소한의 필드만 반환합니다. 추가 데이터를 요청하려면 `fields` 매개변수를 사용하세요:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers?user.fields=created_at,description,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
응답:
```json 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 Platform",
"public_metrics": {
"followers_count": 570842,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
[fields에 대해 자세히 알아보기 →](/x-api/fundamentals/fields)
***
## 더 많은 예제
```bash theme={null}
curl "https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=from:xdevelopers&tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/tweets?max_results=5" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## cURL 대신 코드 사용하기
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/users/by/username/xdevelopers"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers)
print(response.json())
```
```javascript theme={null}
const bearerToken = "YOUR_BEARER_TOKEN";
const url = "https://api.x.com/2/users/by/username/xdevelopers";
fetch(url, {
headers: { Authorization: `Bearer ${bearerToken}` }
})
.then(res => res.json())
.then(data => console.log(data));
```
프로덕션 환경에서는 공식 SDK 사용을 권장합니다:
* [Python SDK](/xdks/python/overview)
* [TypeScript SDK](/xdks/typescript/overview)
인증, 페이지네이션, 속도 제한을 자동으로 처리합니다.
***
## 테스트 도구
컬렉션으로 시각적 API 테스트를 수행합니다.
여러 언어로 된 예제입니다.
전체 엔드포인트 문서입니다.
***
## 문제 해결
* Bearer Token이 올바른지 확인하세요
* 토큰이 재발급되지 않았는지 확인하세요
* `Authorization` 헤더 형식을 확인하세요: `Bearer YOUR_TOKEN`
* 앱에 이 엔드포인트 액세스 권한이 없을 수 있습니다
* 일부 엔드포인트는 사용자 컨텍스트 인증(OAuth 1.0a 또는 2.0)이 필요합니다
* Developer Console에서 앱의 권한을 확인하세요
* 속도 제한에 도달했습니다
* 재시도 시점을 확인하려면 `x-rate-limit-reset` 헤더를 확인하세요
* 코드에 지수 백오프를 구현하세요
[전체 오류 레퍼런스 →](/x-api/fundamentals/response-codes-and-errors)
***
## 다음 단계
사용자 컨텍스트 요청을 위한 OAuth를 이해하세요.
무엇을 만들 수 있는지 알아보세요.
공식 라이브러리로 더 빠르게 개발하세요.
무엇을 만들지에 대한 아이디어입니다.
# 개발자 뉴스 구독
Source: https://docs.x.com/ko/newsletter
제품 업데이트, 새로운 엔드포인트, 지원 중단, 이벤트 및 API 개발자를 위한 기타 뉴스를 위한 X 개발자 플랫폼 뉴스레터를 구독하세요.
X 개발자 팀의 최신 뉴스, 제품 업데이트 및 이벤트에 대한 이메일에 등록하세요.
# X 개발자 플랫폼
Source: https://docs.x.com/ko/overview
X의 실시간 글로벌 데이터를 활용해 구축, 분석, 혁신하세요. 유연한 사용량 기반 가격으로 최신 v2 API를 통해 게시물, 사용자, 트렌드, Spaces, 리스트, DM에 액세스하고 필터링된 스트림과 검색 엔드포인트도 사용할 수 있습니다.
## 제품
요구 사항에 맞는 액세스 수준을 선택하세요.
약정 없이 크레딧 기반 가격으로 사용하세요. 사용한 만큼만 지불합니다.
대용량 엔드포인트, 전담 계정 관리, 맞춤형 속도 제한을 제공합니다.
X API 크레딧을 구매하면 무료 [xAI API](https://docs.x.ai) 크레딧을 받을 수 있습니다 — 지출 금액에 따라 최대 20% 적립. [자세히 알아보기](/x-api/getting-started/pricing#free-xai-api-credits)
***
## 시작하기
Owned Reads를 통해 본인의 데이터에 더 낮은 비용으로 액세스할 수 있습니다. 본인 게시물, 북마크, 팔로워, 좋아요 등에 대한 요청은 리소스당 \$0.001의 가격으로 제공됩니다.
API 키를 받고 몇 분 안에 첫 요청을 보내세요.
게시물, 사용자, Spaces, DM, 리스트 등 다양한 엔드포인트를 살펴보세요.
빠른 개발을 위한 공식 Python 및 TypeScript SDK입니다.
***
## 리소스
일반적인 사용 사례와 통합을 위한 단계별 가이드입니다.
모든 언어를 위한 공식 SDK 및 커뮤니티 라이브러리입니다.
커뮤니티와 X 팀의 도움을 받으세요.
AI 기반 개발을 위한 llms.txt, skill.md, MCP 서버 및 리소스입니다.
***
## 기타 제품
프로그래밍 방식으로 광고 캠페인, 타겟팅, 크리에이티브, 분석을 관리하세요.
# X 개발자 플랫폼 상태
Source: https://docs.x.com/ko/status
X API v2, Enterprise API, Ads API, 스트리밍 및 Webhook 엔드포인트, 개발자 포털, 지원 서비스의 실시간 상태입니다. 진행 중인 인시던트, 해결된 장애, 과거 가동 시간과 다운타임 기록을 확인할 수 있습니다.
모든 시스템이 정상적으로 작동 중입니다.
정상정상정상
***
## 인시던트 기록
### 2026년 7월
인시던트가 해결되었습니다. | **6월 30일 23:00 UTC - 7월 1일 01:00 UTC**
### 2026년 6월
인시던트가 해결되었습니다. | **6월 22일, 12:00 UTC - 15:41 UTC**
인시던트가 해결되었습니다. | **6월 17일, 02:20 UTC - 03:45 UTC**
### 2026년 4월
인시던트가 해결되었습니다. | **4월 14일, 21:00 UTC - 21:30 UTC**
인시던트가 해결되었습니다. | **4월 1일, 20:15 UTC - 20:30 UTC**
### 2026년 3월
인시던트가 해결되었습니다. | **3월 31일, 20:45 UTC - 21:00 UTC**
인시던트가 진행 중입니다. | **3월 24일, 02:00 UTC - 현재**
인시던트가 해결되었습니다. | **3월 27일, 23:20 UTC - 3월 28일, 00:56 UTC**
인시던트가 해결되었습니다. | **3월 24일, 15:20:00 UTC - 18:00:00 UTC**
인시던트가 해결되었습니다. | **3월 24일, 15:20:00 UTC - 18:00:00 UTC**
### 2026년 2월
인시던트가 해결되었습니다. | **2월 16일, 18:20 UTC - 19:50 UTC**
인시던트가 해결되었습니다. | **2월 16일, 13:27 UTC - 14:29 UTC**
### 2026년 1월
인시던트가 해결되었습니다. | **1월 29일, 04:00 UTC - 04:45 UTC**
인시던트가 해결되었습니다. | **1월 29일, 04:00 UTC - 04:45 UTC**
인시던트가 해결되었습니다. | **1월 25일, 17:00 UTC - 19:00 UTC**
인시던트가 해결되었습니다. | **1월 24일, 16:48 UTC - 20:30 UTC**
인시던트가 해결되었습니다. | **1월 23일, 19:25 UTC - 20:30 UTC**
인시던트가 해결되었습니다. | **1월 22일, 17:30 UTC - 17:45 UTC**
인시던트가 해결되었습니다. | **1월 16일, 15:39 UTC - 21:00 UTC**
### 2025년 12월
인시던트가 해결되었습니다. | **12월 5일, 7:00 UTC - 10월 15일, 8:40 UTC**
### 2025년 9월
인시던트가 해결되었습니다. | **9월 10일, 20:30 UTC - 9월 11일, 04:30 UTC**
인시던트가 해결되었습니다. | **9월 10일, 20:30 UTC - 9월 10일, 22:00 UTC**
### 2025년 8월
인시던트가 해결되었습니다. | **8월 12일, 01:00 UTC - 8월 12일, 13:30 UTC**
### 2025년 5월
인시던트가 해결되었습니다. | **6월 26일, 17:00 UTC - 6월 26일, 17:45 UTC**
인시던트가 [해결](https://downdetector.com/status/google/)되었습니다. | **6월 12일, 15:00 UTC - 6월 12일, 23:00 UTC**
인시던트가 해결되었습니다. | **5월 30일, 20:20 UTC - 5월 30일, 21:00 UTC**
인시던트가 해결되었습니다. | **5월 30일, 18:45 UTC - 5월 30일, 21:00 UTC**
인시던트가 해결되었습니다. | **5월 28일, 17:00 UTC - 5월 28일, 21:41 UTC**
인시던트가 해결되었습니다. | **5월 23일, 17:35 UTC - 5월 27일, 00:00 UTC**
인시던트가 해결되었습니다. | **5월 22일, 18:00 UTC**
인시던트가 해결되었습니다. | **5월 09일, 05:00 - 5월 09일, 07:00 UTC**
### 2025년 4월
인시던트가 해결되었습니다. | **4월 02일, 17:10 - 4월 02일, 20:30 UTC**
인시던트가 해결되었습니다. | **4월 02일, 13:09 - 4월 02일, 13:51 UTC**
### 2025년 3월
인시던트가 해결되었습니다. | **3월 10일, 12:00 - 3월 11일, 00:00 UTC**
### 2025년 2월
인시던트가 진행 중입니다. | **2월 6일, 00:00**
인시던트가 해결되었습니다. | **2월 3일, 17:30 - 2월 4일, 01:00 UTC**
### 2025년 1월
과거 인시던트가 없습니다.
과거 인시던트가 없습니다.
### 2024년 12월
과거 인시던트가 없습니다.
과거 인시던트가 없습니다.
# 성공 사례
Source: https://docs.x.com/ko/success-stories
마케팅, 리서치, 헬스케어, 금융 분야의 사례 연구를 포함하여 X API로 구축한 개발자 및 기업의 고객 성공 사례입니다.
전 세계의 기업과 개인이 X 개발자 플랫폼을 사용하여 창의적으로 혁신하고, 귀중한 인사이트를 얻으며, 미래를 형성하고 있습니다.
## 성공 사례 살펴보기
# 개발자 지원
Source: https://docs.x.com/ko/support
개발자 커뮤니티 포럼, Stack Overflow, GitHub 이슈, 상태 페이지, 티켓 문의를 포함한 X API의 지원 채널을 확인하세요. 문제 해결 팁, 담당자 연락 방법, API 장애 및 유지 관리 알림 구독 방법도 함께 소개합니다.
문제를 해결하든, 가이드를 찾든, 다른 개발자와 연결하고 싶든, 저희가 도와드립니다.
***
## 커뮤니티 및 도움말
질문하고, 프로젝트를 공유하며, X 개발자 커뮤니티와 팀의 도움을 받으세요. 기술적 질문에 대한 지원을 받기에 가장 좋은 곳입니다.
X API v2, Enterprise API, Developer Console의 현재 운영 상태를 확인하세요.
***
## 연락처 및 양식
엔터프라이즈 수준의 API 액세스에 관심이 있으신가요? 관심을 표명하면 저희 팀이 연락드립니다.
Self-serve 및 Enterprise API 구독에 대한 결제 문의를 받으세요.
정책, 준수 또는 특정 사용 사례에 대한 승인이 필요하신가요? 정책팀에 문의하세요.
***
## 문서 및 리소스
X API가 처음이신가요? 여기에서 API 키를 받고 첫 요청을 보내세요.
모든 X API v2 엔드포인트, 매개변수, 응답 형식에 대한 완전한 레퍼런스입니다.
OAuth 1.0a, OAuth 2.0 및 API 요청 인증 방법에 대해 알아보세요.
개발 속도를 높이기 위한 공식 Python 및 TypeScript SDK입니다.
속도 제한과 애플리케이션에서 이를 처리하는 방법을 이해하세요.
API 오류 코드와 일반적인 문제를 해결하는 방법에 대한 레퍼런스입니다.
***
## 정책 및 가이드라인
X API로 빌드할 때 허용되는 것과 그렇지 않은 것에 대한 실용적인 가이드입니다.
X API 액세스에 대한 구속력 있는 법적 약관입니다.
X에서 빌드할 때의 규칙과 기대 사항입니다.
금지되었거나 특별 승인이 필요한 활동입니다.
***
## 문제 해결 팁
* API 키와 토큰이 올바른지 다시 확인하세요
* 엔드포인트에 적합한 인증 방법을 사용하고 있는지 확인하세요(OAuth 1.0a vs OAuth 2.0)
* 앱에 필요한 권한(읽기, 쓰기, DM 액세스)이 있는지 확인하세요
* 토큰이 만료되지 않았는지 확인하세요 — 필요한 경우 재발급하세요
* API 응답의 `x-rate-limit-*` 헤더를 확인하여 사용량을 모니터링하세요
* 429 오류를 받으면 지수 백오프를 구현하세요
* 가능한 경우 응답을 캐시하여 API 호출을 줄이세요
* 더 높은 한도를 위해 액세스 티어 업그레이드를 고려하세요
* 자세한 정보는 [속도 제한 가이드](/x-api/fundamentals/rate-limits)를 참조하세요
* 정지 원인을 이해하려면 [개발자 가이드라인](/developer-guidelines)을 검토하세요
* 정지에 대한 X의 커뮤니케이션이 있는지 이메일을 확인하세요
* [Policy Support form](https://help.x.com/forms/platform)을 통해 항의를 제출하세요
* 일반적인 원인: 자동화된 좋아요, 원치 않는 DM/멘션, 스크래핑, 속도 제한 남용
* 적절한 플랜을 찾으려면 [가격 티어](/x-api/getting-started/pricing)를 검토하세요
* 엔터프라이즈 요구 사항은 [Enterprise API Interest 양식](/forms/enterprise-api-interest)을 제출하세요
* 액세스 업그레이드는 [Use Case Upgrade 양식](/forms/use-case/upgrade)을 사용하세요
* 전체 [API 레퍼런스](/x-api/introduction)를 둘러보세요
* 아직 v2에 없을 수 있는 [v1.1 엔드포인트](/x-api/migrate/overview)에 기능이 있는지 확인하세요
* 확실하지 않다면 [Developer Forums](https://devcommunity.x.com)에서 질문하세요
***
## 최신 정보 받기
최신 API 업데이트, 새로운 기능 및 변경 사항입니다.
공지 사항 및 개발자 뉴스를 위해 팔로우하세요.
과거 인시던트 및 해결 내역입니다.
# 도구 & 라이브러리
Source: https://docs.x.com/ko/tools-and-libraries
Python 및 TypeScript용 공식 X API SDK, xurl 같은 CLI 도구, 플레이그라운드 서버, AI 통합을 위한 MCP 서버와 커뮤니티 클라이언트 라이브러리를 소개합니다. 프로토타이핑, 테스트, 프로덕션 통합에 필요한 도구 모음입니다.
공식 SDK, 개발자 도구 및 커뮤니티 라이브러리로 개발 속도를 높이세요.
***
## 공식 SDK
비동기 지원, 타입 힌트, 자동 토큰 갱신을 제공합니다. 데이터 분석 및 자동화에 적합합니다.
완전한 타입 안전성 및 ESM 지원. Node.js 및 최신 번들러에서 작동합니다.
### 빠른 시작
```bash theme={null}
pip install xdk
```
```python theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
for page in client.posts.search_recent(query="api", max_results=10):
if page.data and len(page.data) > 0:
print(page.data[0].text)
break
```
```bash theme={null}
npm install @xdevplatform/xdk
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ bearerToken: 'YOUR_BEARER_TOKEN' });
const userResponse = await client.users.getByUsername('XDevelopers');
console.log(userResponse.data?.username);
```
***
## 개발자 도구
모든 v2 엔드포인트에 대한 대화형 API 테스트입니다.
OAuth 인증이 내장된 X API용 curl 유사 CLI입니다. 수동 토큰 관리가 없습니다.
실제 크레딧을 사용하지 않고 X API v2 엔드포인트를 테스트하기 위한 로컬 목 서버입니다.
XMCP, llms.txt, skill.md, docs MCP 서버 및 AI 기반 개발용 리소스입니다.
### 기타 도구
| 도구 | 설명 |
| :------------------------------------------------------ | :------------------------------ |
| [OpenAPI Spec](https://api.x.com/2/openapi.json) | 머신 판독 가능한 API 명세 |
| [twitter-text](https://github.com/twitter/twitter-text) | 게시물 텍스트 파싱 및 검증, 글자 수 계산 |
| [Embed Generator](https://publish.x.com/#) | 사이트에 임베드 가능한 게시물, 타임라인 또는 버튼 생성 |
***
## 커뮤니티 라이브러리
X API v2를 지원하는 커뮤니티 유지 관리 라이브러리입니다. 현재 지원 범위는 각 라이브러리의 문서를 확인하세요.
| 라이브러리 | 설명 |
| :----------------------------------------------------------- | :---------------------------- |
| [tweepy](https://github.com/tweepy/tweepy) | v2 지원이 포함된 인기 있는 Python 라이브러리 |
| [twarc](https://twarc-project.readthedocs.io/) | 데이터 수집을 위한 CLI 및 라이브러리 |
| [python-twitter](https://github.com/sns-sdks/python-twitter) | 간단한 Python 래퍼 |
| [TwitterAPI](https://github.com/geduldig/TwitterAPI) | 미니멀한 Python 래퍼 |
| 라이브러리 | 설명 |
| :------------------------------------------------------------------- | :---------------------------- |
| [node-twitter-api-v2](https://github.com/PLhery/node-twitter-api-v2) | 강력한 타입 지정, 풀 기능 Node.js 클라이언트 |
| [twitter.js](https://github.com/twitterjs/twitter.js) | 객체 지향 Node.js 라이브러리 |
| [twitter-v2](https://github.com/HunterLarco/twitter-v2) | 비동기 클라이언트 라이브러리 |
| 라이브러리 | 설명 |
| :-------------------------------------------------------------- | :--------------- |
| [go-twitter](https://github.com/g8rswimmer/go-twitter) | v2 API용 Go 라이브러리 |
| [gotwi](https://github.com/michimani/gotwi) | v2용 Go 래퍼 |
| [twitter-stream](https://github.com/Fallenstedt/twitter-stream) | 필터링된 스트림 래퍼 |
| 라이브러리 | 설명 |
| :---------------------------------------------------- | :------------------- |
| [twittered](https://github.com/redouane59/twittered) | v2용 Java 클라이언트 |
| [twitter4j-v2](https://github.com/takke/twitter4j-v2) | Twitter4J v2 래퍼 |
| [KTweet](https://github.com/ChromasIV/KTweet) | Kotlin v2 라이브러리 |
| [Tweedle](https://github.com/tyczj/Tweedle) | Kotlin Android 라이브러리 |
| 라이브러리 | 설명 |
| :---------------------------------------------------------------- | :---------------- |
| [twitter-api-v2-php](https://github.com/noweh/twitter-api-v2-php) | PHP v2 클라이언트 |
| [bird-elephant](https://github.com/danieldevine/bird-elephant) | PHP v2 라이브러리 |
| [twitteroauth](https://github.com/abraham/twitteroauth) | 인기 있는 OAuth 라이브러리 |
| 라이브러리 | 설명 |
| :---------------------------------------------------------------- | :-------------- |
| [tweetkit](https://github.com/julianfssen/tweetkit) | Ruby v2 클라이언트 |
| [twitter\_oauth2](https://github.com/nov/twitter_oauth2) | OAuth 2.0 라이브러리 |
| [omniauth-twitter2](https://github.com/unasuke/omniauth-twitter2) | OmniAuth 전략 |
| 언어 | 라이브러리 |
| :------------- | :--------------------------------------------------------------------------------------------------------- |
| **C#/.NET** | [Tweetinvi](https://github.com/linvi/tweetinvi), [LinqToTwitter](https://github.com/JoeMayo/LinqToTwitter) |
| **Rust** | [twitter-v2](https://github.com/jpopesculian/twitter-v2-rs) |
| **Swift** | [Twift](https://github.com/daneden/Twift/), [TwitterAPIKit](https://github.com/mironal/TwitterAPIKit) |
| **R** | [academictwitteR](https://github.com/cjbarrie/academictwitteR) |
| **PowerShell** | [BluebirdPS](https://github.com/thedavecarroll/BluebirdPS) |
커뮤니티 라이브러리는 X가 유지 관리하지 않습니다. 지원 및 현재 상태에 대해서는 해당 저장소를 확인하세요.
***
## 코드 샘플
* [X API v2 Sample Code](https://github.com/xdevplatform/Twitter-API-v2-sample-code) — Python, JavaScript, Ruby 등의 예제
* [Code Samples Repo](https://github.com/xdevplatform/samples) — 공식 XDK를 사용한 예제
* [X Developer GitHub](https://github.com/xdevplatform) — 공식 저장소 및 도구
***
## X Ads API 라이브러리
X Ads API 전용 도구 및 라이브러리는 [Ads API 도구 및 라이브러리](/x-ads-api/tools-and-libraries) 페이지를 참조하세요.
# 에이전트 리소스
Source: https://docs.x.com/ko/tools/ai
llms.txt, skill.md, MCP 서버, OpenAPI 명세, 그리고 Grok, Cursor, Windsurf를 위한 통합 가이드를 포함하여 X API를 사용하는 AI 에이전트를 위한 리소스입니다.
AI 도구를 X API 및 그 문서에 연결하기 위한 리소스입니다.
***
## AI 도구에서 X API 사용
AI 에이전트가 X API 엔드포인트를 직접 호출할 수 있게 합니다.
**MCP 서버** — XMCP는 200개 이상의 X API 엔드포인트를 호출 가능한 MCP 도구로 노출합니다. Docs MCP를 사용하면 에이전트가 이 문서를 즉시 검색하고 읽을 수 있습니다.
**OpenAPI Spec** — 클라이언트를 자동 생성하거나 에이전트에 공급하기 위한 머신 판독 가능 API 정의([https://api.x.com/2/openapi.json)입니다](https://api.x.com/2/openapi.json\)입니다).
| 리소스 | 하는 일 | URL |
| :--------------- | :------------------------------------------------ | :----------------------------------------------------------- |
| **X MCP** | 호스팅 MCP 서버 — 에이전트가 검색, 사용자 조회, 북마크 관리 등을 할 수 있습니다 | [docs.x.com/tools/mcp](/tools/mcp) |
| **OpenAPI Spec** | 코드 생성 및 에이전트 도구를 위한 머신 판독 가능 API 정의 | [api.x.com/2/openapi.json](https://api.x.com/2/openapi.json) |
***
## AI 도구에서 X API 문서 읽기
AI 에이전트에게 X API가 어떻게 작동하는지에 대한 컨텍스트를 제공합니다.
**llms.txt / llms-full.txt** — LLM이 수집할 수 있는 문서 인덱스 및 전체 내용 Markdown 파일입니다.
**skill.md** — 에이전트에게 어떤 작업, 매개변수 및 제약이 존재하는지 정확히 알려주는 기능 요약(agentskills.io)입니다.
**Docs MCP** — MCP를 통해 AI 어시스턴트에서 직접 문서 페이지를 검색하고 읽습니다.
| 리소스 | 하는 일 | URL |
| :---------------- | :--------------------------------------- | :----------------------------------------------------------- |
| **llms.txt** | 문서 인덱스 — 페이지 제목, URL 및 설명 | [docs.x.com/llms.txt](https://docs.x.com/llms.txt) |
| **llms-full.txt** | 전체 컨텍스트 로딩을 위한 단일 파일의 전체 문서 | [docs.x.com/llms-full.txt](https://docs.x.com/llms-full.txt) |
| **skill.md** | 기능 요약 — 작업, 입력 및 제약 | [docs.x.com/skill.md](https://docs.x.com/skill.md) |
| **Docs MCP** | MCP 서버 — 에이전트가 즉시 문서 페이지를 검색하고 읽을 수 있습니다 | [docs.x.com/mcp](https://docs.x.com/mcp) |
# llms.txt & llms-full.txt
Source: https://docs.x.com/ko/tools/llms-txt
llms.txt 및 llms-full.txt를 사용하여 Cursor, Windsurf, Grok과 같은 AI 도구가 정확한 코드 생성을 위해 X API 문서에 구조화된 액세스를 제공합니다.
**llms.txt** — 모든 문서 페이지(제목, URL, 짧은 설명)의 구조화된 인덱스입니다. AI 도구에 무엇이 사용 가능한지에 대한 맵을 제공합니다.
**llms-full.txt** — 최대 컨텍스트를 위한 단일 Markdown 파일의 전체 문서입니다.
[`llms.txt` 표준](https://llmstxt.org)은 AI를 위한 사이트맵과 같습니다. LLM이 문서 구조를 이해하고 관련 콘텐츠를 찾는 데 도움이 되며, `sitemap.xml`이 검색 엔진에 도움이 되는 것과 유사합니다.
| 파일 | 포함 내용 | 최적 용도 |
| :-------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------- | :--------------------------------------- |
| [`llms.txt`](https://docs.x.com/llms.txt) | 큐레이션된 루트 인덱스 + 섹션 인덱스로 이동 링크 | 빠른 개요 및 에이전트 진입점 |
| [`x-api/llms.txt`](https://docs.x.com/x-api/llms.txt) | 370개 이상의 X API v2 레퍼런스 페이지 | Posts, Users, DMs, Streams, Compliance 등 |
| [`enterprise-api/llms.txt`](https://docs.x.com/enterprise-api/llms.txt) | Enterprise, Account Activity, GNIP, Webhooks | 과거 + 실시간 엔터프라이즈 데이터 |
| [`x-ads-api/llms.txt`](https://docs.x.com/x-ads-api/llms.txt) | Ads API (캠페인, 크리에이티브, 오디언스, 분석) | 광고 및 측정 |
| [`xdks/python/llms.txt`](https://docs.x.com/xdks/python/llms.txt) + [`xdks/typescript/llms.txt`](https://docs.x.com/xdks/typescript/llms.txt) | 전체 SDK 클라이언트 및 모델 레퍼런스 | Python 및 TypeScript/JavaScript 개발자 |
| [`llms-full.txt`](https://docs.x.com/llms-full.txt) | 하나의 Markdown 파일로 된 전체 문서 | 심층 추론을 위한 최대 컨텍스트 |
이러한 파일(그리고 `/x-api/llms.txt`, `/enterprise-api/llms.txt`, `/x-ads-api/llms.txt` 및 XDK 아래의 섹션별 인덱스)은 루트와 `/.well-known/` 아래에서 사용할 수 있습니다. 모든 문서 페이지는 깔끔한 Markdown을 위한 `.md` 접미사를 지원합니다(예: `https://docs.x.com/x-api/posts/get-post-by-id.md`).
***
## 사용 방법
**에이전트에게 강력히 권장:** 명시적인 사용 지침은 [AGENTS.md](https://docs.x.com/AGENTS.md) (또는 AGENT.md)를 먼저 읽으세요.
대부분의 AI 도구는 URL을 직접 수락합니다. URL만 제공하면 도구가 콘텐츠를 가져와 파싱합니다:
* **Grok**: `https://docs.x.com/llms-full.txt`를 채팅에 붙여넣고 X API에 대해 질문하세요
* **Cursor / Windsurf**: 프로젝트에 대한 문서 컨텍스트로 `https://docs.x.com/llms-full.txt`를 추가하세요
* **커스텀 에이전트**: 프로그래밍 방식으로 파일을 가져와 시스템 프롬프트 또는 컨텍스트 창에 포함하세요
```bash theme={null}
# 문서 인덱스 가져오기
curl https://docs.x.com/llms.txt
# 전체 문서 가져오기
curl https://docs.x.com/llms-full.txt
# 개별 페이지를 Markdown으로 가져오기
curl https://docs.x.com/tools/llms-txt.md
```
# MCP 서버
Source: https://docs.x.com/ko/tools/mcp
Grok, Cursor, Claude 같은 AI 도구를 xurl 실행과 문서 검색을 제공하는 호스팅된 Model Context Protocol 서버를 통해 X API 및 X 개발자 문서에 연결하여, 자연어로 엔드포인트를 호출하고 통합 코드를 자동 생성하세요.
AI 도구에서 X와 함께 작업할 수 있는 두 가지 [MCP](https://modelcontextprotocol.io)(Model Context Protocol) 서버가 제공됩니다:
| 서버 | 기능 | URL |
| :----------- | :-------------------------------------------------------- | :------------------------------------------------ |
| **X MCP** | X API 엔드포인트 호출 (게시물 검색, 사용자 조회, 북마크, 트렌드, 뉴스, Articles 등) | `https://api.x.com/mcp` (호스팅됨; `xurl mcp`를 통해 연결) |
| **Docs MCP** | X API 문서 검색 및 읽기 | `https://docs.x.com/mcp` (호스팅됨) |
***
## X MCP — X API
MCP 호환 AI 도구(Grok Build, Cursor, Claude, VS Code 등)를 **X API**에 직접 연결하여 전체 아카이브 검색, 사용자 조회, 북마크 관리, 트렌드 및 뉴스 가져오기, Articles 초안 작성을 모두 본인의 X 계정 권한으로 수행할 수 있습니다.
X API는 \*\*`https://api.x.com/mcp`\*\*에서 호스팅되는 **Streamable HTTP** MCP 서버를 노출합니다(프로토콜 `2025-06-18`, `serverInfo: xmcp`). 오픈 소스 **`xurl mcp`** 브리지를 통해 접근하며, 이 브리지가 OAuth를 처리하고 매 호출마다 최신 Bearer token을 주입합니다.
### 한눈에 보는 기능
| 카테고리 | 모델이 수행할 수 있는 작업 |
| ----------------- | ----------------------------------------- |
| **Posts** | 게시물 가져오기, 좋아요/리포스트/인용한 사용자 보기, 최근 카운트 |
| **Search** | 전체 아카이브 게시물 검색, 사용자 검색, 뉴스 검색 |
| **Users** | 현재 사용자 식별, ID/핸들로 조회, 사용자의 게시물·타임라인·멘션 읽기 |
| **Bookmarks** | 북마크 나열/추가/제거 및 북마크 폴더 관리 |
| **News & Trends** | 뉴스 기사 가져오기, 위치(WOEID)별 트렌드 가져오기 |
| **Articles** | Articles 초안 작성 및 게시 |
### 작동 방식
X의 OAuth는 *본인 소유의* 개발자 앱을 요구합니다(동적 클라이언트 등록이 없으며 `api.x.com/mcp`는 네이티브 MCP OAuth 디스커버리를 광고하지 않습니다). 따라서 클라이언트를 URL로 직접 가리키는 대신, 앱 ID를 소유하고 1회 로그인을 수행하며 토큰을 항상 최신 상태로 유지하는 작은 로컬 브리지를 실행합니다.
```mermaid theme={null}
flowchart LR
A["MCP client (Grok Build, Cursor, …)"] -- "stdio JSON-RPC" --> B["xurl mcp (local bridge)"]
B -- "HTTPS + Authorization: Bearer" --> C[("api.x.com/mcp")]
B <-- "OAuth2 PKCE login + auto-refresh" --> D["X OAuth"]
```
* 브리지는 **npm 런처**(`npx`)를 통해 실행되므로 **별도의 설치 단계가 필요 없습니다**.
* **캐시된 토큰 없이 처음 실행할 때**, 브라우저를 열어 1회 OAuth2 로그인을 수행한 후 토큰을 캐시하고 이후 **자동 갱신**합니다.
* 모든 진단 정보는 **stderr**로 출력되며, **stdout은 깔끔한 JSON-RPC 채널로 유지됩니다**.
### 시작하기
두 가지 경로 중 하나를 선택하세요:
* **간단 경로 — App-only Bearer.** 앱의 Bearer token을 MCP 클라이언트의 `Authorization` 헤더에 붙여넣습니다. 브리지도, 브라우저 로그인도 필요 없습니다. 읽기 전용 엔드포인트이며 사용자 컨텍스트가 없습니다(사용자로서 행동할 수 없음). 사용자 정의 헤더가 있는 원격 MCP를 지원하는 클라이언트에서 동작합니다.
* **풀 경로 — `xurl mcp` 브리지(OAuth 2.0 사용자 컨텍스트).** 로컬 브리지가 OAuth 2.0 PKCE 로그인을 처리하고 토큰을 자동 갱신하므로, 모델이 사용자 계정의 스코프로 동작합니다. 쓰기 작업(북마크, Articles)이나 모든 사용자 컨텍스트 도구에 필수입니다.
#### 간단 경로 (app-only Bearer)
1. [X 개발자 포털](https://developer.x.com)에서 **X 앱을 생성**합니다.
2. 앱의 "Keys and tokens" 페이지에서 **App-only Bearer token을 복사**합니다.
3. 토큰을 `Authorization` 헤더로 사용하여 클라이언트를 `https://api.x.com/mcp`에 연결하세요 — 아래 [App 전용 (직접 URL, 브리지 없음)](#app-only-direct-url-no-bridge) 스니펫을 참고하세요.
#### 풀 경로 (xurl bridge)
1. **OAuth 2.0**이 활성화된 **X 앱을 생성**합니다.
2. 첫 실행 시 브라우저 로그인에 필요한 **리다이렉트 URI** `http://localhost:8080/callback`을 앱에 등록합니다. 다른 URI를 사용하려면 `REDIRECT_URI`를 설정하고 해당 URI를 등록하세요.
3. **`CLIENT_ID`와 `CLIENT_SECRET`을 복사**하세요 — 클라이언트 설정에 입력해야 합니다. `xurl auth oauth2`를 수동으로 실행하는 경우(예: 아래의 헤드리스 흐름), 먼저 해당 셸에서 환경 변수로 export 하세요 — 이 값이 없으면 브라우저에서 로그인이 실패합니다.
4. **Node.js를 설치**해 두세요 (`npx`에 필요).
5. **[xurl](https://github.com/xdevplatform/xurl) 설치**를 권장합니다:
```bash theme={null}
brew install --cask xdevplatform/tap/xurl # Homebrew
npm install -g @xdevplatform/xurl # npm (global)
curl -fsSL https://raw.githubusercontent.com/xdevplatform/xurl/main/install.sh | bash
```
**첫 로그인에는 브라우저가 필요합니다.** 헤드리스/원격 환경에서는 먼저 `xurl auth oauth2 --headless`(코드 붙여넣기 방식)로 별도 인증을 수행하면, 이후 브리지는 캐시된 토큰을 재사용합니다. [Headless](/tools/mcp#headless--remote-machines)를 참고하세요.
### 클라이언트 연결
#### 1. Grok Build
```toml xurl bridge (~/.grok/config.toml) theme={null}
[mcp_servers.xapi]
command = "npx"
args = ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"]
enabled = true
startup_timeout_sec = 300 # give the first-run browser login time
[mcp_servers.xapi.env]
CLIENT_ID = "YOUR_X_APP_CLIENT_ID"
CLIENT_SECRET = "YOUR_X_APP_CLIENT_SECRET"
```
```toml App-only Bearer (~/.grok/config.toml) theme={null}
[mcp_servers.xapi]
url = "https://api.x.com/mcp"
enabled = true
[mcp_servers.xapi.headers]
Authorization = "Bearer YOUR_APP_ONLY_BEARER_TOKEN"
```
또는 한 번의 명령으로 xurl 브리지를 추가합니다(`-e` 플래그는 서버의 환경 변수가 되고, `--` 뒤의 인자는 `npx`로 전달됩니다):
```bash theme={null}
grok mcp add xapi npx \
-e CLIENT_ID=YOUR_X_APP_CLIENT_ID \
-e CLIENT_SECRET=YOUR_X_APP_CLIENT_SECRET \
-- -y @xdevplatform/xurl mcp https://api.x.com/mcp
```
확인 및 나열:
```bash theme={null}
grok mcp doctor xapi # ✓ server started, ✓ handshake OK, ✓ tools discovered
grok mcp list
```
도구를 처음 호출할 때(또는 `doctor` 실행 시) 브라우저가 열려 X 로그인을 진행합니다 — 1회 완료하면 됩니다.
#### 2. Cursor
`~/.cursor/mcp.json`(전역, 모든 프로젝트) 또는 `.cursor/mcp.json`(이 프로젝트만)을 생성하세요:
```json xurl bridge theme={null}
{
"mcpServers": {
"xapi": {
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": {
"CLIENT_ID": "YOUR_X_APP_CLIENT_ID",
"CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET"
}
}
}
}
```
```json App-only Bearer theme={null}
{
"mcpServers": {
"xapi": {
"url": "https://api.x.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_APP_ONLY_BEARER_TOKEN"
}
}
}
}
```
그런 다음 **Cursor → Settings → MCP**를 열고 **xapi**에 녹색 표시와 도구 목록이 표시되는지 확인하세요. 처음 사용할 때 Cursor가 브리지를 실행하고 브라우저가 열려 로그인을 진행합니다; 핸드셰이크가 완료되면 도구 목록이 채워집니다.
#### 3. Claude Desktop
`claude_desktop_config.json`을 편집하세요(macOS: `~/Library/Application Support/Claude/`, Windows: `%APPDATA%\Claude\`):
```json xurl bridge theme={null}
{
"mcpServers": {
"xapi": {
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": { "CLIENT_ID": "YOUR_X_APP_CLIENT_ID", "CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET" }
}
}
}
```
```json App-only Bearer theme={null}
{
"mcpServers": {
"xapi": {
"url": "https://api.x.com/mcp",
"headers": { "Authorization": "Bearer YOUR_APP_ONLY_BEARER_TOKEN" }
}
}
}
```
Claude Desktop을 재시작하면 X 도구가 도구(🔌) 메뉴에 표시됩니다.
#### 4. VS Code (GitHub Copilot / Agent mode)
`.vscode/mcp.json`에 추가하세요:
```json xurl bridge theme={null}
{
"servers": {
"xapi": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": { "CLIENT_ID": "YOUR_X_APP_CLIENT_ID", "CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET" }
}
}
}
```
```json App-only Bearer theme={null}
{
"servers": {
"xapi": {
"type": "http",
"url": "https://api.x.com/mcp",
"headers": { "Authorization": "Bearer YOUR_APP_ONLY_BEARER_TOKEN" }
}
}
}
```
#### 5. 모든 MCP 클라이언트
**xurl 브리지 (stdio):**
| 필드 | 값 |
| --------- | -------------------------------------------------------------- |
| `command` | `npx` |
| `args` | `["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"]` |
| `env` | `CLIENT_ID`, `CLIENT_SECRET` |
| 시작 타임아웃 | **≥ 300초** (첫 실행 로그인이 완료될 수 있도록) |
`xurl`을 네이티브로 설치했다면 `command`/`args`를 `"command": "xurl", "args": ["mcp", "https://api.x.com/mcp"]`로 교체하세요.
**App-only Bearer (원격 HTTP):**
| 필드 | 값 |
| ----------------------- | ----------------------------------- |
| `url` | `https://api.x.com/mcp` |
| `headers.Authorization` | `Bearer YOUR_APP_ONLY_BEARER_TOKEN` |
### 인증
#### OAuth 2.0 사용자 컨텍스트 (기본)
브리지는 **사용자 본인**으로 인증되며(PKCE 흐름), 도구는 사용자 계정의 스코프로 동작합니다. 자격 증명 해석 순서: **`CLIENT_ID`/`CLIENT_SECRET` 환경 변수 → `~/.xurl`에 있는 활성 앱**. 토큰은 `~/.xurl`에 캐시되고 자동으로 갱신됩니다(`401` 발생 시 강제 갱신 포함).
#### 첫 실행 브라우저 로그인
캐시된 토큰이 없으면 브리지는 stderr로 다음을 출력하고 브라우저를 엽니다:
```
[xurl mcp] no valid OAuth2 token; opening the browser to sign in -- complete the login to start the bridge...
[xurl mcp] authentication complete; starting bridge
```
MCP 핸드셰이크는 로그인이 완료될 때까지 보류됩니다 — 그래서 클라이언트에 넉넉한 `startup_timeout_sec`이 필요합니다.
#### 헤드리스 / 원격 환경
접근 가능한 브라우저가 없나요? 한 번 별도로 인증한 후 클라이언트를 시작하세요:
```bash theme={null}
# Required: the env block in your client config only applies to the bridge,
# not to manual xurl runs — export the credentials in this shell first.
export CLIENT_ID="YOUR_X_APP_CLIENT_ID"
export CLIENT_SECRET="YOUR_X_APP_CLIENT_SECRET"
xurl auth oauth2 --headless # prints an auth URL; you paste back the redirect URL/code
xurl auth oauth2 --app my-app --headless # for a specific app
```
#### App 전용 (직접 URL, 브리지 없음)
읽기 엔드포인트의 경우 브리지를 건너뛰고 **정적 App 전용 Bearer token**으로 클라이언트를 URL에 직접 연결할 수 있습니다 — 사용자 정의 헤더가 있는 원격 MCP를 지원하는 클라이언트에 유용합니다:
```toml theme={null}
# ~/.grok/config.toml
[mcp_servers.xapi_direct]
url = "https://api.x.com/mcp"
enabled = true
[mcp_servers.xapi_direct.headers]
Authorization = "Bearer YOUR_APP_ONLY_BEARER_TOKEN"
```
절충점: 자동 갱신이 없고 사용자 컨텍스트도 없습니다(사용자로서의 액션 불가). 전체 기능을 위해서는 브리지 사용을 권장합니다.
#### 여러 앱과 계정
OAuth 로그인은 **브라우저가 열릴 때 로그인되어 있는 X 계정**을 인증합니다 — 반드시 앱을 소유한 계정일 필요는 없습니다. 보조/봇 계정을 대신하여 게시하려는 경우, 로그인을 완료하기 전에 브라우저에서 해당 계정으로 전환하거나(또는 `-u`를 사용해 이전에 인증된 사용자를 선택하세요).
```bash theme={null}
xurl --app my-app mcp # bridge using a specific registered app
xurl mcp -u alice https://api.x.com/mcp # act as a specific OAuth2 user
```
클라이언트 설정에서는 `args`에 `"--app", "my-app"` 또는 `"-u", "alice"`를 추가하세요.
### 설정 레퍼런스
| 설정 | 위치 | 비고 |
| ----------------------------- | -------- | ------------------------------------------------------------ |
| `CLIENT_ID` / `CLIENT_SECRET` | `env` | X 앱 자격 증명(또는 `~/.xurl`의 등록된 앱에 의존) |
| `REDIRECT_URI` | `env` | 콜백을 재정의; 앱에 등록되어 있어야 함. 기본값 `http://localhost:8080/callback` |
| `startup_timeout_sec` | 클라이언트 설정 | 첫 실행 로그인이 완료되도록 **≥ 300**으로 설정 |
| `[URL]` 위치 인자 | `args` | 기본값 `https://api.x.com/mcp` |
| `--app NAME` | `args` | 특정 등록된 앱 사용 |
| `-u, --username` | `args` | 특정 OAuth2 사용자로 동작 |
고급 환경 변수 재정의(거의 필요 없음): `AUTH_URL`, `TOKEN_URL`, `API_BASE_URL`, `INFO_URL`.
### 검증 및 문제 해결
```bash theme={null}
grok mcp doctor xapi # Grok Build: end-to-end check
# or test the bridge by hand (Ctrl-C to exit):
npx -y @xdevplatform/xurl mcp https://api.x.com/mcp
```
| 증상 | 원인 / 해결 |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| 시작 시 클라이언트 타임아웃 | `startup_timeout_sec`를 300 이상으로 올리세요; 브리지가 브라우저 로그인을 대기 중입니다 |
| 브라우저가 열리지 않음 | 디스플레이 없음(헤드리스) → 먼저 `xurl auth oauth2 --headless`를 실행; `npx`가 해석되는지 확인 |
| `401` / `token refresh failed` | 앱 자격 증명이 잘못되었거나 리프레시 토큰이 폐기됨 → 다시 로그인(`xurl auth oauth2 [--app NAME]`) |
| 브라우저에 "Something went wrong — You weren't able to give access to the App" 표시 | `xurl`이 실행되는 위치에 `CLIENT_ID`/`CLIENT_SECRET`이 설정되지 않음 → 클라이언트의 `env` 블록에 넣거나, `xurl auth oauth2`를 수동으로 실행하기 전에 셸에서 `export` 하세요 |
| 브라우저에서 리다이렉트/콜백 오류 | `http://localhost:8080/callback`이 앱에 등록되지 않음(또는 `REDIRECT_URI` 불일치) |
| 로그인 후 `client-not-enrolled` | 앱이 올바른 X 패키지/환경에 없음 → 포털에서 **Pay-per-use** + **Production**으로 이동 |
| `npx`가 오래된 버전을 가져옴 | 프라이빗 레지스트리 미러가 기본값 → `args`에 `--registry=https://registry.npmjs.org/` 고정 |
| 비어 있거나 깨진 도구 출력 | 클라이언트를 `--verbose`로 실행하지 마세요; stdout은 깔끔한 JSON-RPC 채널로 유지되어야 합니다 |
### 보안 및 모범 사례
* **`~/.xurl`과 액세스 토큰을 비밀로 취급하세요** — 채팅, 로그, 공유 설정에 붙여넣지 마세요. 원시 비밀을 커밋하는 대신 환경 변수를 참조하는 프로젝트별 `.mcp.json`/`.grok/config.toml`을 선호하세요.
* MCP에는 **필요한 스코프만 가진 전용 앱을 사용**하세요.
* **쓰기는 속도 제한에 포함**되며(북마크, `article_publish`) 읽기보다 더 엄격합니다; 가끔 `429`가 발생할 수 있으니 백오프하세요.
* **브리지는 로컬에서 실행됩니다** — 자격 증명은 TLS를 통해 `api.x.com`에 전송되는 Bearer token을 제외하고 컴퓨터를 떠나지 않습니다.
***
## Docs MCP — 문서 검색
X API 문서를 위한 MCP 서버가 `https://docs.x.com/mcp`에 호스팅되어 있습니다. AI 도구에 연결하여 워크플로우를 벗어나지 않고 문서 페이지를 검색하고 읽을 수 있습니다.
### 사용 가능한 도구
| 도구 | 설명 |
| :----------- | :--------------------------------------- |
| `search_x` | X 문서 전반에서 관련 정보, 코드 예제, API 레퍼런스, 가이드 검색 |
| `get_page_x` | 경로로 특정 문서 페이지의 전체 내용 조회 |
### 설정
MCP 클라이언트 설정에 docs MCP 서버를 추가하세요:
```json theme={null}
{
"mcpServers": {
"x-docs": {
"url": "https://docs.x.com/mcp"
}
}
}
```
X API로 빌드하면서 AI 어시스턴트가 엔드포인트 세부 정보, 인증 가이드 또는 코드 예제를 실시간으로 조회하기를 원할 때 유용합니다.
***
## 두 서버를 함께 사용하기
두 MCP 서버를 동시에 연결할 수 있습니다. 이를 통해 AI 어시스턴트가 문서를 조회하는 동시에 API를 호출할 수 있습니다.
**Grok Build** (`~/.grok/config.toml`):
```toml theme={null}
[mcp_servers.xapi]
command = "npx"
args = ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"]
enabled = true
startup_timeout_sec = 300
[mcp_servers.xapi.env]
CLIENT_ID = "YOUR_X_APP_CLIENT_ID"
CLIENT_SECRET = "YOUR_X_APP_CLIENT_SECRET"
[mcp_servers.x-docs]
url = "https://docs.x.com/mcp"
enabled = true
```
**Cursor / Claude 스타일** (`mcp.json`):
```json theme={null}
{
"mcpServers": {
"xapi": {
"command": "npx",
"args": ["-y", "@xdevplatform/xurl", "mcp", "https://api.x.com/mcp"],
"env": {
"CLIENT_ID": "YOUR_X_APP_CLIENT_ID",
"CLIENT_SECRET": "YOUR_X_APP_CLIENT_SECRET"
}
},
"x-docs": {
"url": "https://docs.x.com/mcp"
}
}
}
```
***
## OpenAPI 사양
모든 X API v2 엔드포인트에 대한 머신 판독 가능한 API 사양입니다.
| 리소스 | URL |
| :---------------------- | :--------------------------------------------------------------------- |
| **OpenAPI Spec (JSON)** | [`https://api.x.com/2/openapi.json`](https://api.x.com/2/openapi.json) |
```bash theme={null}
curl https://api.x.com/2/openapi.json -o openapi.json
```
이를 사용하여 API 클라이언트를 자동 생성하고, [Postman](https://www.postman.com/xapidevelopers/x-api-public-workspace/collection/34902927-2efc5689-99c6-4ab6-8091-996f35c2fd80)으로 가져오고, 커스텀 AI 에이전트에 공급하거나 요청/응답 스키마를 검증할 수 있습니다.
# Python XDK
Source: https://docs.x.com/ko/tools/python-xdk
인증 설정, 페이지네이션 요청 및 스트리밍 예제를 포함하여 X API v2를 위한 공식 Python XDK 클라이언트 라이브러리를 설치하고 사용합니다.
[Python XDK](https://github.com/xdevplatform/xdk-py)는 X API v2의 공식 클라이언트 라이브러리입니다. 인증, 페이지네이션 및 스트리밍을 처리하므로 구축에 집중할 수 있습니다.
소스 코드, 이슈 및 릴리스.
***
## 설치
```bash theme={null}
pip install xdk
```
Python 3.8+가 필요합니다.
***
## 빠른 시작
```python theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
# Search for posts
for page in client.posts.search_recent(query="X API", max_results=10):
if page.data and len(page.data) > 0:
print(page.data[0].text)
break
```
***
## 주요 기능
| 기능 | 설명 |
| :------------ | :---------------------------------------------- |
| **OAuth 지원** | Bearer Token, PKCE가 포함된 OAuth 2.0, OAuth 1.0a |
| **자동 페이지네이션** | 수동 `next_token` 처리 없이 결과 반복 |
| **스트리밍** | 지속적 연결을 통한 실시간 데이터(filtered stream 등) |
| **전체 API 지원** | 모든 X API v2 엔드포인트 — 검색, 타임라인, filtered stream 등 |
***
## 인증
```python theme={null}
from xdk import Client
client = Client(bearer_token="YOUR_BEARER_TOKEN")
```
```python theme={null}
from xdk import Client
from xdk.oauth2_auth import OAuth2PKCEAuth
auth = OAuth2PKCEAuth(
client_id="YOUR_CLIENT_ID",
redirect_uri="YOUR_CALLBACK_URL",
scope="tweet.read users.read offline.access"
)
auth_url = auth.get_authorization_url()
tokens = auth.fetch_token(authorization_response=callback_url)
client = Client(bearer_token=tokens["access_token"])
```
```python theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
oauth1 = OAuth1(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
client = Client(auth=oauth1)
```
***
## 일반적인 메서드
| 카테고리 | 메서드 |
| :--------- | :----------------------------- |
| **Posts** | `client.posts.search_recent()` |
| **Users** | `client.users.get_me()` |
| **Spaces** | `client.spaces.get()` |
| **Lists** | `client.lists.get()` |
| **DMs** | `client.direct_messages.get()` |
***
## 자세히 알아보기
개발 설치, 사전 요구 사항 및 검증.
첫 요청 단계별 워크스루.
모든 인증 방법에 대한 자세한 가이드.
자동 페이지네이션 및 반복자.
filtered stream을 통한 실시간 데이터.
전체 클라이언트 및 모델 레퍼런스.
코드 예제는 [samples 저장소](https://github.com/xdevplatform/samples/tree/main/python)를 참조하세요.
# skill.md
Source: https://docs.x.com/ko/tools/skill-md
skill.md는 AI 에이전트가 X API로 무엇을 할 수 있는지 설명하는 구조화된 기능 요약이며, agentskills.io와 같은 도구에서 워크플로우를 활성화하는 데 사용됩니다.
[`skill.md`](https://docs.x.com/skill.md) 파일은 [agentskills.io 명세](https://agentskills.io/specification)를 따르며 AI 에이전트가 X API로 *무엇을 할 수 있는지*를 설명합니다. [`llms.txt`](/tools/llms-txt)는 페이지 디렉터리인 반면, `skill.md`는 기능 요약입니다 — 특정 작업, 필수 입력 및 제약 사항을 나열하여 에이전트가 API를 더 안정적으로 사용할 수 있게 합니다.
***
## 포함된 내용
* **기능(Capabilities)** — 에이전트가 달성할 수 있는 것(게시물 검색, 게시물 생성, 사용자 관리 등)
* **스킬(Skills)** — 필수 매개변수와 함께 카테고리별로 구성된 특정 작업
* **워크플로우(Workflows)** — 일반적인 작업을 위한 단계별 절차
* **컨텍스트(Context)** — 인증, rate limit 및 아키텍처에 대한 배경
```bash theme={null}
# skill 파일 가져오기
curl https://docs.x.com/skill.md
```
***
## 검색 엔드포인트
에이전트는 well-known 엔드포인트를 통해 프로그래밍 방식으로 skill 파일을 검색할 수 있습니다:
```bash theme={null}
# 검색 엔드포인트 (agent-skills 0.2.0 명세)
curl https://docs.x.com/.well-known/agent-skills/index.json
# 원본 검색 형식
curl https://docs.x.com/.well-known/skills/index.json
```
[skills CLI](https://www.npmjs.com/package/skills)를 지원하는 모든 에이전트에 X API 기능을 추가할 수 있습니다:
```bash theme={null}
npx skills add https://docs.x.com
```
# TypeScript XDK
Source: https://docs.x.com/ko/tools/typescript-xdk
인증, 타입 지정된 응답, 페이지네이션 및 스트리밍 예제와 함께 X API v2를 위한 공식 TypeScript XDK 클라이언트 라이브러리를 설치하고 사용합니다.
[TypeScript XDK](https://github.com/xdevplatform/twitter-api-typescript-sdk)는 X API v2의 공식 클라이언트 라이브러리입니다. 완전한 타입 안전성, 자동 페이지네이션 및 이벤트 기반 스트리밍을 제공합니다.
소스 코드, 이슈 및 릴리스.
***
## 설치
```bash npm theme={null}
npm install @xdevplatform/xdk
```
```bash yarn theme={null}
yarn add @xdevplatform/xdk
```
```bash pnpm theme={null}
pnpm add @xdevplatform/xdk
```
Node.js 16+ 및 TypeScript 4.5+가 필요합니다(TypeScript 사용 시).
***
## 빠른 시작
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ bearerToken: 'YOUR_BEARER_TOKEN' });
const userResponse = await client.users.getByUsername('XDevelopers');
console.log(userResponse.data?.username);
```
***
## 주요 기능
| 기능 | 설명 |
| :------------ | :-------------------------------------------- |
| **타입 안전성** | 모든 엔드포인트 및 매개변수에 대한 완전한 TypeScript 정의 |
| **인증** | Bearer Token, PKCE가 포함된 OAuth 2.0, OAuth 1.0a |
| **자동 페이지네이션** | 페이지네이션된 엔드포인트에 대한 비동기 반복 지원 |
| **스트리밍** | 자동 재연결이 있는 이벤트 기반 스트리밍 |
| **전체 API 지원** | Users, Posts, Lists, Bookmarks, Communities 등 |
***
## 인증
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ bearerToken: 'YOUR_BEARER_TOKEN' });
```
```typescript theme={null}
import { Client, OAuth2, generateCodeVerifier, generateCodeChallenge } from '@xdevplatform/xdk';
const oauth2 = new OAuth2({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
redirectUri: 'https://your-app.com/callback',
scope: ['tweet.read', 'users.read', 'offline.access'],
});
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
const authUrl = await oauth2.getAuthorizationUrl('state');
const tokens = await oauth2.exchangeCode(authCode, codeVerifier);
const client = new Client({ accessToken: tokens.access_token });
```
```typescript theme={null}
import { Client, OAuth1 } from '@xdevplatform/xdk';
const oauth1 = new OAuth1({
apiKey: 'YOUR_API_KEY',
apiSecret: 'YOUR_API_SECRET',
accessToken: 'YOUR_ACCESS_TOKEN',
accessTokenSecret: 'YOUR_ACCESS_TOKEN_SECRET'
});
const client = new Client({ oauth1: oauth1 });
```
***
## 일반적인 메서드
| 카테고리 | 메서드 |
| :--------- | :------------------------------- |
| **Posts** | `client.posts.search()` |
| **Users** | `client.users.getMe()` |
| **Spaces** | `client.spaces.findSpaceById()` |
| **Lists** | `client.lists.getList()` |
| **DMs** | `client.directMessages.lookup()` |
***
## 자세히 알아보기
패키지 관리자, TypeScript 설정 및 요구 사항.
모든 인증 방법에 대한 자세한 가이드.
비동기 반복 및 페이지네이션된 응답.
재연결이 있는 이벤트 기반 스트리밍.
전체 클라이언트, 인터페이스 및 타입 레퍼런스.
코드 예제는 [samples 저장소](https://github.com/xdevplatform/samples/tree/main/javascript)를 참조하세요.
# xurl — X API를 위한 curl 스타일 커맨드라인 클라이언트
Source: https://docs.x.com/ko/tools/xurl
내장 OAuth를 갖춘 X API용 curl 스타일 CLI인 xurl을 설치하고 사용하여 엔드포인트를 테스트하고, OAuth 1.0a 및 OAuth 2.0 요청에 자동 서명하고, 터미널에서 프로토타입을 빠르게 만들 수 있는 방법을 예제 명령과 함께 안내합니다.
[xurl](https://github.com/xdevplatform/xurl)은 X API를 위한 curl과 유사한 커맨드라인 도구입니다. OAuth 인증을 자동으로 처리해 주므로 토큰을 수동으로 관리하거나 요청에 서명할 필요 없이 API 요청을 보낼 수 있습니다.
소스 코드, 릴리스 및 문서.
***
## 설치
Go로 설치하거나 [releases](https://github.com/xdevplatform/xurl/releases)에서 미리 빌드된 바이너리를 다운로드하세요.
```bash theme={null}
go install github.com/xdevplatform/xurl@latest
```
***
## 설정
### 1. X 앱 만들기
xurl은 사용자 본인의 개발자 앱을 사용해 인증합니다. [X 개발자 포털](https://developer.x.com)에서:
1. **OAuth 2.0**이 활성화된 앱을 만들거나 엽니다.
2. 리다이렉트 URI `http://localhost:8080/callback`을 앱에 등록합니다.
3. "Keys and tokens" 페이지에서 앱의 **Client ID**와 **Client Secret**을 복사합니다.
### 2. 자격 증명 설정
xurl을 실행할 동일한 셸에서 자격 증명을 export 하세요:
```bash theme={null}
export CLIENT_ID="your-x-app-client-id"
export CLIENT_SECRET="your-x-app-client-secret"
```
### 3. 인증
```bash theme={null}
xurl auth oauth2
```
이 명령은 브라우저 기반 OAuth 흐름을 엽니다. 인증이 완료되면 xurl이 토큰을 `~/.xurl`에 로컬로 저장하므로 다시 인증할 필요가 없습니다.
브라우저에 \*\*"Something went wrong — You weren't able to give access to the App"\*\*이 표시된다면, xurl이 유효한 자격 증명 없이 로그인을 시작한 것입니다. `xurl auth oauth2`를 실행한 셸에서 `CLIENT_ID`와 `CLIENT_SECRET`이 export되어 있는지, 그리고 `http://localhost:8080/callback`이 앱에 리다이렉트 URI로 등록되어 있는지 확인하세요.
***
## 사용법
### 원시 API 요청
xurl을 curl처럼 사용하면 됩니다 — 인증 헤더는 자동으로 처리됩니다:
```bash theme={null}
# Look up a user
xurl /2/users/by/username/xdevelopers
# Search recent posts
xurl "/2/tweets/search/recent?query=from:xdevelopers&max_results=10"
# Create a post
xurl -X POST /2/tweets -d '{"text": "Hello from xurl!"}'
```
### 단축 명령어
xurl에는 일반적인 작업을 위한 내장 단축 명령어가 포함되어 있습니다:
```bash theme={null}
# Look up a user by username
xurl user xdevelopers
# Search recent posts
xurl search "X API"
# Post a tweet
xurl post "Hello from xurl!"
```
***
## 왜 xurl을 사용해야 하나요?
| 기능 | curl | xurl |
| :------------- | :--------------- | :------------------------ |
| **인증** | 수동 OAuth 헤더 설정 | 자동 — `xurl auth`를 한 번만 실행 |
| **토큰 관리** | 갱신/로테이션을 직접 처리 | 내장 토큰 저장 및 갱신 |
| **API 단축 명령어** | 전체 URL 필요 | 일반 작업을 위한 단축 명령어 |
| **요청 서명** | 수동 OAuth 1.0a 서명 | 모든 요청에 대해 자동 |
***
## AI 에이전트와 함께 xurl 사용하기
xurl에는 기능을 머신 판독 가능한 형식으로 기술한 [`SKILL.md`](https://github.com/xdevplatform/xurl/blob/main/SKILL.md) 파일이 포함되어 있습니다. AI 에이전트는 이를 이용해 사용자 대신 xurl 명령어를 어떻게 호출해야 하는지 이해할 수 있습니다.
```bash theme={null}
npx skills add https://github.com/xdevplatform/xurl
```
***
## 관련 자료
cURL 또는 SDK를 사용해 X API로 시작하세요.
모의 데이터로 로컬에서 엔드포인트를 테스트하세요 — API 크레딧이 필요 없습니다.
# 튜토리얼
Source: https://docs.x.com/ko/tutorials
Postman, Python, R을 이용한 예제부터 필터링된 스트리밍, 전체 아카이브 검색, webhook, OAuth 1.0a 및 OAuth 2.0 인증, 게시물 조회와 검색 등 일반적인 워크플로우를 단계별 코드와 함께 다루는 X API 튜토리얼 모음입니다.
user Post timeline 및 user mention timeline 엔드포인트를 사용해 지난 7일간의 사용자 게시물과 멘션을 살펴보는 방법을 알아보세요.
[**튜토리얼 보기**](/tutorials/explore-a-users-posts)
Postman을 사용해 X API 및 X Ads API에 요청을 보내는 방법을 알아보세요.
[**튜토리얼 보기**](/tutorials/postman-getting-started)
R을 사용해 user lookup 엔드포인트에 연결하고 X API v2에서 반환된 JSON으로 작업하는 방법을 알아보세요.
[**튜토리얼 보기**](/tutorials/getting-started-with-r-and-v2-of-the-x-api)
full-archive search 엔드포인트를 사용해 공개 X 데이터의 전체 기록을 검색하고, geo 태그가 지정된 게시물의 데이터 세트를 구축하며, 쿼리 결과를 페이지네이션하는 방법을 알아보세요.
[**튜토리얼 보기**](/tutorials/getting-historical-posts-using-the-full-archive-search-endpoint)
대규모로 게시물을 수집하고 메타데이터를 사용해 특정 카테고리 또는 하위 카테고리로 분류하는 방법에 대한 고수준 개요를 확인하세요.
[**튜토리얼 보기**](/tutorials/post-processing-x-data-with-the-google-cloud-platform)
# 무엇을 만들 수 있나요
Source: https://docs.x.com/ko/what-to-build
챗봇과 분석 대시보드부터 콘텐츠 조정 도구, 학술 연구 프로젝트, 커뮤니티 앱, 자동화 봇, 실시간 알림 서비스까지 X API를 활용한 다양한 프로젝트 아이디어와 사용 사례를 살펴보고, 아이디어별로 적합한 엔드포인트와 액세스 티어를 함께 확인하세요.
X API는 콘텐츠 조정, 분석, 커뮤니티 구축 등 다양한 가능성을 열어줍니다. 다음 프로젝트에 영감을 주는 아이디어를 소개합니다.
***
## 안전 및 콘텐츠 조정을 위한 구축
X에서 더 건강한 대화를 만들도록 돕습니다.
사용자가 답글을 관리하고, 콘텐츠를 필터링하며, 자신의 경험을 보호할 수 있도록 돕는 도구를 만드세요.
악의적인 콘텐츠를 탐지하고 신고하며, 일괄 차단 도구를 제공하세요.
**관련 엔드포인트:**
* [Blocks](/x-api/users/blocks/introduction) — 사용자 차단 및 차단 해제
* [Mutes](/x-api/users/mutes/introduction) — 계정 및 키워드 뮤트
* [Hide replies](/x-api/posts/hide-replies/introduction) — 원치 않는 답글 숨김
* [Manage posts](/x-api/posts/manage-tweets/introduction) — 답글 설정 제어
***
## 크리에이터를 위한 구축
사람들이 자신을 표현하고 청중을 늘릴 수 있도록 돕습니다.
게시물, 스레드, 콘텐츠 캘린더를 예약하세요.
여러 플랫폼과 형식에서 콘텐츠를 동기화하세요.
사용자가 긴 형식의 스레드를 작성하고 게시할 수 있도록 돕습니다.
대화에 가치를 더하는 유용한 봇을 만드세요.
**관련 엔드포인트:**
* [Manage posts](/x-api/posts/manage-tweets/introduction) — 게시물 작성 및 삭제
* [Media upload](/x-api/media/quickstart/media-upload-chunked) — 이미지 및 비디오 업로드
* [Spaces](/x-api/spaces/lookup/introduction) — 오디오 대화 검색
***
## 분석을 위한 구축
사용자가 자신의 영향력과 청중을 이해할 수 있도록 돕습니다.
참여도 지표, 성장 트렌드, 도달 범위를 시각화하세요.
팔로워, 참여 패턴, 인구 통계를 분석하세요.
해시태그, 주제, 대화량을 추적하세요.
계정을 비교하고 성과를 벤치마킹하세요.
**관련 엔드포인트:**
* [Metrics](/x-api/fundamentals/metrics) — 참여도 및 성과 데이터
* [Search posts](/x-api/posts/search/introduction) — 과거 및 최근 검색
* [Post counts](/x-api/posts/counts/introduction) — 볼륨 분석
* [Annotations](/x-api/fundamentals/post-annotations) — 주제 분류
***
## 커뮤니티를 위한 구축
사람들이 공통 관심사를 중심으로 연결되고 모일 수 있도록 돕습니다.
조정, 회원 관리, 참여 도구입니다.
Spaces, 라이브 이벤트, 그룹 활동을 조직하세요.
주제 또는 관심사별로 콘텐츠를 집계하고 큐레이션하세요.
특정 언어와 지역을 위한 도구를 만드세요.
**관련 엔드포인트:**
* [Lists](/x-api/lists/list-lookup/introduction) — 큐레이션된 계정 리스트
* [Spaces](/x-api/spaces/lookup/introduction) — 오디오 대화
* [Follows](/x-api/users/follows/introduction) — 관계 관리
***
## 연구를 위한 구축
공개 대화를 분석하고 인사이트를 추출하세요.
공개 담론, 정보 확산, 트렌드를 연구하세요.
기사를 소싱하고, 정보를 검증하며, 속보를 추적하세요.
브랜드 감성, 업계 트렌드, 경쟁사를 모니터링하세요.
모델을 학습하고, 네트워크를 분석하며, 행동 패턴을 연구하세요.
**관련 엔드포인트:**
* [Full-archive search](/x-api/posts/search/introduction) — 2006년까지의 게시물 검색
* [Filtered stream](/x-api/posts/filtered-stream/introduction) — 일치하는 게시물의 거의 실시간 수신
* [Post annotations](/x-api/fundamentals/post-annotations) — 엔티티 인식
* [Conversation ID](/x-api/fundamentals/conversation-id) — 스레드 재구성
***
## 선한 영향력을 위한 구축
긍정적인 영향을 미치기 위해 API를 활용하세요.
응급 상황을 모니터링하고, 지원을 조율하며, 인식을 확산하세요.
X를 누구나 더 쉽게 사용할 수 있도록 도구를 만드세요.
학습 도구, 교육 리소스, 튜토리얼을 만드세요.
사람들이 정보를 얻고 민주주의에 참여할 수 있도록 도우세요.
***
## AI 에이전트로 구축하기
AI 도구를 X API에 연결하고 지능적인 워크플로를 구축하세요.
XMCP를 사용해 AI 어시스턴트에게 X API 엔드포인트에 대한 직접 액세스 권한을 부여하세요 — 자연어로 게시물 작성, 검색, 계정 관리를 수행합니다.
감성 분석, 콘텐츠 생성, 자동 보고를 위해 X 데이터를 LLM에 공급하세요.
Grok, Cursor 또는 선호하는 AI 도구에 llms.txt로 X API에 대한 전체 컨텍스트를 제공하여 개발 속도를 높이세요.
트렌드를 모니터링하거나, 멘션에 응답하거나, 콘텐츠를 자동으로 큐레이션하는 에이전트를 만드세요.
**시작하기:**
* [XMCP](/tools/mcp#xmcp--x-api-endpoints) — X API용 MCP 서버
* [llms-full.txt](https://docs.x.com/llms-full.txt) — AI 도구에 전체 문서 제공
* [OpenAPI Spec](https://api.x.com/2/openapi.json) — 머신 판독 가능한 API 정의
[모든 에이전트 리소스 둘러보기](/tools/ai)
***
## 시작하기
만들 준비가 되셨나요? 다음 단계를 따르세요:
[개발자 계정에 가입](/x-api/getting-started/getting-access)하고 앱을 만드세요.
[첫 요청을 보내고](/x-api/getting-started/make-your-first-request) API를 살펴보세요.
사용하는 언어에 맞는 [SDK 또는 라이브러리](/tools-and-libraries)를 선택하세요.
작게 시작하고, 반복하며, 만든 것을 공유하세요!
***
## 작업물 공유하기
X API로 무언가를 만드셨나요? 함께 보고 싶습니다:
* [Developer Forum](https://devcommunity.x.com)에 공유하세요
* X에서 [@XDevelopers](https://x.com/XDevelopers)를 태그하세요
* [Success Stories](/success-stories)에 제출하세요
# 분석(Analytics)
Source: https://docs.x.com/ko/x-ads-api/analytics
X Ads API의 동기 및 비동기 분석 엔드포인트를 사용해 노출 수, 클릭 수, 동영상 조회 수, 인게이지먼트, 지출 등 광고 캠페인 성과 지표를 세분화 옵션과 그래뉼래리티 옵션을 지정해 가져오고 집계해 리포팅하는 방법을 안내합니다.
분석 지표는 파트너와 광고주가 X에서 프로모션 중인 콘텐츠의 성과를 이해하는 데 도움이 됩니다. 여기에는 노출 수, 클릭 수, 동영상 조회 수, 지출 금액과 같은 정보가 포함됩니다. 또한 파트너와 광고주는 도달한 오디언스의 다양한 세그먼트에 대한 상세 지표도 얻을 수 있습니다.
Ads API는 캠페인 성과 지표를 가져오는 두 가지 방식, 즉 동기와 비동기 방식을 지원합니다. 동기 분석 호출에서는 요청한 지표가 응답에 그대로 반환됩니다. 비동기 분석 엔드포인트에서는 연결된 "작업(job)"이 처리 완료된 후 다운로드 가능한 결과 파일에서 요청한 지표를 받을 수 있습니다. 동기 엔드포인트는 짧은 기간을 지원하며 실시간 캠페인 최적화에 이상적입니다. 비동기 엔드포인트는 훨씬 더 긴 기간을 지원하므로 더 많은 데이터를 가져오는 데 사용되며, 리포트 생성이나 과거 데이터 백필에 적합합니다.
## 세부 사항
### 동기 vs. 비동기
동기와 비동기 분석 엔드포인트의 차이점은 다음 표에 요약되어 있습니다. 이 정보는 개발자가 어떤 엔드포인트 세트를 사용할지 선택하는 데 도움이 되도록 제공됩니다.
| 기능 | 동기 | 비동기 |
| :------- | :------------------------ | :--------------------------- |
| 속도 제한 | 사용자 수준: 15분당 250 요청 | 계정 수준: 동시\\\* 작업 100개 |
| 기간 | 7일 | 90일(비세분화) 45일(세분화) |
| 세분화 | 미지원 | 지원 |
| 응답 반환 | 지표 데이터 | 작업의 처리 상태\\*\\* |
| 권장 사용 사례 | 실시간 최적화 사용자 인터페이스 요청 | 정기적으로 예약된 동기화 과거 데이터 백필 |
\* 이는 특정 시점에 처리 중 상태로 있을 수 있는 작업의 최대 수를 의미합니다.
\*\* 작업이 처리에 성공적으로 완료되면 URL이 반환됩니다. 이 URL에서 압축된(gzip) 결과 파일을 다운로드할 수 있습니다.
이를 제외하면 두 엔드포인트는 동일한 기능을 제공합니다.
### 사용 사례
주요 분석 사용 사례는 세 가지입니다.
1. 실시간 최적화: 성과 지표를 활용하여 활성 캠페인 업데이트
2. 동기화: 정기적으로 예약된 백그라운드 동기화
3. 신규 계정 온보딩: 과거 데이터 백필
동기 분석 엔드포인트는 최근 5\~15분 이내의 지표 변화에 기반하여 캠페인을 업데이트하는 실시간 최적화에 사용할 수 있습니다. 두 엔드포인트 모두 분석 동기화에 사용할 수 있습니다. 원하는 기간과 세분화 필요 여부에 따라 사용할 엔드포인트가 결정됨을 염두에 두세요. 신규 계정 온보딩은 비동기 분석 엔드포인트로만 수행해야 합니다. (동기 분석 엔드포인트는 대량의 데이터를 가져오는 데 사용해서는 안 됩니다.)
비동기 분석 엔드포인트는 지표가 백엔드 프로세스와 동기화되어 있는 경우 대시보드와 기타 UI 요소를 구동할 수 있습니다. 사용자 인터페이스 요청을 충족시키기 위해 비동기 분석 엔드포인트를 호출하지 않도록 구현해야 합니다.
### 요청 옵션
분석 요청은 광고 계정 범위로 제한되므로 리소스 경로에 계정 ID가 필요합니다. 아래에 나열된 요청 옵션은 쿼리 파라미터로 지정합니다. 다음 유형의 값이 필요합니다.
* Entities: 분석을 요청할 엔티티 유형 및 최대 20개의 엔티티 ID
* 기간: 시작 및 종료 시각, ISO 8601로 표현
* **참고:** 정시 단위(whole hours)로 표현해야 합니다
* 지표 그룹(Metric groups): 관련 지표의 하나 이상의 집합(각 지표 그룹 내 지표 목록은 Metrics and Segmentation 참고)
* 그래뉼래리티(Granularity): 지표가 반환되어야 하는 집계 수준 지정
* 게재 위치(Placement): X 내에서 게재된 광고와 외부에서 게재된 광고 중 어디에서 지표를 가져올지 결정
* **참고:** 요청당 단일 게재 위치 값만 지정할 수 있습니다
기간을 지정하려면 `start_time`과 `end_time` 요청 파라미터를 사용하세요. 이 값들은 지정된 그래뉼래리티에 따라 다음과 같이 정렬되어야 합니다.
1. `TOTAL`: 임의 기간 지정(엔드포인트의 제한 내)
2. `DAY`: 시작 시각과 종료 시각 모두 계정의 시간대 기준 자정에 정렬되어야 함
3. `HOUR`: 임의 기간 지정(엔드포인트의 제한 내)
종료 시각은 미포함(exclusive)입니다. 예를 들어 `start_time=2026-01-01T00:00:00Z`와 `end_time=2026-01-02T00:00:00Z`로 요청하면, 이 기간은 24시간만을 포함하므로 (이틀이 아니라) 하루치 분석 지표가 반환됩니다.
**세분화(Segmentation)**
세분화는 비동기 분석 엔드포인트에서만 사용할 수 있으며, 파트너와 광고주가 특정 타깃팅 값별로 분리된 지표를 가져올 수 있게 해줍니다. 세분화된 지표를 요청하려면 `segmentation_type` 요청 파라미터를 사용하세요. 세분화 옵션에 대한 자세한 내용은 [Metrics and Segmentation](/x-ads-api/analytics#metrics-and-segmentation)을 참고하세요.
## FAQ
Ads API 수치가 X Ads UI에 표시되는 값과 일치하지 않는 이유는 무엇인가요?
* 모든 게재 위치(`ALL_ON_TWITTER`, `SPOTLIGHT`, `TREND`)에 대한 데이터를 요청했는지 확인하세요.
* Ads API의 종료 시각은 미포함이며, Ads UI에서는 포함이라는 점을 기억하세요.
데이터를 요청한 시점에 따라 수치가 변하는 이유는 무엇인가요?
* 리포팅 지표는 사용 가능해지는 즉시 가져올 수 있습니다. 이는 거의 실시간으로 제공됩니다. 다만 초기 결과는 추정치이므로 변경될 수 있습니다. 지출 데이터를 제외하면 지표는 24시간 후에 확정됩니다.
* 지출 지표는 일반적으로 이벤트로부터 3일 이내에 확정됩니다. 그러나 (예: 스팸 필터링을 위해) 이벤트 발생일로부터 최대 14일까지 청구 데이터를 처리합니다.
특정 기간에 대해 어떤 엔티티 ID를 요청할지 어떻게 결정하나요?
* [Active Entities 엔드포인트](/x-ads-api/analytics#active-entities-2)를 사용하세요.
분석 응답의 모든 값이 `null`인 이유는 무엇인가요?
* 요청한 기간 동안 캠페인이 게재되지 않았을 가능성이 큽니다.
* [Active Entities 엔드포인트](/x-ads-api/analytics#active-entities-2)를 사용하여 어떤 엔티티에 대해 어떤 기간 동안 분석을 가져올지 결정하세요.
API는 `null` 값을 표시하는데 UI에서는 0으로 표시되는 이유는 무엇인가요?
* UI는 이러한 값을 0으로 표시하지만, 두 값은 동등합니다.
X 타임라인과 같은 세분화된 게재 위치와 관련된 지표를 어떻게 요청할 수 있나요?
* 분석에서는 다음 게재 위치 값을 지원합니다: `ALL_ON_TWITTER`, `SPOTLIGHT`, `TREND`.
삭제되거나 일시중지된 엔티티에 대한 지표를 가져올 수 있나요?
* 네. 엔티티의 상태는 분석 지표의 가용성에 영향을 주지 않습니다.
세분화된 값이 비세분화된 값과 일치하지 않는 이유는 무엇인가요?
* 이 정보가 도출되는 방식 때문에, 세분화된 데이터는 비세분화된 데이터로 100% 합산되지 *않을* 수 있습니다.
API의 세분화된 값이 Ads Manager UI에 표시되는 값과 일치하지 않는 이유는 무엇인가요?
* API는 쿼리한 특정 엔티티 유형(CAMPAIGN, PROMOTED\_TWEET)에 한정된 세분화 지표를 반환합니다. Ads Manager UI는 엔티티 유형 간 데이터를 집계합니다. 이는 동일한 기반 데이터의 다른 관점이며 예상된 동작입니다.
여러 차원으로 세분화된 데이터를 요청할 수 있나요?
* 다차원 세분화는 지원하지 않습니다.
## 모범 사례
Ads API에서 [분석](/x-ads-api/analytics) 데이터를 수집할 때의 몇 가지 모범 사례입니다.
### 속도 제한 및 재시도
* 속도 제한된 쿼리(`HTTP 429` 상태 코드를 반환하는 쿼리)에서는 `x-rate-limit-reset` 헤더를 확인하고, 표시된 시각 이후에만 재시도해야 합니다.
* HTTP 503 Service Unavailable 상태 코드가 반환된 쿼리에서는 `retry-after` 헤더를 확인하고, 표시된 시간 이후에만 재시도해야 합니다.
* 재시도에 표시된 시간을 준수하지 않는 애플리케이션은 통보 없이 Ads API 접근 권한이 취소되거나 제한될 수 있습니다.
### 분석 지표 요약
* 모든 분석 지표는 24시간 후에 잠기며, `billed_charge_local_micro`를 제외하고는 변경되지 않습니다.
* `billed_charge_local_micro` 지표는 데이터가 반환된 후 최대 3일까지 추정치입니다.
* 24시간 후에 이 지표는 과지출(`end_time` 이후 게재된 광고)에 대한 크레딧과 무효로 판정된 청구 이벤트 때문에 감소할 수 있습니다. 이 지표는 24시간 이후에는 매우 미미하게 변동합니다.
* 자세한 내용은 [분석(Analytics)](/x-ads-api/analytics)을 참고하세요.
### 실시간 비세분화 데이터 가져오기
* 항상 `start_time`과 `end_time`을 모두 제공하세요.
* 7일이 지난 엔티티의 데이터는 가져오지 마세요.
* 지표를 항상 집계하여 `DAY` 및 `TOTAL` 그래뉼래리티로 합산할 수 있으므로, 가능하면 `HOUR` 그래뉼래리티로 데이터를 요청하세요.
* 광고 엔티티 계층 구조 전체(예: 캠페인, 자금 조달 수단(funding instrument), 계정 수준)의 합계를 얻기 위해 이러한 지표를 항상 집계하여 합산할 수 있으므로, 가능하면 `line_items` 및 `promoted_tweets` 수준에서 데이터를 요청하세요.
* 분석 지표의 값을 로컬에 저장하고 보관하세요.
* 30일이 지난 데이터에 대해 반복적으로 쿼리하지 마세요. 이 데이터는 변경되지 않으므로 로컬에 저장해야 합니다.
* 모든 비세분화 데이터는 실시간이며, 이벤트 발생 후 수 초 내에 데이터를 사용할 수 있어야 합니다.
* 전환 지표와 비전환 지표를 별도의 요청으로 묶으세요.
### 세분화된 데이터 가져오기
* 위의 "실시간 비세분화 데이터 가져오기"에 제공된 가이드라인을 참고하세요. 아래에 추가적인 조언이 제공됩니다.
* 대부분의 세분화 데이터 유형은 데이터가 완전해지기까지 최대 1시간이 걸릴 수 있습니다. `INTERESTS`로 세분화된 데이터는 최대 12시간까지 지연될 수 있습니다.
* 이 정보가 도출되는 방식 때문에, 세분화된 데이터는 비세분화된 데이터로 100% 합산되지 않을 수 있습니다.
### 과거 데이터 가져오기
* 데이터 백필 시(예: 신규 광고주 계정 추가)에는 더 작은 `start_time` 및 `end_time` 청크로 여러 번 요청해야 할 수 있습니다.
* 가져오기는 30일 단위의 기간으로 제한하세요.
* 이러한 가져오기에 대한 속도 제한을 모두 소진하지 않도록 요청을 조절하고 시간에 걸쳐 분산하세요.
### 샘플
이러한 모범 사례 중 일부를 보여주는 샘플 스크립트(`fetch_stats`)는 [ads-platform-tools GitHub](https://github.com/xdevplatform/ads-platform-tools) 리포지토리에서 확인할 수 있습니다.
## 목표별 지표
엔티티에 어떤 지표가 적용되는지는 [캠페인 목표](/x-ads-api/campaign-management)에 따라 다릅니다. 이 가이드를 사용해 각 목표 유형에 대해 가져와야 할 관련 지표 그룹과 추가 파생 지표를 계산하는 방법을 확인하세요.
### `ENGAGEMENTS`
**관련 지표 그룹:**`ENGAGEMENT` 및 `BILLING`.
| | |
| :-------------- | :-------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| Engagement Rate | `engagements/impressions` |
| CPE | `billed_charge_local_micro/engagements` |
### `WEBSITE_CLICKS` 및 `WEBSITE_CONVERSIONS`
**관련 지표 그룹:**`ENGAGEMENT`, `BILLING`, `WEB_CONVERSION`.
| | |
| :---------------- | :----------------------------------------------------------------------------------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Click Rate | `clicks/impressions` |
| CPLC | `billed_charge_local_micro/clicks` |
| Total Conversions | `conversion_custom` + `conversion_site_visits` + `conversion_sign_ups` + `conversion_downloads` + `conversion_purchases` |
| Conversion Rate | Total Conversions / `impressions` |
| CPA | `billed_charge_local_micro` / Total Conversions |
### `APP_INSTALLS`
**관련 지표 그룹:**`ENGAGEMENT`, `BILLING`, `MOBILE_CONVERSION`, `LIFE_TIME_VALUE_MOBILE_CONVERSION`. 크리에이티브에 비디오 앱 카드가 사용된 경우 `VIDEO`도 적용됩니다.
| | |
| :------------- | :----------------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| CPM | `billed_charge_local_micro/impressions/1000` |
| App Click Rate | `app_clicks/impressions` |
| CPAC | `billed_charge_local_micro/app_clicks` |
| CPI | `billed_charge_local_micro/mobile_conversion_installs` |
### `FOLLOWERS`
**관련 지표 그룹:**`ENGAGEMENT` 및 `BILLING`.
| | |
| :---------- | :------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Follow Rate | `follows/impressions` |
| CPF | `billed_charge_local_micro/follows` |
### `VIDEO_VIEWS`
**관련 지표 그룹:**`ENGAGEMENT`, `BILLING`, `VIDEO`.
| | |
| :------------ | :-------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Video Rate | `video_total_views/impressions` |
| Cost Per View | `billed_charge_local_micro/video_total_views` |
### `VIDEO_VIEWS_PREROLL`
**관련 지표 그룹:**`ENGAGEMENT`, `BILLING`, `VIDEO`.
| | |
| :------------ | :-------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| CPM | `billed_charge_local_micro/impressions/1000` |
| Video Rate | `video_total_views/impressions` |
| Cost Per View | `billed_charge_local_micro/video_total_views` |
## 지표 및 세분화
이 문서는 각 엔티티 유형별로 [분석(Analytics)](/x-ads-api/analytics)에서 사용 가능한 지표와, 각 지표에 대해 사용 가능한 세분화에 대한 개요입니다.
| | | | | | | |
| :------------------- | :-------------------------- | :-------------------- | :---------------- | :---------------------------------- | :---------------------------------------- | :------------------------------------------------------------------------ |
| | 지표 그룹 | | | | | |
| 엔티티 | [`ENGAGEMENT`](#engagement) | [`BILLING`](#BILLING) | [`VIDEO`](#VIDEO) | [`WEB_CONVERSION`](#WEB_CONVERSION) | [`MOBILE_CONVERSION`](#MOBILE_CONVERSION) | [`LIFE_TIME_VALUE_MOBILE_CONVERSION`](#LIFE_TIME_VALUE_MOBILE_CONVERSION) |
| `ACCOUNT` | ✔\\\* | | | | | |
| `FUNDING_INSTRUMENT` | ✔\\\* | ✔ | | | | |
| `CAMPAIGN` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
| `LINE_ITEM` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
| `PROMOTED_TWEET` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
\*`ENGAGEMENT` 지표 패밀리의 일부 지표는 계정 및 자금 조달 수단 수준에서 사용할 수 없습니다. 자세한 내용은 `ENGAGEMENT` 섹션을 참고하세요.
### 지표 그룹별 사용 가능한 지표
#### `ENGAGEMENT`
| | | | | |
| :---------------------- | :-------------------------------------------- | :----- | :------------ | :----------------------------------- |
| 지표 | 설명 | 세분화 가능 | 데이터 유형 | Account / Funding Instrument에서 사용 가능 |
| `engagements` | 총 인게이지먼트 수 | ✔ | Array of ints | ✔ |
| `impressions` | 총 노출 수 | ✔ | Array of ints | ✔ |
| `retweets` | 총 리포스트 수 | ✔ | Array of ints | ✔ |
| `replies` | 총 답글 수 | ✔ | Array of ints | ✔ |
| `likes` | 총 좋아요 수 | ✔ | Array of ints | ✔ |
| `follows` | 총 팔로우 수 | ✔ | Array of ints | ✔ |
| `card_engagements` | 총 카드 인게이지먼트 수 | ✔ | Array of ints | |
| `clicks` | 좋아요 및 기타 인게이지먼트를 포함한 총 클릭 수 | ✔ | Array of ints | |
| `app_clicks` | 앱 설치 또는 앱 열기 시도 수 | ✔ | Array of ints | |
| url\_clicks | 광고 내 링크 또는 Website Card에 대한 총 클릭 수(획득 클릭 포함). | ✔ | Array of ints | |
| `qualified_impressions` | 총 qualified impressions 수 | ✔ | Array of ints | |
| `carousel_swipes` | Carousel 이미지 또는 동영상에 대한 총 스와이프 수 | ✔ | Array of ints | |
#### `BILLING`
| | | | |
| :-------------------------- | :------------- | :----- | :------------ |
| 지표 | 설명 | 세분화 가능 | 데이터 유형 |
| `billed_engagements` | 청구된 총 인게이지먼트 수 | ✔ | Array of ints |
| `billed_charge_local_micro` | 총 지출(마이크로 단위) | ✔ | Array of ints |
#### `VIDEO`
비디오 지표 정의 변경에 대한 안내:
`VIDEO` 지표 그룹 내 `video_total_views` 지표는 MRC 표준에 따라 50% 이상이 2초 동안 화면에 노출된 모든 조회를 리포트합니다.
기존의 비디오 조회 정의(100% 노출 상태에서 최소 3초)는 `VIDEO` 지표 그룹의 새로운 `video_3s100pct_views` 지표로 계속 제공됩니다. 기존 조회 정의에 기반하여 입찰하고 청구되려면 새롭게 제공되는 `VIEW_3S_100PCT` bid\_unit을 사용하세요.
| | | | |
| :--------------------- | :-------------------------------------------------------- | :----- | :------------ |
| 지표 | 설명 | 세분화 가능 | 데이터 유형 |
| `video_total_views` | 총 동영상 조회 수 | ✔ | Array of ints |
| `video_views_25` | 동영상의 25% 이상이 조회된 총 조회 수. | ✔ | Array of ints |
| `video_views_50` | 동영상의 50% 이상이 조회된 총 조회 수. | ✔ | Array of ints |
| `video_views_75` | 동영상의 75% 이상이 조회된 총 조회 수. | ✔ | Array of ints |
| `video_views_100` | 동영상의 100% 이상이 조회된 총 조회 수. | ✔ | Array of ints |
| `video_cta_clicks` | call to action에 대한 총 클릭 수 | ✔ | Array of ints |
| `video_content_starts` | 동영상 재생 시작 총 수 | ✔ | Array of ints |
| `video_3s100pct_views` | 100% 노출 상태에서 최소 3초 동안 재생된 총 조회 수(레거시 `video_total_views`) | ✔ | Array of ints |
| `video_6s_views` | 동영상의 6초 이상이 조회된 총 조회 수 | ✔ | Array of ints |
| `video_15s_views` | 동영상의 15초 이상 또는 전체 재생 시간의 95% 이상이 조회된 총 조회 수 | ✔ | Array of ints |
#### `WEB_CONVERSION`
| | | | |
| :----------------------- | :------------------------------------- | :----------- | :---------- |
| 지표 | 설명 | 세분화 가능 | 데이터 유형 |
| `conversion_purchases` | PURCHASE 유형의 전환 수와 해당 판매 금액 및 주문 수량 | `PLATFORMS`만 | JSON object |
| `conversion_sign_ups` | SIGN\_UP 유형의 전환 수와 해당 판매 금액 및 주문 수량 | `PLATFORMS`만 | JSON object |
| `conversion_site_visits` | SITE\_VISIT 유형의 전환 수와 해당 판매 금액 및 주문 수량 | `PLATFORMS`만 | JSON object |
| `conversion_downloads` | DOWNLOAD 유형의 전환 수와 해당 판매 금액 및 주문 수량 | `PLATFORMS`만 | JSON object |
| `conversion_custom` | CUSTOM 유형의 전환 수와 해당 판매 금액 및 주문 수량 | `PLATFORMS`만 | JSON object |
#### `MOBILE_CONVERSION`
모바일 전환 통계는 MACT가 활성화된 광고주 계정에서만 사용할 수 있습니다.
| | | | |
| :----------------------------------------- | :------------------------------------------------------------------------------------------------------------ | :----- | :---------- |
| 지표 | 설명 | 세분화 가능 | 데이터 유형 |
| `mobile_conversion_spent_credits` | SPENT\_CREDIT 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_installs` | INSTALL 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_content_views` | CONTENT\_VIEW 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_add_to_wishlists` | ADD\_TO\_WISHLIST 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_checkouts_initiated` | CHECKOUT\_INITIATED 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_reservations` | RESERVATION 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_tutorials_completed` | TUTORIAL\_COMPLETED 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_achievements_unlocked` | ACHIEVEMENT\_UNLOCKED 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_searches` | SEARCH 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_add_to_carts` | ADD\_TO\_CART 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_payment_info_additions` | PAYMENT\_INFO\_ADDITION 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_re_engages` | RE\_ENGAGE 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_shares` | SHARE 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_rates` | RATE 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_logins` | LOGIN 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_updates` | UPDATE 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_levels_achieved` | LEVEL\_ACHIEVED 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_invites` | INVITE 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| `mobile_conversion_key_page_views` | KEY\_PAGE\_VIEW 유형의 모바일 전환을 post\_view, post\_engagement로 분류 | ✔ | JSON object |
| mobile\_conversion\_downloads | DOWNLOAD 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| mobile\_conversion\_purchases | PURCHASE 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| mobile\_conversion\_sign\_ups | SIGN\_UP 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
| mobile\_conversion\_site\_visits | SITE\_VISIT 유형의 모바일 전환을 post\_view, post\_engagement, assisted, order\_quantity, sale\_amount로 분류 | ✔ | JSON object |
#### `LIFE_TIME_VALUE_MOBILE_CONVERSION`
라이프타임 모바일 전환 통계는 MACT가 활성화된 광고주 계정에서만 사용할 수 있습니다.
| | | | |
| :-------------------------------------------------------- | :------------------------------------ | :----- | :---------- |
| 지표 | 설명 | 세분화 가능 | 데이터 유형 |
| `mobile_conversion_lifetime_value_purchases` | PURCHASE 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_sign_ups` | SIGN\_UP 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_updates` | UPDATE 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_tutorials_completed` | TUTORIAL\_COMPLETED 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_reservations` | RESERVATION 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_add_to_carts` | ADD\_TO\_CART 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_add_to_wishlists` | ADD\_TO\_WISHLIST 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_checkouts_initiated` | CHECKOUT\_INITIATED 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_levels_achieved` | LEVEL\_ACHIEVED 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_achievements_unlocked` | ACHIEVEMENT\_UNLOCKED 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_shares` | SHARE 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_invites` | INVITE 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_payment_info_additions` | PAYMENT\_INFO\_ADDITION 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_spent_credits` | SPENT\_CREDIT 유형의 모바일 전환 분류 | | JSON object |
| `mobile_conversion_lifetime_value_rates` | RATE 유형의 모바일 전환 분류 | | JSON object |
### 세분화
세분화 리포팅은 특정 타깃팅 유형의 값별로 분리된 지표를 가져올 수 있게 해줍니다. 세분화는 상당한 추가 복잡성 때문에 [비동기 분석 쿼리](/x-ads-api/analytics#asynchronous-analytics)에서만 사용할 수 있습니다.
2026년 5월 기준으로 다음 세분화 유형만 활성화되어 있습니다. METROS는 Nielsen DMA 코드를 숫자 문자열로 반환합니다(819 = Seattle-Tacoma). METROS와 같은 지리적 세분화 유형은 country 파라미터가 필요합니다(미국의 경우 96683cc9126741d1).
| | |
| :---------- | :---------------- |
| 세분화 유형 | `country` 파라미터 필수 |
| `AGE` | |
| `GENDER` | |
| `METROS` | ✔ |
| `PLATFORMS` | |
## 파생 지표
캠페인 지표는 [캠페인 목표](/x-ads-api/campaign-management)에 따라 달라집니다. 이 가이드를 사용해 적용된 목표에 기반한 파생 지표 계산 방법을 확인하세요.
중괄호 없이 표기된 `metric`은 Ads API [분석](/x-ads-api/analytics#synchronous-analytics) 엔드포인트에서 반환되는 지표입니다. `{curley brackets}`로 둘러싸인 이름은 해당 카테고리의 파생 지표를 나타냅니다.
### ENGAGEMENTS
| | |
| :------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `{Total Engagements}` | `promoted_account_follows + promoted_tweet_search_engagements + promoted_tweet_timeline_engagements + promoted_tweet_profile_engagements` 또는 `promoted_account_follows + promoted_tweet_search_clicks + promoted_tweet_search_replies + promoted_tweet_search_retweets + promoted_tweet_search_follows + promoted_tweet_timeline_clicks + promoted_tweet_timeline_replies + promoted_tweet_timeline_retweets + promoted_tweet_timeline_follows + promoted_tweet_profile_clicks + promoted_tweet_profile_replies + promoted_tweet_profile_retweets + promoted_tweet_profile_follows` |
| `{Engagement Rate}` | `{Total Engagements} / {Impressions}` |
| `billed_charge_local_micro / {Total Engagements}` | |
### WEBSITE\_CLICKS
| | |
| :------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `{Link Clicks}` | `promoted_tweet_search_url_clicks + promoted_tweet_timeline_url_clicks + promoted_tweet_profile_url_clicks` |
| `{Click Rate}` | `{Link Clicks} / {Impressions}` |
| `billed_charge_local_micro / {Link Clicks}` | |
| `conversion_site_visits` | |
| `{Conversion Rate}` | `conversion_site_visits / {Impressions}` |
| `billed_charge_local_micro / conversion_site_visits` | |
### APP\_INSTALLS
| | |
| :------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `{App Clicks}` | `promoted_tweet_app_install_attempts + promoted_tweet_app_open_attempts + promoted_tweet_timeline_url_clicks + promoted_tweet_search_url_clicks` |
| `{App Click Rate}` | `{App Clicks} / {Impressions}` |
| `billed_charge_local_micro / {App Clicks}` | |
| `billed_charge_local_micro / mobile_conversion_installs` | |
### FOLLOWERS
| | |
| :----------------------------------------------------- | :----------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| `promoted_account_impressions` | |
| `billed_charge_local_micro / {Impressions} / 1000` | |
| `promoted_account_follows` | |
| `{Follow Rate}` | `promoted_account_follow_rate` |
| `billed_charge_local_micro / promoted_account_follows` | |
### VIDEO\_VIEWS
| | |
| :------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| | `billed_charge_local_micro / {Impressions} / 1000` |
| `{Video Views}` | `promoted_video_total_views` |
| `{Video Rate}` | `promoted_video_total_views / {Impressions}` |
| `{Cost Per View}` | `billed_charge_local_micro / promoted_video_total_views` |
### QUALIFIED\_IMPRESSIONS
| | |
| :------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| 파생 지표 | 노출 지표 계산식 |
| `promoted_tweet_search_impressions + promoted_tweet_timeline_impressions + promoted_tweet_profile_impressions` | |
| | `billed_charge_local_micro / {Impressions} / 1000` |
| `{Qualified Impressions}` | `promoted_tweet_timeline_qualified_impressions + promoted_tweet_search_qualified_impressions + promoted_tweet_profile_qualified_impressions` |
| `{Qualified Impression Rate}` | `{Qualified Impressions} / {Impressions}` |
| `{Cost Per 1000 Qualified Impressions }` | `billed_charge_local_micro / {Qualified Impressions} / 1000` |
### CUSTOM
`PROMOTED_ACCOUNT`의 `placement_type`에 대해서는 위의 `FOLLOWERS` 목표를 참고하세요. 이 목표를 가진 그 외 모든 게재 위치에 대해서는 해당 파생 지표를 위해 `ENGAGEMENTS`를 참고하세요.
## 가이드
### Active Entities
#### 소개
[Active Entities 엔드포인트](/x-ads-api/analytics#get-stats-accounts-account-id-active-entities)는 [동기](/x-ads-api/analytics#get-stats-accounts-account-id) 및 [비동기](/x-ads-api/analytics#asynchronous-analytics) 분석 엔드포인트와 함께 사용되도록 설계되었습니다. 이 엔드포인트는 어떤 캠페인에 대해 분석을 요청해야 하는지에 대한 정보를 제공하기 때문입니다. 광고 엔티티와 해당 지표가 변경된 시점에 대한 상세 정보를 반환함으로써 이를 수행합니다. 이 엔드포인트를 사용하면 코드와 분석 가져오기 로직이 크게 단순해집니다.
이 가이드는 엔드포인트와 그 데이터 소스에 대한 정보와 맥락을 포함합니다. 또한 분석 엔드포인트와 함께 Active Entities를 사용하는 방법을 보여주는 [사용 가이드라인](#usage)과 [예제 요청](#example)도 제공합니다. [요약 섹션](#summary)은 권장 접근 방식에 대한 고수준 설명을 제공합니다.
#### 데이터
광고 엔티티의 지표가 변경될 때마다 해당 변경에 대한 정보를 기록합니다. 이러한 변경 이벤트는 시간 단위 버킷에 저장되며, 엔티티에 대한 상세 정보와 변경이 적용되는 시각을 포함합니다. 후자가 필요한 이유는 변경 이벤트가 항상 기록 시점과 일치하지는 않기 때문입니다. 청구 조정이 흔한 이유 중 하나이지만, 그 외에도 다른 이유들이 있습니다.
#### 엔드포인트
### 요청
Active Entities 요청은 광고 계정 범위 하에 있으며, 세 가지 필수 쿼리 파라미터(`entity`, `start_time`, `end_time`)를 갖습니다.
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=PROMOTED_TWEET&start_time=2026-03-05T00:00:00Z&end_time=2026-03-06T00:00:00Z"`
다음 `entity` 값이 지원됩니다: `CAMPAIGN`, `FUNDING_INSTRUMENT`, `LINE_ITEM`, `PROMOTED_ACCOUNT`, `PROMOTED_TWEET`. 이는 분석 엔드포인트가 지원하는 엔티티 유형을 반영합니다.
`start_time` 및 `end_time` 값은 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현해야 하며 어떤 시간 단위 버킷을 쿼리할지 지정합니다. 이러한 값은 정시 단위로 표현해야 합니다.
이 엔드포인트는 또한 결과를 필터링하는 데 사용할 수 있는 세 가지 선택적 파라미터(`funding_instrument_ids`, `campaign_ids`, `line_item_ids`)를 지원합니다. 이들은 광고 계층의 모든 수준 및 지정된 모든 `entity` 유형에서 작동합니다.
### 응답
위 요청에 대한 Active Entities 응답은 아래와 같습니다.
```json theme={null}
{
"request": {
"params": {
"account_id": "18ce54d4x5t",
"entity": "PROMOTED_TWEET",
"start_time": "2026-03-05T00:00:00Z",
"end_time": "2026-03-06T00:00:00Z"
}
},
"data": [
{
"entity_id": "2r0wxw",
"activity_start_time": "2026-03-04T20:55:20Z",
"activity_end_time": "2026-03-05T03:43:56Z",
"placements": [
"ALL_ON_TWITTER"
]
},
{
"entity_id": "2r30fn",
"activity_start_time": "2026-03-05T08:11:08Z",
"activity_end_time": "2026-03-05T14:40:59Z",
"placements": [
"ALL_ON_TWITTER",
"PUBLISHER_NETWORK"
]
}
]
}
```
`data` 배열은 후속 분석 요청에 포함시켜야 하는 모든 엔티티에 대한 객체를 포함합니다. 이 집합 외부의 ID에 대해 분석을 요청해서는 안 됩니다.
각 객체는 `entity_id`, `activity_start_time`, `activity_end_time`, `placements`의 네 가지 필드를 포함합니다. activity 시작 및 종료 시각은 해당 엔티티의 변경 이벤트가 적용되는 기간을 나타내며, 따라서 후속 분석 요청에서 지정해야 할 날짜를 결정합니다. `placements` 배열에는 `ALL_ON_TWITTER`, `SPOTLIGHT`, `TREND` 값이 포함될 수 있습니다. 이는 주어진 엔티티 ID에 대해 어떤 게재 위치를 요청해야 하는지를 나타냅니다.
#### 사용법
Active Entities 엔드포인트는 분석 요청을 어떻게 만들지를 좌우해야 합니다. 다음 사용 가이드라인은 분석 동기화를 지원하기 위해 작성되었으며, 파트너가 자신의 데이터 저장소를 X와 동기화 상태로 유지할 수 있게 해줍니다. 다시 말해, 이는 정기적으로 예약된 백그라운드 동기화를 수행하는 방법을 설명합니다.
개발자가 내려야 할 두 가지 결정이 있습니다.
1. 얼마나 자주 active entities 정보를 요청할지, 따라서 얼마나 자주 분석을 가져올지.
2. activity 시작 및 종료 시각을 사용해 분석 요청의 `start_time` 및 `end_time` 값을 어떻게 결정할지.
이는 요약 다음의 두 하위 섹션에서 더 자세히 다룹니다.
### 요약
분석 요청을 어떻게 만들지를 좌우하기 위해 Active Entities 엔드포인트를 다음과 같이 사용하세요. 얼마나 자주 active entities 정보를 요청할지(따라서 얼마나 자주 분석을 가져올지)를 결정한 후에 이를 따르세요.
1. Active Entities 요청을 보냅니다.
2. 게재 위치별로 응답을 분할합니다. `ALL_ON_TWITTER` 그룹, `SPOTLIGHT` 그룹, `TREND` 그룹으로 나눕니다.
3. 각 게재 위치 그룹에 대해 다음을 수행합니다.
1. 엔티티 ID를 추출합니다.
2. 분석 `start_time` 및 `end_time` 값을 결정합니다.
* 최소 `activity_start_time`을 찾습니다. 이 값을 내림합니다.
* 최대 `activity_end_time`을 찾습니다. 이 값을 올림합니다.
3. 분석 요청(들)을 보냅니다.
* 엔티티 ID를 20개씩 배치로 묶습니다.
* \#3b의 `start_time` 및 `end_time` 값을 사용합니다.
* 적절한 `placement` 값을 지정합니다.
4. 데이터 저장소에 씁니다.
Python SDK를 사용하는 예제로 [active\_entities.py](https://github.com/xdevplatform/twitter-python-ads-sdk/blob/master/examples/active_entities.py)를 참고하세요.
### 빈도
첫 번째 질문에 대한 답은 Active Entities 요청에서 사용해야 할 기간을 결정합니다. 예를 들어, 매 시간 active entities 정보를 요청한다면 기간은 1시간이어야 합니다. 하루에 한 번 active entities 정보를 요청한다면 기간은 하루여야 합니다. 다시 말해, 현재 요청의 `start_time`이 이전 요청의 `end_time`과 같도록 기간을 선택해야 합니다.
**참고**: 한 시간 창은 한 번만 요청해야 합니다. 동일한 시간 창을 두 번 이상 요청하면 불필요한 분석 요청이 발생합니다. (예외는 아래.)
*현재* 시간에 대해 한 시간에 여러 번 분석을 요청하려는 파트너의 경우 동일한 패턴이 적용됩니다. 즉, 빈도가 기간을 결정합니다. 아래 표는 이 시나리오에 대한 Active Entities 시작 및 종료 타임스탬프 예시를 보여줍니다.
| | | |
| :-------- | :--------------------- | :------------------- |
| **요청 시각** | **`start_time` 타임스탬프** | **`end_time` 타임스탬프** |
| 00:15:00 | 00:00:00 | 00:15:00 |
| 00:30:00 | 00:15:00 | 00:30:00 |
| 00:45:00 | 00:30:00 | 00:45:00 |
| 01:00:00 | 00:45:00 | 01:00:00 |
변경 이벤트가 저장되는 방식 때문에, 위의 네 Active Entities 요청은 모두 동일한 시간 단위 버킷을 쿼리하며, 이는 이 사용 사례에 필요합니다. 다만 현재 시간이 지난 후에는 이 시간 단위 버킷을 더 이상 쿼리해서는 안 됩니다.
### Activity 시각
activity 시작 및 종료 시각을 다룰 때 다음 접근 방식을 권장합니다. Active Entities 응답의 모든 객체에서 최소 `activity_start_time`과 최대 `activity_end_time`을 찾습니다. 이 값들을 수정하여 최소 activity 시작 시각은 내림하고 최대 activity 종료 시각은 올림합니다. 구체적으로, 다음 표에 나타난 것처럼 둘 다 타임스탬프를 0으로 설정하고 종료 시각에 하루를 더합니다. 이것이 후속 분석 요청에 지정되어야 할 시작 및 종료 시각입니다.
| | |
| :----------------------------------------------------- | :----------------------------------------------------- |
| **최소, 최대 activity 시각** | **파생된 시각** |
| 2026-03-04T20:55:20Z
2026-03-05T14:40:59Z | 2026-03-04T00:00:00Z
2026-03-06T00:00:00Z |
**참고**: 시·분·초를 0으로 설정한 타임스탬프를 포함하는 것이 중요합니다. 그렇지 않고 날짜만 전달되면, 광고 계정의 시간대에서 자정에 시작하고 종료하는 분석을 요청하는 것으로 간주되며, 이는 원하는 결과가 아닐 수 있습니다. 예를 들어, 최소 activity 시작 시각이 2026-02-28T01:30:07Z이고 -08:00:00 오프셋을 가진 광고 계정에 대해 타임스탬프를 생략하면 분석 요청은 01:30과 08:00 사이에 발생한 변경 사항을 누락하게 됩니다.
또는 전체 일자로 확장하지 않고 반환된 activity 기간에 대해서만 분석을 요청하고 싶다면 그렇게 할 수도 있습니다. 이 접근 방식을 사용하면 파생된 시작 및 종료 시각은 각각 2026-03-04T20:00:00Z와 2026-03-05T15:00:00Z가 됩니다. (이러한 범위는 분석 요청에서 `DAY` 그래뉼래리티를 지정한 경우에는 허용되지 않습니다.)
#### 예제
이 섹션은 동기 분석 엔드포인트와 함께 Active Entities를 사용하는 방법을 보여줍니다. (응답은 가독성을 위해 약간 수정되었습니다.) 이 예제에서는 Active Entities 엔드포인트가 매 시간 정각에 호출되며, 각 요청은 이전 시간을 살펴봅니다. 응답이 동기 분석 엔드포인트를 어떻게 사용할지를 결정합니다.
첫 번째 Active Entities 요청은 03:00:00에 이루어집니다. 응답은 line item dvcz7의 지표가 변경되었으며, 해당 변경 이벤트가 02:02:55와 02:28:12 사이의 창에 적용됨을 나타냅니다.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T02:00:00Z&end_time=2026-02-11T03:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": [
{
"entity_id": "dvcz7",
"activity_start_time": "2026-02-11T02:02:55Z",
"activity_end_time": "2026-02-11T02:58:12Z",
"placements": [
"ALL_ON_TWITTER"
]
}
]
}
```
위에서 설명한 접근 방식을 사용하여 이러한 activity 시작 및 종료 시각에 기반해 분석 `start_time`과 `end_time` 값은 각각 2026-02-11T00:00:00Z와 2026-02-12T00:00:00Z로 설정됩니다. active entities 정보에서 예상한 대로 아래의 각 지표 배열에서 세 번째 요소가 0이 아님을 확인할 수 있습니다.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=dvcz7&start_time=2026-02-11T00:00:00Z&end_time=2026-02-12T00:00:00Z&granularity=HOUR&metric_groups=ENGAGEMENT,VIDEO&placement=ALL_ON_TWITTER"`
```
```json theme={null}
{
"data_type": "stats",
"time_series_length": 24,
"data": [
{
"id": "dvcz7",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
0,0,2792,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"engagements": [
0,0,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"video_total_views": [
0,0,1326,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
}
}
]
}
],
"request": {}
}
```
다음 Active Entities 요청은 04:00:00에 이루어지며 이전 시간만 봅니다. 위에서 언급했듯이, 한 시간 창은 한 번만 요청해야 합니다. 응답을 보면 이 line item의 변경 이벤트가 02:00:00과 03:00:00 \_둘 다\_에 적용됨을 알 수 있습니다. 후속 분석 요청에서 두 시간 모두에 대한 변경 사항을 볼 것으로 예상됩니다.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T03:00:00Z&end_time=2026-02-11T04:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": [
{
"entity_id": "dvcz7",
"activity_start_time": "2026-02-11T02:07:17Z",
"activity_end_time": "2026-02-11T03:49:22Z",
"placements": [
"ALL_ON_TWITTER"
]
}
]
}
```
03:00:00의 0이 아닌 지표를 보는 것 외에도, impressions, spend, MRC 비디오 조회가 이전 값에서 업데이트된 것을 볼 수 있습니다. 예를 들어, 02:00:00 시간의 impressions는 2,792에서 2,995로 증가했습니다. 이는 03:00:00 시간 동안 기록된 변경 이벤트가 02:00:00 시간에 어떻게 적용되는지를 보여줍니다.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=dvcz7&start_time=2026-02-11T00:00:00Z&end_time=2026-02-12T00:00:00Z&granularity=HOUR&metric_groups=ENGAGEMENT,VIDEO&placement=ALL_ON_TWITTER"`
```
```json theme={null}
{
"data_type": "stats",
"time_series_length": 24,
"data": [
{
"id": "dvcz7",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
0,0,2995,734,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"engagements": [
0,0,65,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"video_total_views": [
0,0,1449,342,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
}
}
]
}
],
"request": {}
}
```
05:00:00의 Active Entities 요청은 다시 이전 시간만 살펴보는데, 변경 이벤트가 03:00:00 시간에만 적용됨을 보여줍니다. 후속 요청에서 분석 지표의 변경 사항이 이를 반영합니다.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T04:00:00Z&end_time=2026-02-11T05:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": [
{
"entity_id": "dvcz7",
"activity_start_time": "2026-02-11T03:42:39Z",
"activity_end_time": "2026-02-11T03:48:48Z",
"placements": [
"ALL_ON_TWITTER"
]
}
]
}
```
분석 응답은 03:00:00 시간의 지표만 변경되었음을 보여줍니다. 02:00:00 시간의 값은 이전 분석 요청과 동일합니다.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=dvcz7&start_time=2026-02-11T00:00:00Z&end_time=2026-02-12T00:00:00Z&granularity=HOUR&metric_groups=ENGAGEMENT,VIDEO&placement=ALL_ON_TWITTER"`
```
```json theme={null}
{
"data_type": "stats",
"time_series_length": 24,
"data": [
{
"id": "dvcz7",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
0,0,2995,753,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"engagements": [
0,0,65,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
],
"video_total_views": [
0,0,1449,351,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
}
}
]
}
],
"request": {}
}
```
마지막으로, 06:00:00에는 추가 변경 이벤트가 없음을 확인합니다. **참고**: 다만 이것이 향후 이 line item에 대한 지표가 변경될 수 없음을 *의미하지는* 않습니다.
```text theme={null}
`twurl -H ads-api.x.com "/12/stats/accounts/18ce54d4x5t/active_entities?entity=LINE_ITEM&start_time=2026-02-11T05:00:00Z&end_time=2026-02-11T06:00:00Z"`
```
```json theme={null}
{
"request": {},
"data": []
}
```
### 비동기 가이드
## API 레퍼런스
### 비동기 분석
#### 소개
비동기 분석 엔드포인트는 파트너와 광고주가 서버가 비동기적으로 처리하는 생성 요청을 제출하여 지표를 요청할 수 있게 해줍니다. (이를 비동기 분석 "작업(job)"이라고 부릅니다.) 이 접근 방식을 사용하면 요청이 완료될 때까지 클라이언트의 연결을 유지하지 않아도 됩니다.
이러한 엔드포인트는 동기 엔드포인트와 마찬가지로 파트너와 광고주가 캠페인 성과에 대한 상세 통계를 요청할 수 있게 해줍니다. accounts, funding instruments, campaigns, line items, promoted posts, media creatives에 대한 데이터를 요청하는 것을 지원합니다. 동기 엔드포인트와의 차이점은 비동기 분석 엔드포인트가 최대 90일까지의 더 긴 기간과 세분화를 지원한다는 점입니다. 둘 사이의 차이에 대한 추가 세부 사항은 [분석 개요](/x-ads-api/analytics) 페이지에서 확인할 수 있습니다.
동기 엔드포인트와 달리 속도 제한은 주어진 계정에 대한 동시 작업 수에 기반합니다. 다시 말해, 특정 시점에 처리 중 상태에 있을 수 있는 작업 수에 기반합니다. 이는 광고 계정 수준에서 계산됩니다.
#### 사용법
비동기 분석 엔드포인트를 사용해 캠페인 지표를 가져오는 것은 여러 단계로 진행되는 과정입니다. 작업을 생성하고, 작업이 처리 완료되었는지 확인한 다음, 마지막으로 데이터를 다운로드하는 과정이 포함됩니다. 데이터 파일은 압축 해제해야 합니다. 네 가지 구체적인 단계는 아래에 요약되어 있습니다.
1. [POST stats/jobs/accounts/:account\_id](/x-ads-api/analytics#asynchronous-analytics) 엔드포인트를 사용해 작업을 생성합니다.
2. [GET stats/jobs/accounts/:account\_id](/x-ads-api/analytics#asynchronous-analytics) 엔드포인트에 정기적인 간격으로 요청을 보내 작업이 처리 완료되었는지 확인합니다.
3. 작업이 처리 완료되면 데이터 파일을 다운로드합니다.
4. 데이터 파일의 압축을 풉니다.
데이터 파일에서 반환된 응답 객체는 동기 분석 엔드포인트의 응답과 동일한 JSON 스키마를 갖습니다.
세분화된 캠페인 지표는 비동기 분석 엔드포인트를 통해서만 사용할 수 있습니다. 캠페인 지표는 위치, 성별, 관심사, 키워드 등으로 분류될 수 있습니다. 전체 옵션 목록은 [지표 및 세분화](/x-ads-api/analytics#metrics-and-segmentation) 페이지를 참고하세요. 세분화된 지표를 요청하려면 작업을 생성할 때 `segmentation_type` 요청 파라미터를 사용하세요.
#### 예제
이 섹션은 비동기 분석 엔드포인트를 사용하는 방법을 보여줍니다.
먼저 [POST stats/jobs/accounts/:account\_id](/x-ads-api/analytics#asynchronous-analytics) 엔드포인트를 사용해 작업을 생성합니다. 아래 예제는 특정 line item에 대해 한 주 동안의 인게이지먼트 지표—노출 수, 좋아요, 클릭 수 등—를 요청합니다. (요청한 기간은 3월 20일을 포함하지 않으며, 타임스탬프가 자정으로 설정되어 있으므로 그 전까지만 포함됩니다.)
```text theme={null}
$ twurl -X POST -H ads-api.x.com "/12/stats/jobs/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=el32n&start_time=2026-03-12T00:00:00Z&end_time=2026-03-20T00:00:00Z&granularity=TOTAL&placement=ALL_ON_TWITTER&metric_groups=ENGAGEMENT"
```
```json theme={null}
{
"request": {
"params": {
"start_time": "2026-03-12T00:00:00Z",
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"placement": "ALL_ON_TWITTER",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"metric_groups": [
"ENGAGEMENT"
]
}
},
"data": {
"start_time": "2026-03-12T00:00:00Z",
"segmentation_type": null,
"url": null,
"id_str": "1120829647711653888",
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"id": 1120829647711653888,
"expires_at": null,
"account_id": "18ce54d4x5t",
"status": "PROCESSING",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"created_at": "2026-04-01T23:19:46Z",
"platform": null,
"updated_at": "2026-04-01T23:19:46Z",
"metric_groups": [
"ENGAGEMENT"
]
}
}
```
이 응답은 line item 지표를 반환하지 않습니다. 방금 생성한 작업에 대한 정보만 제공합니다. 작업의 상태를 확인하려면 작업 ID가 필요합니다. 이는 응답 속성의 `id`와 `id_str` 모두에 표시됩니다.
다음으로, 이전 응답의 `id_str`을 사용해 생성한 작업이 처리 완료되었는지 확인하고 싶을 것입니다. 이는 응답에 `"status": "SUCCESS"`로 표시됩니다. 이는 데이터를 다운로드할 준비가 되었음을 의미합니다. `url` 필드에는 다운로드 링크가 포함되어 있습니다.
```text theme={null}
$ twurl -H ads-api.x.com "/12/stats/jobs/accounts/18ce54d4x5t?job_ids=1120829647711653888"
```
```json theme={null}
{
"request": {
"params": {
"job_ids": [
1120829647711653888
]
}
},
"next_cursor": "1120828505715920896",
"data": [
{
"start_time": "2026-03-12T00:00:00Z",
"segmentation_type": null,
"url": "https://ton.twimg.com/advertiser-api-async-analytics/stats_job_1120829647711653888.json.gz",
"id_str": "1120829647711653888",
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"id": 1120829647711653888,
"expires_at": "2026-04-03T23:19:48Z",
"account_id": "18ce54d4x5t",
"status": "SUCCESS",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"created_at": "2026-04-01T23:19:46Z",
"platform": null,
"updated_at": "2026-04-01T23:19:48Z",
"metric_groups": [
"ENGAGEMENT"
]
}
]
}
```
위 예제에서는 단일 작업 ID를 전달하지만, 실제로는 최대 200개의 작업 ID를 지정하여 `job_ids` 파라미터로 여러 작업의 상태를 한 번에 확인하고 싶을 것입니다.
다음으로, 표시된 `url` 값을 사용해 데이터 파일을 다운로드합니다.
```text theme={null}
$ wget https://ton.twimg.com/advertiser-api-async-analytics/stats_job_1120829647711653888.json.gz
```
마지막으로, 데이터 파일의 압축을 풉니다.
```text theme={null}
`$ gunzip stats_job_1120829647711653888.json.gz`
```
파일의 내용은 아래와 같습니다.
```json theme={null}
{
"data_type": "stats",
"time_series_length": 1,
"data": [
{
"id": "el32n",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
3482
],
"tweets_send": null,
"qualified_impressions": null,
"follows": null,
"app_clicks": null,
"retweets": [
102
],
"unfollows": null,
"likes": [
15
],
"engagements": [
171
],
"clicks": [
30
],
"card_engagements": null,
"poll_card_vote": null,
"replies": null,
"carousel_swipes": null
}
}
]
}
],
"request": {
"params": {
"start_time": "2026-03-12T00:00:00Z",
"segmentation_type": null,
"entity_ids": [
"el32n"
],
"end_time": "2026-03-20T00:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"platform": null,
"metric_groups": [
"ENGAGEMENT"
]
}
}
}
```
### Reach 및 Average Frequency
#### GET stats/accounts/:account\_id/reach/campaigns
지정된 캠페인의 reach 및 average frequency 분석을 가져옵니다.
### 리소스 URL
`https://ads-api.x.com/stats/accounts/:account_id/reach/campaigns`
### 파라미터
| 이름 | 설명 |
| :------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *필수* | 사용 중인 계정의 식별자입니다. 리소스 경로 내에 표시되며 일반적으로 [GET accounts](/x-ads-api/campaign-management/reference#accounts)를 제외한 모든 Advertiser API 요청에 필수 파라미터입니다. 지정된 계정은 인증된 사용자와 연결되어 있어야 합니다.
Type: string
Example: `18ce54d4x5t` |
| campaign\_ids *필수* | 쉼표로 구분된 식별자 목록을 지정하여 원하는 캠페인으로만 응답 범위를 좁힙니다. 최대 20개의 ID를 제공할 수 있습니다.
**참고**: 최대 20개의 campaign ID를 제공할 수 있습니다.
Type: string
Example: `8fgzf` |
| end\_time *필수* | 가져올 데이터의 범위를 지정된 종료 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
**참고**: 정시 단위(0분 0초)로 표현해야 합니다.
Type: string
Example: `2026-05-26T07:00:00Z` |
| start\_time *필수* | 가져올 데이터의 범위를 지정된 시작 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
**참고**: 정시 단위(0분 0초)로 표현해야 합니다.
Type: string
Example: `2026-05-19T07:00:00Z` |
### 요청 예시
`GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/reach/campaigns?campaign_ids=8fgzf&start_time=2026-05-19&end_time=2026-05-26`
### 응답 예시
```json theme={null}
{
"request": {
"params": {
"campaign_ids": [
"8fgzf"
],
"start_time": "2026-05-19T00:00:00Z",
"end_time": "2026-05-26T00:00:00Z",
"account_id": "18ce54d4x5t"
}
},
"data_type": "reach",
"data": [
{
"id": "8fgzf",
"total_audience_reach": 1217,
"average_frequency": 1.01
}
]
}
```
#### GET stats/accounts/:account\_id/reach/funding\_instruments
지정된 funding instrument의 reach 및 average frequency 분석을 가져옵니다.
### 리소스 URL
`https://ads-api.x.com/stats/accounts/:account_id/reach/funding_instruments`
### 파라미터
| 이름 | 설명 |
| :----------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *필수* | 사용 중인 계정의 식별자입니다. 리소스 경로 내에 표시되며 일반적으로 [GET accounts](/x-ads-api/campaign-management/reference#accounts)를 제외한 모든 Advertiser API 요청에 필수 파라미터입니다. 지정된 계정은 인증된 사용자와 연결되어 있어야 합니다.
Type: string
Example: `18ce54d4x5t` |
| funding\_instrument\_ids *필수* | 쉼표로 구분된 식별자 목록을 지정하여 원하는 funding instrument로만 응답 범위를 좁힙니다. 최대 20개의 ID를 제공할 수 있습니다.
**참고**: 최대 20개의 funding instrument ID를 제공할 수 있습니다.
Type: string
Example: `lygyi` |
| end\_time *필수* | 가져올 데이터의 범위를 지정된 종료 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
**참고**: 정시 단위(0분 0초)로 표현해야 합니다.
Type: string
Example: `2026-05-26T07:00:00Z` |
| start\_time *필수* | 가져올 데이터의 범위를 지정된 시작 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
**참고**: 정시 단위(0분 0초)로 표현해야 합니다.
Type: string
Example: `2026-05-19T07:00:00Z` |
### 요청 예시
```text theme={null}
GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/reach/funding_instruments?funding_instrument_ids=lygyi&start_time=2026-05-19&end_time=2026-05-26
```
### 응답 예시
```json theme={null}
{
"request": {
"params": {
"funding_instrument_ids": [
"lygyi"
],
"start_time": "2026-05-19T00:00:00Z",
"end_time": "2026-05-26T00:00:00Z",
"account_id": "18ce54d4x5t"
}
},
"data_type": "reach",
"data": [
{
"id": "lygyi",
"total_audience_reach": 1217,
"average_frequency": 1.01
}
]
}
```
### 동기 분석
#### GET stats/accounts/:account\_id
현재 계정에 대한 동기 분석을 가져옵니다. 최대 기간(`end_time` - `start_time`)은 7일까지 허용됩니다.
### 리소스 URL
`https://ads-api.x.com/12/stats/accounts/:account_id`
### 파라미터
| 이름 | 설명 |
| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *필수* | 사용 중인 계정의 식별자입니다. 리소스 경로 내에 표시되며 일반적으로 [GET accounts](/x-ads-api/campaign-management/reference#accounts)를 제외한 모든 Advertiser API 요청에 필수 파라미터입니다. 지정된 계정은 인증된 사용자와 연결되어 있어야 합니다.
Type: string
Example: `18ce54d4x5t` |
| end\_time *필수* | 가져올 데이터의 범위를 지정된 종료 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
Possible values: `ACCOUNT`, `CAMPAIGN`, `FUNDING_INSTRUMENT`, `LINE_ITEM`, `PROMOTED_ACCOUNT`, `PROMOTED_TWEET` |
| entity\_ids *필수* | 데이터를 가져올 특정 엔티티입니다. 쉼표로 구분된 엔티티 ID 목록을 지정하세요.
Possible values: `DAY`, `HOUR`, `TOTAL` |
| metric\_groups *필수* | 반환되어야 하는 특정 지표입니다. 쉼표로 구분된 지표 그룹 목록을 지정하세요. 자세한 내용은 [Metrics and Segmentation](/x-ads-api/analytics#metrics-and-segmentation)을 참고하세요.
**참고**: `MOBILE_CONVERSION` 데이터는 별도로 요청해야 합니다.
Type: enum
Possible values: `BILLING`, `ENGAGEMENT`, `LIFE_TIME_VALUE_MOBILE_CONVERSION`, `MOBILE_CONVERSION`, `VIDEO`, `WEB_CONVERSION` |
| placement *필수* | 가져올 데이터의 범위를 특정 게재 위치로 좁힙니다.
**참고**: 요청당 단일 값만 허용됩니다. X와 X Audience Platform 양쪽에 게재 위치를 가진 엔티티의 경우, 게재 위치 값마다 별도의 요청이 필요합니다.
Type: enum
Possible values: `ALL_ON_TWITTER`, `SPOTLIGHT`, `TREND` |
| start\_time *필수* | 가져올 데이터의 범위를 지정된 시작 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
**참고**: 정시 단위(0분 0초)로 표현해야 합니다.
Type: string
Example: `2026-05-19T07:00:00Z` |
### 요청 예시
```text theme={null}
GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=8u94t&start_time=2026-05-19&end_time=2026-05-26&granularity=TOTAL&placement=ALL_ON_TWITTER&metric_groups=ENGAGEMENT
```
### 응답 예시
```json theme={null}
{
"data_type": "stats",
"time_series_length": 1,
"data": [
{
"id": "8u94t",
"id_data": [
{
"segment": null,
"metrics": {
"impressions": [
1233
],
"tweets_send": null,
"qualified_impressions": null,
"follows": null,
"app_clicks": null,
"retweets": null,
"likes": [
1
],
"engagements": [
58
],
"clicks": [
58
],
"card_engagements": null,
"poll_card_vote": null,
"replies": null,
"carousel_swipes": null
}
}
]
}
],
"request": {
"params": {
"start_time": "2026-05-19T07:00:00Z",
"segmentation_type": null,
"entity_ids": [
"8u94t"
],
"end_time": "2026-05-26T07:00:00Z",
"country": null,
"placement": "ALL_ON_TWITTER",
"granularity": "TOTAL",
"entity": "LINE_ITEM",
"platform": null,
"metric_groups": [
"ENGAGEMENT"
]
}
}
}
```
### Active Entities
#### GET stats/accounts/:account\_id/active\_entities
지정된 기간에 분석 지표가 변경된 엔티티에 대한 상세 정보를 가져옵니다.
이 엔드포인트는 분석 엔드포인트와 함께 사용해야 합니다. 이 엔드포인트의 결과는 어떤 광고 엔티티에 대해 분석을 요청해야 하는지를 나타냅니다. 사용 가이드라인은 [Active Entities 가이드](/x-ads-api/analytics#active-entities)를 참고하세요.
변경 이벤트는 시간 단위 버킷에서 사용할 수 있습니다.
* `start_time` 및 `end_time` 값은 쿼리할 시간 단위 버킷을 지정합니다.
* 반환된 `data` 배열에는 후속 분석 요청에 포함시켜야 하는 모든 엔티티에 대한 객체가 포함됩니다.
* **중요**: 후속 분석 요청에서 지정해야 할 날짜는 `activity_start_time` 및 `activity_end_time` 값을 기반으로 결정되어야 합니다.
* 이 값들은 저장된 변경 이벤트가 *적용되는* 기간을 나타냅니다. 엔티티별로 반환됩니다.
**참고**: 최대 기간(`end_time` - `start_time`)은 90일까지 허용됩니다.
### 리소스 URL
`https://ads-api.x.com/12/stats/accounts/:account_id/active_entities`
### 파라미터
| 이름 | 설명 |
| :----------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| account\_id *필수* | 사용 중인 계정의 식별자입니다. 리소스 경로 내에 표시되며 일반적으로 [GET accounts](/x-ads-api/campaign-management/reference#accounts)를 제외한 모든 Advertiser API 요청에 필수 파라미터입니다. 지정된 계정은 인증된 사용자와 연결되어 있어야 합니다.
Type: string
Example: `18ce54d4x5t` |
| end\_time *필수* | 가져올 데이터의 범위를 지정된 종료 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
Possible values: `CAMPAIGN`, `FUNDING_INSTRUMENT`, `LINE_ITEM`, `PROMOTED_ACCOUNT`, `PROMOTED_TWEET` |
| start\_time *필수* | 가져올 데이터의 범위를 지정된 시작 시각으로 좁히며, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)로 표현합니다.
**참고**: 정시 단위(0분 0초)로 표현해야 합니다.
Type: string
Example: `2026-05-19T07:00:00Z` |
| campaign\_ids *선택* | 쉼표로 구분된 식별자 목록을 지정하여 원하는 캠페인과 관련된 엔티티로만 응답 범위를 좁힙니다. 최대 200개의 ID를 제공할 수 있습니다.
**참고**: `funding_instrument_ids` 및 `line_item_ids`와 함께 사용할 수 없습니다.
Type: string
Example: `8wku2` |
| funding\_instrument\_ids *선택* | 쉼표로 구분된 식별자 목록을 지정하여 원하는 funding instrument와 관련된 엔티티로만 응답 범위를 좁힙니다. 최대 200개의 ID를 제공할 수 있습니다.
**참고**: `campaign_ids` 및 `line_item_ids`와 함께 사용할 수 없습니다.
Type: string
Example: `lygyi` |
| line\_item\_ids *선택* | 쉼표로 구분된 식별자 목록을 지정하여 원하는 line item과 관련된 엔티티로만 응답 범위를 좁힙니다. 최대 200개의 ID를 제공할 수 있습니다.
**참고**: `campaign_ids` 및 `line_item_ids`와 함께 사용할 수 없습니다.
Type: string
Example: `8v7jo` |
### 요청 예시
`GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/active_entities?entity=PROMOTED_TWEET&start_time=2026-02-28&end_time=2026-03-01`
### 응답 예시
```json theme={null}
{
"request": {
"params": {
"account_id": "18ce54d4x5t",
"entity": "PROMOTED_TWEET",
"start_time": "2026-02-28T08:00:00Z",
"end_time": "2026-03-01T08:00:00Z"
}
},
"data": [
{
"entity_id": "2mvb28",
"activity_start_time": "2026-02-28T01:30:07Z",
"activity_end_time": "2026-03-01T07:42:55Z",
"placements": [
"ALL_ON_TWITTER"
]
},
{
"entity_id": "2mvb29",
"activity_start_time": "2026-02-27T11:30:07Z",
"activity_end_time": "2026-03-01T07:42:50Z",
"placements": [
"ALL_ON_TWITTER",
"PUBLISHER_NETWORK"
]
},
{
"entity_id": "2mvfan",
"activity_start_time": "2026-02-27T09:00:05Z",
"activity_end_time": "2026-03-01T06:06:36Z",
"placements": [
"PUBLISHER_NETWORK"
]
},
{
"entity_id": "2n17dx",
"activity_start_time": "2026-02-28T02:02:26Z",
"activity_end_time": "2026-03-01T07:52:44Z",
"placements": [
"ALL_ON_TWITTER",
"PUBLISHER_NETWORK"
]
}
]
}
```
# 단계별 가이드
Source: https://docs.x.com/ko/x-ads-api/getting-started/step-by-step-guide
X Ads API를 처음 사용하는 개발자를 위한 단계별 시작 가이드입니다. 광고 계정 설정과 개발자 앱 생성, Ads API 액세스 신청, OAuth 1.0a 인증 토큰 발급, 첫 API 요청 인증과 호출 방법을 차근차근 알려드립니다.
## Ads API 액세스 권한을 얻는 방법
1. [개발자 계정](https://developer.x.com/en/apply-for-access)에 가입하세요.
2. [개발자 App](https://developer.x.com/app)을 생성하고 토큰을 안전하게 보관하세요.
3. [ads.x.com/help](https://ads.x.com/help)을 방문하여 각 개발자 App에 대한 Ads API 액세스 요청을 제출하세요.
**참고:** 이미 X Developer Platform에서 개발 중이며 개발자 계정이 있는 경우 3단계로 건너뛰세요.
### 1단계: 개발자 계정에 가입하기
X의 어떤 API 제품에든 요청을 보내려면 먼저 개발자 계정에 가입해야 합니다. Developer Console 내에서 App과 개발자 App을 생성하세요. 이를 통해 API에 대한 모든 요청을 인증하는 데 사용할 자격 증명 세트를 얻을 수 있습니다.
### 2단계: App의 키와 토큰을 저장하고 안전하게 관리하기
개발자 App 내에서 API 키 세트(Consumer Key라고도 함)를 받게 됩니다. 또한 개인 X 계정을 대신하여 요청을 보내는 데 사용할 수 있는 Access Token 세트와 OAuth 2.0 Bearer Token이 필요한 엔드포인트를 인증하는 데 사용할 수 있는 Bearer Token을 생성할 수 있는 기회도 있습니다. 이러한 키와 토큰은 재생성하지 않는 한 만료되지 않으므로 환경 변수를 생성하거나 안전한 비밀번호 관리자를 사용하는 것이 좋습니다.
또한 App 세부 정보의 URL에서 찾을 수 있는 App ID도 기록해 두세요. 이렇게 하면 다음 단계에서 Ads API 액세스를 요청하기가 더 쉬워집니다.
**참고:** 키와 토큰은 Developer Console에서 한 번만 표시되므로 생성 즉시 비밀번호 관리 시스템에 저장하는 것이 중요합니다.
키와 토큰을 분실하거나 잊어버린 경우 재생성해야 하며, 이 경우 새 키와 토큰이 생성되고 이전 것은 무효화됩니다. 이는 이전 자격 증명으로 설정한 통합을 모두 업데이트해야 함을 의미합니다.
자세한 내용은 [인증 모범 사례](/fundamentals/authentication/guides/authentication-best-practices)를 참고하세요.
### 3단계: Ads API 액세스 신청하기
이 시점에서는 X API에 대한 기본 액세스 권한은 있지만 X Ads API 전용 기능에는 액세스할 수 없습니다. 다음으로 Ads API 액세스를 요청하고 승인을 받아야 합니다. [ads.x.com/help](https://ads.x.com/help)을 방문하여 각 개발자 App에 대한 Ads API 액세스 요청을 제출하세요.
### 액세스 등급
신청 과정의 일부로 필요한 액세스 수준을 지정해야 합니다. [App 수준 및 광고 계정 수준 권한](/x-ads-api/fundamentals/accessing-ads-accounts#levels-of-access)에 대해 자세히 알아보세요.
#### Conversion Only
Mobile 및 Web Conversion 엔드포인트에 대한 읽기/쓰기 액세스.
#### Standard Access
Analytics, Campaign Management, Creatives, Custom Audiences 및 Conversion 엔드포인트에 대한 읽기/쓰기 액세스.
**참고:** App이 Ads API 액세스 승인을 받은 후에는 올바르게 [인증된 Ads API 요청](/x-ads-api/fundamentals/making-authenticated-requests)을 보내기 위해 [사용자 액세스 토큰을 재생성](/fundamentals/authentication/oauth-1-0a/obtaining-user-access-tokens)해야 합니다.**참고:** 2023년 7월 이전에 액세스를 요청한 Ads API 개발자는 다른 액세스 수준과 권한을 가질 수 있으며, OAuth 토큰이 5개로 제한될 수 있습니다. 기존 애플리케이션에서 추가 엔드포인트에 액세스하거나 토큰 제한을 해제하려면 [액세스 확대](/x-ads-api/getting-started/increasing-access) 가이드를 참고하세요.
## 첫 요청 보내기
Ads API에 대한 액세스를 테스트하려면 [GET accounts](/x-ads-api/campaign-management/reference#get-accounts) 엔드포인트에 요청을 보냅니다. 이 엔드포인트는 현재 인증된 사용자가 액세스할 수 있는 광고 계정을 반환합니다. 이 요청에서 얻은 광고 계정 ID를 후속 API 요청에서 사용하여 특정 광고 계정에 대한 데이터를 읽고 쓸 수 있습니다. 명령줄에서 [Twurl](https://github.com/twitter/twurl)을 사용하면 요청은 다음과 같습니다.
**요청 예시**
```bash theme={null}
twurl -H ads-api.x.com "/11/accounts"
```
**응답 예시**
```json theme={null}
{
"request": {
"params": {}
},
"data": [
{
"name": "Furni",
"business_name": null,
"timezone": "America/Los_Angeles",
"timezone_switch_at": "2016-04-06T07:00:00Z",
"id": "18ce54ayf0z",
"created_at": "2016-04-07T14:40:15Z",
"salt": "b88939e5cabbca720159cb3659d73c06",
"updated_at": "2017-02-08T08:49:53Z",
"business_id": null,
"approval_status": "ACCEPTED",
"deleted": false
}
]
}
```
## 다음 단계 . . .
* [Ads API 문서](/x-ads-api/introduction)를 통해 [버전 관리](/x-ads-api/fundamentals/versioning) 및 [계층 구조](/x-ads-api/fundamentals/hierarchy-and-terminology)와 같은 기본 사항을 확인하세요.
* Ads API 통합을 지원하는 다양한 [Ads API 도구 및 라이브러리](/x-ads-api/tools-and-libraries)를 확인하세요.
* [Ads API 액세스 확대](/x-ads-api/getting-started/increasing-access) 단계를 이해하세요.
* 이용 가능한 [지원 리소스](/support)를 숙지하세요.
* API 변경, 서비스 문제, X 프로모션 제품의 개선 사항에 대한 실시간 업데이트는 [@API](https://x.com/API)를 팔로우하세요.
# 소개
Source: https://docs.x.com/ko/x-api/activity/introduction
X Activity API 개요입니다. post.create, post.delete, 프로필 업데이트, 팔로우, 좋아요 등 X 플랫폼에서 발생하는 사용자 활동 이벤트를 실시간으로 스트리밍하는 엔드포인트와 웹훅 구독 관리 방법을 소개합니다.
X Activity API(XAA) 엔드포인트 그룹을 사용하면 개발자가 X 플랫폼에서 발생하는 활동 이벤트에 접근할 수 있습니다.
개발자는 `profile.update.bio`, `post.create`, `post.delete` 등 관심 있는 이벤트를 구독하고, 이벤트를 받고자 하는 사용자의 User ID로 필터링할 수 있습니다. 해당 User ID에 매칭되는 이벤트는 1초 미만의 지연 시간으로 앱에 전달됩니다.
## 전달 메커니즘
X Activity API는 현재 이벤트를 앱으로 전송하기 위해 다음과 같은 전달 메커니즘을 지원합니다:
* 영구 HTTP 스트림
* [Webhook](/x-api/webhooks/introduction)
## 지원되는 이벤트 유형
현재 X Activity API는 카테고리별로 분류된 다음 이벤트 유형을 지원합니다:
### Post 이벤트
Post 이벤트는 사용자가 Post를 생성하거나 삭제할 때 트리거됩니다.
| 이벤트 이름 | 설명 | 필터 |
| --------------------- | ------------------------------ | --------- |
| `post.create` | 사용자가 Post를 생성할 때 발생 | `user_id` |
| `post.delete` | 사용자가 Post를 삭제할 때 발생 | `user_id` |
| `post.mention.create` | 누군가 필터링된 사용자를 Post에서 @멘션할 때 발생 | `user_id` |
**XAA를 통한 Post 이벤트 vs Filtered Stream:** X Activity API는 `post.create` 및 `post.delete` 이벤트를 지원합니다. `user_id`로 구독하여 사용자가 Post를 생성하거나 삭제할 때 실시간 알림을 받을 수 있습니다.
타겟 키워드 필터링, 불리언 로직, 지역 타겟팅, 언어 필터 또는 Filtered Stream이 지원하는 기타 연산자가 필요한 경우 [Filtered Stream](/x-api/posts/filtered-stream/introduction) 엔드포인트를 대신 사용하세요.
### Follow 이벤트
Follow 이벤트는 필터링된 사용자가 다른 사용자를 팔로우하거나 다른 사용자에게 팔로우될 때 트리거됩니다.
| 이벤트 이름 | 설명 | 필터 |
| ----------------- | ----------------------- | --------- |
| `follow.follow` | 사용자가 다른 사용자를 팔로우할 때 발생 | `user_id` |
| `follow.unfollow` | 사용자가 다른 사용자를 언팔로우할 때 발생 | `user_id` |
### 프로필 이벤트
프로필 이벤트는 사용자가 자신의 프로필 정보를 변경할 때 트리거됩니다.
| 이벤트 이름 | 설명 | 필터 |
| -------------------------------- | ----------------------------- | --------- |
| `profile.update.bio` | 사용자가 프로필 자기소개를 업데이트할 때 발생 | `user_id` |
| `profile.update.profile_picture` | 사용자가 프로필 사진을 업데이트할 때 발생 | `user_id` |
| `profile.update.banner_picture` | 사용자가 프로필 배너를 업데이트할 때 발생 | `user_id` |
| `profile.update.screenname` | 사용자가 표시 이름을 업데이트할 때 발생 | `user_id` |
| `profile.update.handle` | 사용자가 핸들을 업데이트할 때 발생 | `user_id` |
| `profile.update.geo` | 사용자가 프로필 위치를 업데이트할 때 발생 | `user_id` |
| `profile.update.url` | 사용자가 프로필 웹사이트 URL을 업데이트할 때 발생 | `user_id` |
| `profile.update.verified_badge` | 사용자가 인증 배지를 업데이트할 때 발생 | `user_id` |
| `profile.update.affiliate_badge` | 사용자가 제휴 배지를 업데이트할 때 발생 | `user_id` |
### 채팅 이벤트
채팅 이벤트는 새로운 암호화 메시징 스택, 즉 XChat과 관련됩니다.
| 이벤트 이름 | 설명 | 필터 |
| ------------------------ | --------------------------- | --------- |
| `chat.received` | 사용자가 암호화된 다이렉트 메시지를 받을 때 발생 | `user_id` |
| `chat.sent` | 사용자가 암호화된 다이렉트 메시지를 보낼 때 발생 | `user_id` |
| `chat.conversation_join` | 사용자가 암호화된 채팅 대화에 참여할 때 발생 | `user_id` |
### 레거시 DM 이벤트
레거시 DM 이벤트는 암호화되지 않은 기존 DM 시스템과 관련됩니다.
| 이벤트 이름 | 설명 | 필터 |
| -------------------- | --------------------------------------------------------- | --------- |
| `dm.received` | 사용자가 암호화되지 않은 다이렉트 메시지를 받을 때 발생 | `user_id` |
| `dm.sent` | 사용자가 암호화되지 않은 다이렉트 메시지를 보낼 때 발생 | `user_id` |
| `dm.read` | 사용자가 필터링된 사용자의 암호화되지 않은 DM 메시지를 읽을 때, 즉 "읽음 확인"이 발생할 때 발생 | `user_id` |
| `dm.indicate_typing` | 사용자가 필터링된 사용자에게 메시지를 입력 중일 때 발생 | `user_id` |
### 뉴스 이벤트
뉴스 이벤트는 Grok이 큐레이션한 트렌딩 주제 및 헤드라인에 대한 업데이트를 제공합니다.
| 이벤트 이름 | 설명 | 필터 |
| ---------- | ------------------------- | --------- |
| `news.new` | Grok이 큐레이션한 새로운 트렌드와 헤드라인 | `keyword` |
**엔터프라이즈 전용:** `news.new` 이벤트는 현재 Enterprise 및 Partner 등급 계정에서만 사용할 수 있습니다.
### Spaces 이벤트
Spaces 이벤트는 사용자가 Space를 시작하거나 종료할 때 트리거됩니다.
| 이벤트 이름 | 설명 | 필터 |
| -------------- | -------------------- | --------- |
| `spaces.start` | 사용자가 Space를 시작할 때 발생 | `user_id` |
| `spaces.end` | 사용자가 Space를 종료할 때 발생 | `user_id` |
향후 릴리스에서 XAA는 소셜 상호작용, 콘텐츠 참여, 수익화 기능 등 추가 이벤트 유형을 지원하도록 확장될 예정입니다. 새로운 이벤트 유형이 제공되면 문서를 계속 업데이트하겠습니다.
## 이벤트 프라이버시 및 인증
X Activity API는 아래에 설명된 대로 X 앱과 동등하게 **공개 이벤트**와 **비공개 이벤트**를 구분합니다.
### 공개 이벤트
공개 이벤트는 공개 사용자 계정이 공개적으로 수행하는 활동으로, 모든 X 사용자에게 표시됩니다. 이러한 이벤트는 X 플랫폼의 모든 사용자에게 표시되며, 보기 위해 사용자로부터 OAuth 인증을 받을 필요가 없습니다.
**현재 공개 이벤트:**
* 프로필 업데이트(자기소개, 사진, 배너, 위치, URL, 사용자 이름 변경)
* Post 생성(`post.create`) 및 삭제(`post.delete`)
이러한 공개 이벤트의 경우, 필터에 사용자 ID를 지정하여 구독을 생성하고 XAA를 통해 받을 수 있습니다.
### 비공개 이벤트
비공개 이벤트는 OAuth 인증을 통해 사용자의 명시적 동의가 필요한 활동입니다. 사용자는 X를 통해 인증하고 이러한 이벤트에 접근할 수 있도록 개발자 앱에 명시적인 권한을 부여해야 합니다.
**현재 비공개 이벤트:**
* 좋아요 (`like.create`)
* 암호화된 채팅 수신 (`chat.received`)
* 암호화된 채팅 발송 (`chat.sent`)
* DM 수신 (`dm.received`)
* DM 발송 (`dm.sent`)
* DM 읽음 (`dm.read`)
* DM 입력 표시기 (`dm.indicate_typing`)
* Post 멘션 (`post.mention.create`)
**비공개 이벤트에 대한 인증 요구사항:**
* 사용자가 OAuth 2.0을 통해 애플리케이션을 인증해야 합니다
* 애플리케이션이 적절한 OAuth 스코프를 획득해야 합니다
* 사용자가 이러한 이벤트에 접근할 수 있도록 앱에 명시적으로 권한을 부여해야 합니다
* 비공개 이벤트에 대한 구독은 애플리케이션을 승인한 사용자에 대해서만 생성할 수 있습니다
## 구독 한도
X Activity API는 계정 등급에 따라 서로 다른 구독 한도를 가집니다:
| 패키지 등급 | 최대 구독 수 |
| ---------- | ------- |
| 셀프서브 | 1,500 |
| Enterprise | 75,000 |
| Partner | 150,000 |
## 엔드포인트
| 메서드 | 엔드포인트 | 설명 |
| :----- | :--------------------------------------------------------------------------------- | :--------- |
| GET | [`/2/activity/stream`](/x-api/activity/activity-stream) | 활동 스트림에 연결 |
| POST | [`/2/activity/subscriptions`](/x-api/activity/create-x-activity-subscription) | 구독 생성 |
| GET | [`/2/activity/subscriptions`](/x-api/activity/get-x-activity-subscriptions) | 구독 목록 조회 |
| PUT | [`/2/activity/subscriptions/:id`](/x-api/activity/update-x-activity-subscription) | 구독 업데이트 |
| DELETE | [`/2/activity/subscriptions/:id`](/x-api/activity/deletes-x-activity-subscription) | 구독 삭제 |
**계정 설정**
이러한 엔드포인트에 접근하려면 다음이 필요합니다:
* 승인된 [개발자 계정](https://developer.x.com/en/portal/petition/essential/basic-info).
* 프로젝트 내에 위치한 [개발자 앱](/fundamentals/developer-apps)의 키와 토큰을 사용한 인증.
X API v2 엔드포인트에 대한 액세스를 얻는 방법에 대해 [시작 가이드](/x-api/getting-started/getting-access)에서 자세히 알아보세요.
# 소개
Source: https://docs.x.com/ko/x-api/articles/introduction
X API의 Articles 엔드포인트로 리치 텍스트, 이미지, 동영상, 임베드 게시물, 링크를 포함한 장문 게시물의 초안을 프로그래밍 방식으로 작성하고 편집한 뒤, OAuth로 인증된 사용자 계정으로 X에 게시하는 전체 과정을 안내합니다.
Articles 엔드포인트를 사용하면 개발자는 X에서 프로그래밍 방식으로 draft Articles를 생성하고 게시할 수 있습니다. Articles는 서식 있는 텍스트, 임베드된 게시물, 링크, 이미지를 지원하는 장문 형식의 게시물입니다.
이러한 엔드포인트는 `tweet.read`, `tweet.write`, `users.read` 스코프를 사용하는 OAuth 1.0a 또는 OAuth 2.0 PKCE를 통한 사용자 인증이 필요합니다.
현재 API는 두 가지 엔드포인트를 지원합니다.
## draft Article 생성
개발자는 `POST https://api.x.com/2/articles/draft` 엔드포인트를 사용하여 새 draft Article을 생성할 수 있습니다. 요청 본문에는 article 제목, 텍스트 블록과 엔티티로 구성된 [DraftJS](https://draftjs.org/docs/api-reference-content-state) 콘텐츠 상태의 본문 콘텐츠, 그리고 선택적으로 [미디어 업로드 엔드포인트](/x-api/media/introduction)를 통해 업로드한 커버 미디어가 포함됩니다.
## Article 게시
draft가 준비되면 개발자는 `POST https://api.x.com/2/articles/{article_id}/publish` 엔드포인트를 사용하여 공개적으로 게시할 수 있으며, 여기서 `article_id`는 draft를 생성할 때 반환된 ID입니다.
## 시작하기
이 엔드포인트를 사용하려면 사용자 액세스 토큰이 필요합니다. 생성 방법에 대한 자세한 내용은 [PKCE를 사용한 OAuth 2.0 Authorization Code 흐름](/fundamentals/authentication/oauth-2-0/authorization-code) 문서를 참조하세요.
액세스 토큰이 있으면 아래와 같이 draft Article을 생성할 수 있습니다.
```bash theme={null}
curl --request POST 'https://api.x.com/2/articles/draft' \
--header 'Authorization: Bearer XXXXX' \
--header 'Content-Type: application/json' \
--data '{
"title": "My first Article",
"content_state": {
"blocks": [
{
"text": "Hello from the Articles API!",
"type": "unstyled"
}
],
"entities": []
}
}'
```
요청이 성공하면 아래와 같은 JSON 응답을 확인할 수 있습니다.
```json theme={null}
{
"data": {
"id": "1146654567674912769",
"title": "My first Article"
}
}
```
그런 다음 반환된 Article ID를 사용하여 draft를 게시할 수 있습니다.
```bash theme={null}
curl --request POST 'https://api.x.com/2/articles/1146654567674912769/publish' \
--header 'Authorization: Bearer XXXXX'
```
요청이 성공하면 응답에는 게시된 Article에 대해 생성된 게시물의 ID가 포함됩니다.
```json theme={null}
{
"data": {
"post_id": "1346889436626259968"
}
}
```
# 엔터프라이즈
Source: https://docs.x.com/ko/x-api/enterprise-gnip-2.0/enterprise-gnip
X 엔터프라이즈 API와 Gnip 제품군(PowerTrack, Decahose, Search, Engagement, Account Activity, Compliance Firehose)의 개요와 사용 사례, 액세스 방법을 소개합니다.
당사의 엔터프라이즈 API는 X 데이터에 의존하는 사용자에게 최고 수준의 액세스와 신뢰성을 제공합니다. 프리미엄을 넘어 확장하면서 더 안정적인 액세스, 맞춤형 패키지 또는 장기 계약이 필요할 때 적합합니다. 엔터프라이즈 API 액세스에는 전담 계정 관리자와 개인 맞춤형 기술 지원이 포함됩니다.
셀프서브 플랜으로는 요구 사항을 충족할 수 없다고 판단한 경우, 다음 링크에서 엔터프라이즈 제품에 대한 액세스를 신청할 수 있습니다:
## 사용 가능한 엔드포인트
| 실시간 | [PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) | 공개 Post가 발생하는 즉시 완전한 범위로 제공하며, 다양한 연산자와 규칙을 사용해 필터링할 수 있습니다. |
| :------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- | :----------------------------------------------------------- |
| [Decahose API](/x-api/enterprise-gnip-2.0/fundamentals/decahose-api) | 모든 공개 Post와 좋아요의 무작위 10% 샘플을 스트리밍합니다. | |
| :--- | :--- | :--- |
| [Account Activity API](/x-api/enterprise-gnip-2.0/fundamentals/account-activity) | 사용자를 구독하고 Post, 다이렉트 메시지, 좋아요, 팔로우 등 다양한 활동을 받아볼 수 있습니다. | |
| :--- | :--- | :--- |
| 과거 데이터 | [Search API](/x-api/enterprise-gnip-2.0/fundamentals/search-api) | 고급 필터링 도구를 사용하여 지난 30일 또는 공개 Post 전체 아카이브를 검색합니다. |
| [Historical PowerTrack API](/x-api/enterprise-gnip-2.0/powertrack-api) | 경제적인 일괄 액세스 프로세스를 사용하여 공개 Post 전체 아카이브를 필터링합니다. | |
| 인사이트 | [Engagement API](/x-api/enterprise-gnip-2.0/fundamentals/engagement-api) | 공개 Post의 노출 및 참여량을 측정합니다. |
| 컴플라이언스 | [Compliance Firehose API](/x-api/enterprise-gnip-2.0/fundamentals/firehouse) | 모든 컴플라이언스 이벤트를 스트리밍합니다. |
| 사용량 | [Usage API](/x-api/enterprise-gnip-2.0/fundamentals/usage) | 엔터프라이즈 제품 전반에 걸친 활동 소비량에 대한 프로그래밍 방식의 액세스를 제공합니다. |
## 주요 개념
### Gnip 콘솔
[Gnip 콘솔](/x-api/enterprise-gnip-2.0/fundamentals/overview)을 통해 엔터프라이즈 제품과 계정 액세스를 관리할 수 있습니다.
### 강화(Enrichments)
유료 등급을 사용하는 개발자를 위해 프리미엄 API의 응답 페이로드에 메타데이터를 추가했습니다. 확장 URL, 설문 데이터 및 프로필 위치 정보에 대한 자세한 내용은 [강화 섹션](/x-api/enterprise-gnip-2.0/fundamentals/data-enrichments)을 참조하세요.
### 고급 필터링 도구
Premium Search API는 표준 검색 엔드포인트에서는 사용할 수 없는 고급 연산자 세트를 제공합니다. 이러한 연산자 중 다수는 무료 샌드박스 사용자도 사용할 수 있지만, 유료 등급을 사용하면 더 강력한 연산자 세트를 사용할 수 있습니다. 자세한 내용은 [규칙 및 필터 섹션](/x-api/enterprise-gnip-2.0/fundamentals/rules-filtering#getting-started-with-enterprise-rules-and-queries)을 참조하세요.
## X API v2 살펴보기
v2에서 현재 사용할 수 있는 기능을 살펴보고 싶으신가요? 새로운 기능을 확인하려면 문서를 참조하고, 향후 X API v2로 이전하는 데 도움이 되는 리소스는 마이그레이션 허브를 방문하세요. 새 v2 엔드포인트 섹션에 나열된 각 엔드포인트의 마이그레이션 가이드에도 액세스할 수 있습니다.
[자세히 알아보기](/x-api/migrate/overview)
도움이 필요하신가요?
지원 섹션을 확인하시거나 계정 관리자에게 문의하여 지원팀에 연락하는 방법을 알아보세요.
[지원](https://developer.x.com/en/support/x-api))
# X API 소개
Source: https://docs.x.com/ko/x-api/getting-started/about-x-api
X API는 X의 공개 대화에 대한 프로그래밍 방식의 액세스를 제공합니다. 게시물 검색과 조회, 트렌드와 참여도 분석, 사용자 검색, 외부 서비스 통합 구축, v2 엔드포인트 활용, 새로운 플랫폼 경험 구축까지 다양한 용도로 활용할 수 있습니다.
X API는 X의 공개 대화에 대한 프로그래밍 방식의 액세스를 제공합니다. 게시물을 검색하고, 트렌드를 분석하며, 통합을 구축하고, 플랫폼에서 새로운 경험을 만들 수 있습니다.
***
## 할 수 있는 작업
| 기능 | 설명 |
| :--------- | :--------------------------- |
| **게시물 읽기** | 게시물을 검색, 조회하고 실시간으로 스트리밍 |
| **콘텐츠 게시** | 게시물, 답글, 스레드 작성 |
| **사용자 관리** | 사용자 조회, 팔로우/차단/뮤트 관리 |
| **데이터 분석** | 지표, 트렌드, 참여도 분석에 액세스 |
| **통합 구축** | DM 전송, 리스트 관리, Spaces와 상호 작용 |
***
## API 버전
최신 기능과 유연한 가격 정책을 제공하는 X API의 현재 버전입니다.
**v2를 사용해야 하는 이유:**
* 사용량 기반 가격 정책
* 최신 JSON 응답 형식
* 유연한 [fields](/x-api/fundamentals/fields) 및 [expansions](/x-api/fundamentals/expansions)
* 고급 기능: 주석, 대화 추적, 편집 기록
* 모든 신규 엔드포인트 및 기능
**시작하기:**
1. [console.x.com](https://console.x.com)에서 가입
2. 앱을 만들고 자격 증명을 받기
3. [첫 요청 보내기](/x-api/getting-started/make-your-first-request)
X API의 이전 버전입니다. 지원이 제한적이므로 신규 프로젝트에는 v2를 사용하세요.
**계속 사용 가능:**
* 일부 미디어 업로드 엔드포인트
* 레거시 스트리밍 (지원 중단됨)
* 일부 특수 엔드포인트
**v2로 마이그레이션:**
엔드포인트 매핑 및 데이터 형식 변경 사항은 [마이그레이션 가이드](/x-api/migrate/overview)를 참조하세요.
***
## 사용 가능한 리소스
X API는 다음 리소스 유형에 대한 액세스를 제공합니다:
게시물 검색, 조회, 작성, 삭제. 타임라인, 스레드, 인용 게시물에 액세스.
프로필 조회, 관계 관리, 팔로워 데이터 액세스.
라이브 오디오 대화와 참여자를 검색.
사용자 간 비공개 메시지 송수신.
계정의 큐레이션된 리스트 생성 및 관리.
위치별 트렌드 주제에 액세스.
***
## v2 주요 기능
필요한 데이터만 요청하세요. `fields` 매개변수로 특정 속성을 선택하고 `expansions`로 관련 객체를 포함시킵니다.
```bash theme={null}
curl "https://api.x.com/2/tweets/123?tweet.fields=created_at,public_metrics&expansions=author_id&user.fields=username" \
-H "Authorization: Bearer $TOKEN"
```
[fields에 대해 자세히 알아보기 →](/x-api/fundamentals/fields)
게시물에는 사람, 장소, 제품, 주제를 식별하는 의미론적 주석이 포함됩니다. 주제별로 스트림과 검색을 필터링할 수 있습니다.
[주석에 대해 자세히 알아보기 →](/x-api/fundamentals/post-annotations)
공개 지표(좋아요, 리포스트, 답글)와 본인 게시물의 비공개 지표(노출수, 클릭수)에 액세스할 수 있습니다.
[지표에 대해 자세히 알아보기 →](/x-api/fundamentals/metrics)
`conversation_id`를 사용해 전체 대화 스레드를 재구성합니다. 스레드 전체에서 답글을 추적할 수 있습니다.
[대화 추적에 대해 자세히 알아보기 →](/x-api/fundamentals/conversation-id)
이전 버전 및 편집 메타데이터를 포함한 게시물의 편집 기록에 액세스합니다.
[게시물 편집에 대해 자세히 알아보기 →](/x-api/fundamentals/edit-posts)
***
## 가격
X API v2는 **사용량 기반** 가격 정책을 사용합니다:
| 혜택 | 설명 |
| :--------- | :------------------------------ |
| **구독 없음** | 사용한 만큼만 지불 |
| **크레딧 기반** | 크레딧을 구매하고 요청 시 차감 |
| **실시간 추적** | Developer Console에서 사용량 모니터링 |
| **중복 제거** | 24시간 내 동일 리소스를 두 번 요청해도 한 번만 과금 |
[가격 세부 정보 보기 →](/x-api/getting-started/pricing)
***
## 다음 단계
가입하고 첫 번째 앱을 만드세요.
몇 분 안에 API를 호출하세요.
# 액세스 받기
Source: https://docs.x.com/ko/x-api/getting-started/getting-access
개발자 계정에 가입하고, 앱을 생성한 후, X API 호출을 시작하는 데 필요한 API 키, bearer token 및 OAuth 자격 증명을 저장합니다.
세 가지 단계로 X API를 시작하세요: 가입, 앱 생성, 자격 증명 저장.
***
## 1단계: 개발자 계정 생성
[console.x.com](https://console.x.com)을 방문하여 X 계정으로 로그인하세요.
개발자 계약 및 정책을 검토하고 수락하세요.
API를 어떻게 사용할지에 대한 기본 정보를 제공하세요.
***
## 2단계: 앱 생성
가입 후 API 자격 증명을 얻기 위해 앱을 생성하세요:
Developer Console 대시보드에서 새 앱을 생성하세요.
앱의 이름, 설명 및 사용 사례를 제공하세요.
콘솔이 API 키와 토큰을 생성합니다.
***
## 3단계: 자격 증명 저장
인증 요구 사항에 따라 여러 자격 증명을 받게 됩니다:
| 자격 증명 | 목적 |
| :------------------------ | :----------------------------------------- |
| **API Key & Secret** | 앱을 식별합니다. 토큰 생성 및 OAuth 1.0a 요청 서명에 사용됩니다. |
| **Bearer Token** | 공개 데이터를 읽기 위한 App-only 인증. |
| **Access Token & Secret** | 내 계정을 대신하여 요청 (OAuth 1.0a). |
| **Client ID & Secret** | user-context 요청을 위한 OAuth 2.0 인증. |
**즉시 저장하세요.** 자격 증명은 한 번만 표시됩니다. 비밀번호 관리자나 보안 저장소에 저장하세요. 잃어버리면 재생성해야 하며(이 경우 이전 것은 무효화됩니다).
***
## 어떤 자격 증명이 필요한가요?
공개 데이터에 대한 간단한 읽기 전용 액세스를 위해 **Bearer Token**을 사용하세요.
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
최적: 게시물 검색, 사용자 조회, 트렌드 읽기.
사용자를 대신해 활동하려면 **OAuth 2.0** (권장) 또는 **OAuth 1.0a**를 사용하세요.
OAuth 2.0은 세분화된 스코프를 제공합니다—필요한 권한만 요청하세요.
최적: 게시, 좋아요, 팔로우, DM 액세스.
[OAuth 2.0 가이드 →](/resources/fundamentals/authentication/oauth-2-0/overview)
자신의 계정으로 요청을 하려면 **Access Token & Secret**을 사용하세요.
이러한 토큰은 앱을 소유한 계정을 나타냅니다.
최적: 테스트, 개인 봇, 자신의 자동화.
***
## 자격 증명 보안 모범 사례
소스 코드에 자격 증명을 하드코딩하지 마세요.
자격 증명 파일을 `.gitignore`에 추가하세요.
보안 조치로 자격 증명을 주기적으로 재생성하세요.
앱에 필요한 OAuth 권한만 요청하세요.
***
## 다음 단계
새 자격 증명으로 API를 호출하세요.
OAuth 1.0a와 OAuth 2.0을 이해하세요.
# X API 사용량 기반 요금제와 크레딧
Source: https://docs.x.com/ko/x-api/getting-started/pricing
X API는 별도의 구독이 필요 없는 사용량 기반 요금제입니다. 크레딧 구매, 자동 충전, 월별 지출 한도 설정, 요청 중복 제거를 지원하며 사용 금액에 따라 최대 20%의 무료 xAI (Grok) API 크레딧을 환급받을 수 있습니다.
X API는 **사용량 기반(pay-per-usage)** 요금제를 사용합니다. 구독 없이 사용한 만큼만 지불하세요.
***
## 작동 방식
Developer Console에서 크레딧을 미리 구매하세요. API 요청 시 크레딧이 차감됩니다.
엔드포인트마다 비용이 다릅니다. 현재 요율은 Developer Console에서 확인할 수 있습니다.
계약, 구독, 최소 지출액이 없습니다. 언제든지 시작하고 중단할 수 있습니다.
Developer Console에서 사용량과 비용을 실시간으로 모니터링하세요.
X API 크레딧을 구매하면 지출 금액에 따라 최대 20%까지 무료 [xAI API](https://docs.x.ai) 크레딧을 받을 수 있습니다. [자세히 보기](#free-xai-api-credits)
***
## 크레딧 소비 상세
모든 가격은 가져온 리소스당(읽기) 또는 요청당(쓰기/액션) 기준입니다. Developer Console에서 [크레딧을 구매](https://console.x.com)할 수 있습니다.
### 읽기(Read) 작업
응답에 반환된 리소스당 과금됩니다.
| 리소스 | 단가 |
| :---------------------------- | :----------- |
| **Posts: Read** | 리소스당 \$0.005 |
| **User: Read** | 리소스당 \$0.010 |
| **DM Event: Read** | 리소스당 \$0.010 |
| **Following/Followers: Read** | 리소스당 \$0.010 |
| **List: Read** | 리소스당 \$0.005 |
| **Space: Read** | 리소스당 \$0.005 |
| **Community: Read** | 리소스당 \$0.005 |
| **Note: Read** | 리소스당 \$0.005 |
| **Like: Read** | 리소스당 \$0.001 |
| **Mute: Read** | 리소스당 \$0.001 |
| **Block: Read** | 리소스당 \$0.001 |
| **Profile Update: Read** | 리소스당 \$0.005 |
Pay-per-use 요금제는 **월 청구 주기당 200만 건의 Post 읽기** 상한이 적용됩니다. 더 많은 볼륨이 필요한 경우 [Enterprise 요금제](/forms/enterprise-api-interest)로 업그레이드해야 합니다.
### 쓰기(Write) 작업
요청당 과금됩니다.
| 액션 | 단가 |
| :--------------------------- | :---------- |
| **Post: Create** | 요청당 \$0.015 |
| **Post: Create (with URL)** | 요청당 \$0.200 |
| **Post: Create (summoned)** | 요청당 \$0.010 |
| **DM Interaction: Create** | 요청당 \$0.015 |
| **User Interaction: Create** | 요청당 \$0.015 |
| **Interaction: Delete** | 요청당 \$0.010 |
| **Content: Manage** | 요청당 \$0.005 |
| **List: Create** | 요청당 \$0.010 |
| **List: Manage** | 요청당 \$0.005 |
| **Bookmark** | 요청당 \$0.005 |
| **Media Metadata** | 요청당 \$0.005 |
| **Privacy: Update** | 요청당 \$0.010 |
| **Mute: Delete** | 요청당 \$0.005 |
| **Counts: Recent** | 요청당 \$0.005 |
| **Counts: All** | 요청당 \$0.010 |
| **Trends** | 요청당 \$0.010 |
가격은 변경될 수 있습니다. 최신 요율은 항상 [Developer Console](https://console.x.com) 및 [developer.x.com 요금 페이지](https://developer.x.com/#pricing)에서 확인할 수 있습니다.
### Webhook 이벤트
[X Activity API](/x-api/activity/introduction)를 통해 전달되는 Webhook 이벤트는 Activity API 문서에 표시된 것과 동일한 이벤트 이름을 사용하여 전달된 이벤트당 과금됩니다. 과금 대상 이벤트당 한 번 과금되며, 다른 리소스와 동일한 24시간 UTC 기간 내에서 중복 제거됩니다.
| 이벤트 | 이벤트당 비용 |
| :----------------------- | :------ |
| `post.create` | \$0.005 |
| `post.delete` | 과금되지 않음 |
| `follow.follow` | \$0.010 |
| `follow.unfollow` | \$0.010 |
| `profile.update.*` | \$0.005 |
| `chat.received` | \$0.010 |
| `chat.sent` | 과금되지 않음 |
| `chat.conversation_join` | 과금되지 않음 |
| `dm.received` | \$0.010 |
| `dm.sent` | 과금되지 않음 |
| `dm.read` | 과금되지 않음 |
| `dm.indicate_typing` | 과금되지 않음 |
| `news.new` | \$0.005 |
| `spaces.start` | \$0.005 |
| `spaces.end` | \$0.005 |
***
## Owned Reads
Owned Reads는 본인의 developer app이 본인의 데이터(posts, bookmarks, followers, likes, lists 등)에 대해 수행하는 요청입니다. 이러한 엔드포인트의 가격은 **리소스당 \$0.001**(\$1로 리소스 1,000개)입니다.
다음 엔드포인트는 `{id}`가 인증된 사용자와 일치하고, 해당 사용자가 developer app의 소유자인 경우 Owned Read 요금이 적용됩니다.
| 엔드포인트 | 설명 |
| :----------------------------------- | :-------------- |
| `GET /2/users/{id}/tweets` | 본인의 posts |
| `GET /2/users/{id}/mentions` | 본인의 멘션 |
| `GET /2/users/{id}/liked_tweets` | 본인이 좋아요한 posts |
| `GET /2/users/{id}/bookmarks` | 본인의 북마크 |
| `GET /2/users/{id}/followers` | 본인의 팔로워 |
| `GET /2/users/{id}/following` | 본인이 팔로우하는 계정 |
| `GET /2/users/{id}/blocking` | 본인이 차단한 계정 |
| `GET /2/users/{id}/muting` | 본인이 뮤트한 계정 |
| `GET /2/users/{id}/owned_lists` | 본인이 소유한 lists |
| `GET /2/users/{id}/followed_lists` | 본인이 팔로우하는 lists |
| `GET /2/users/{id}/list_memberships` | 본인이 속한 lists |
| `GET /2/users/{id}/pinned_lists` | 본인의 고정 lists |
Owned Reads를 활용하면 대시보드 앱, 개인 분석 도구, 계정 관리 도구 등 사용자 본인의 데이터를 다루는 앱을 훨씬 저렴하게 구축할 수 있습니다.
***
## 중복 제거(Deduplication)
모든 리소스는 **24시간 UTC 일자 윈도우** 내에서 중복 제거됩니다. 특정 리소스(예: Post)를 요청하고 과금된 경우, 동일한 윈도우 내에서 같은 리소스를 다시 요청해도 추가 비용이 발생하지 않습니다.
이는 다음을 의미합니다:
* 동일한 Post를 하루에 여러 번 요청해도 한 번만 과금됩니다
* 중복 제거 윈도우는 UTC 자정에 초기화됩니다
* 과금 대상 모든 리소스(Posts, 사용자 등)에 적용됩니다
중복 제거는 **소프트 보장(soft guarantee)** 입니다. 대부분의 경우 적용되지만, 서비스 장애와 같은 특정 엣지 케이스에서는 리소스가 중복 제거되지 않을 수 있습니다.
***
## 크레딧 잔액
크레딧 잔액은 Developer Console에 표시됩니다. API 요청 시 크레딧이 실시간으로 차감됩니다.
서비스 중단을 방지하기 위해 크레딧 잔액을 정기적으로 모니터링하세요. 잔액이 0에 도달하기 전에 크레딧을 추가하여 중단 없는 API 액세스를 보장하세요.
***참고:** 계정 크레딧 잔액이 약간 마이너스가 될 수 있습니다. 이 경우 마이너스 잔액을 충당할 수 있도록 크레딧을 추가할 때까지 API 요청이 차단됩니다.*
### 자동 충전(Auto-recharge)
자동 충전을 활성화하여 크레딧 잔액을 자동으로 충전하고 서비스 중단을 방지하세요. Developer Console에서 다음을 설정할 수 있습니다:
| 설정 | 설명 |
| :---------- | :--------------------------------------- |
| **충전 금액** | 자동 충전이 발생할 때 추가되는 금액(예: \$25) |
| **트리거 임계값** | 잔액이 이 금액 미만으로 떨어지면 자동 충전이 활성화됩니다(예: \$5) |
자동 충전을 사용하려면 기본 결제 수단으로 저장된 결제 방법이 필요합니다. Developer Console에서 또는 지원팀에 문의하여 언제든지 취소할 수 있습니다.
#### 자동 충전 안전장치(Auto-recharge safeguards)
폭주하거나 예기치 않게 큰 청구로부터 보호하기 위해, 자동 충전에는 두 가지 기본 제한이 적용됩니다:
* **5분 창당 1회 충전.** 자동 청구는 5분에 최대 한 번만 발생할 수 있으므로, 사용량이 갑자기 급증하더라도 여러 번의 충전이 연달아 누적되지 않습니다.
* **잔액이 0이거나 마이너스이면 일시 중지.** 계정 잔액이 0이거나 마이너스인 동안에는 자동 충전이 실행되지 않습니다. 자동 충전을 다시 시작하려면 크레딧을 수동으로 추가하세요.
사용 패턴이 매우 폭발적이어서 한 번의 전체 충전을 5분 이내에 소진할 정도라면, 자동 충전이 켜져 있어도 "크레딧 부족" 오류가 발생할 수 있습니다. 한 번의 충전이 최대 사용량 기준 5분 창을 충분히 견딜 수 있도록 **충전 금액**을 늘리세요.
***
### 지출 한도(Spending limits)
비용을 관리하기 위해 청구 주기당 지출 가능한 최대 금액을 설정하세요. 한도에 도달하면 다음 청구 주기까지 API 요청이 차단됩니다.
| 옵션 | 설명 |
| :-------- | :-------------------------------- |
| **지출 한도** | 청구 주기당 최대 지출 금액을 특정 달러 금액으로 설정합니다 |
특히 개발 및 테스트 단계에서 예기치 않은 비용을 방지하기 위해 지출 한도를 활용하세요.
***
## 무료 xAI API 크레딧
X API 크레딧을 구매하면 청구 주기 동안의 누적 지출 금액에 따라 무료 [xAI API](https://docs.x.ai) 크레딧을 받을 수 있습니다.
무료 xAI 크레딧을 받으려면 xAI 팀을 X developer 계정에 연결해야 합니다. [developer console](https://console.x.com)의 계정 설정에서 연결할 수 있습니다.
### 작동 방식
각 청구 주기 동안의 누적 지출이 추적됩니다. 지출 임계값을 넘을 때마다 더 높은 리워드 적립률이 잠금 해제됩니다. 새로운 청구 주기가 시작되면 누적 지출은 \$0으로 초기화됩니다.
| 누적 지출 | 적립률 |
| :------------ | :-- |
| \$0 – \$199 | 0% |
| \$200 – \$499 | 10% |
| \$500 – \$999 | 15% |
| \$1,000+ | 20% |
이 적립률은 **전체 누적 잔액**에 적용되지만, 실제로는 차액—새로 적립되어야 할 금액에서 이미 적립된 금액을 뺀 만큼만 받게 됩니다.
### 예시
청구 주기 동안 여러 번 구매했다고 가정해 봅시다:
| 구매 | 적립률 | 총 적립액 | 이미 적립됨 | 받는 금액 |
| :---------- | :-- | :------- | :------- | :---------- |
| \$100 | 0% | \$0 | \$0 | **\$0** |
| \$100 | 10% | \$20 | \$0 | **\$20** |
| \$150 | 10% | \$35 | \$20 | **\$15** |
| \$150 | 15% | \$75 | \$35 | **\$40** |
| \$250 | 15% | \$112.50 | \$75 | **\$37.50** |
| \$250 | 20% | \$200 | \$112.50 | **\$87.50** |
| | | | | |
| **\$1,000** | | | | **\$200** |
이는 \$1,000을 한 번에 구매했을 때 받는 금액과 동일합니다. 구매 순서와 규모는 총 리워드에 영향을 미치지 않습니다.
[console.x.ai](https://console.x.ai)에서 xAI 크레딧 잔액을 확인하고 계정을 관리할 수 있습니다. xAI API 청구에 대한 자세한 내용은 [xAI 청구 문서](https://docs.x.ai/docs/key-information/billing)를 참조하세요.
***
## 사용량 모니터링
[Usage 엔드포인트](/x-api/usage/introduction)를 사용하여 API 사용량을 프로그래밍 방식으로 추적할 수 있습니다:
```bash theme={null}
curl "https://api.x.com/2/usage/tweets" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
이는 일일 Post 소비량을 반환하여 다음과 같은 작업에 도움이 됩니다:
* 예산 대비 소비량 추적
* 한도 도달 시 알림 설정
* 소비량이 높은 엔드포인트 식별
* 사용량 보고서 생성
***
## 다음 단계
크레딧을 구매하고 현재 요금을 확인하세요.
사용량을 프로그래밍 방식으로 모니터링하세요.
# X API
Source: https://docs.x.com/ko/x-api/introduction
게시물, 사용자, Spaces, 리스트, DM, 트렌드, 필터링된 스트림, 검색을 위한 v2 REST 엔드포인트와 사용량 기반 pay-per-use 가격 정책, 공식 SDK 및 Postman 컬렉션으로 X에 프로그래밍 방식으로 액세스하는 방법을 소개합니다.
X API는 X의 공개 대화에 대한 프로그래밍 방식의 액세스를 제공합니다. 유연한 사용량 기반 가격 정책과 최신 REST 엔드포인트를 통해 게시물을 읽고, 콘텐츠를 게시하고, 사용자를 관리하고, 트렌드를 분석할 수 있습니다.
앱을 만들고 몇 분 안에 첫 요청을 보내세요.
사용 가능한 모든 엔드포인트를 살펴보세요.
공식 Python 및 TypeScript 라이브러리입니다.
***
## 무엇을 만들 수 있나요
게시물 검색, 조회, 게시. 타임라인, 스레드, 인용 게시물에 액세스합니다.
사용자를 조회하고 팔로우, 차단, 뮤트를 관리합니다.
라이브 오디오 대화와 참여자를 찾으세요.
비공개 메시지를 송수신합니다.
큐레이션된 계정 리스트를 만들고 관리합니다.
위치별 트렌드 주제에 액세스합니다.
***
## 가격
X API는 **사용량 기반** 가격을 사용합니다. 구독 없이 — 사용한 만큼만 지불합니다.
작게 시작하고 성장하세요. 비용은 실제 사용량에 따라 확장됩니다.
계약이나 최소 지출 없음. 언제든지 중단할 수 있습니다.
Developer Console에서 사용량과 비용을 실시간으로 모니터링합니다.
크레딧을 미리 구매합니다. API 사용에 따라 차감됩니다.
X API 크레딧을 구매하면 무료 [xAI API](https://docs.x.ai) 크레딧을 받을 수 있습니다 — 지출 금액에 따라 최대 20% 적립. [자세히 알아보기](/x-api/getting-started/pricing#free-xai-api-credits)
***
## 주요 기능
### 풍부한 데이터 객체
게시물, 사용자, 미디어 등에 대한 상세하고 구조화된 데이터에 액세스합니다:
* **게시물**: 전체 텍스트, 지표, 엔티티, 주석, 대화 스레드
* **사용자**: 프로필, 팔로워 수, 인증 상태
* **미디어**: 이미지, 비디오, 메타데이터가 있는 GIF
* **설문조사**: 옵션 및 투표 수
[fields](/x-api/fundamentals/fields) 및 [expansions](/x-api/fundamentals/expansions)로 응답을 맞춤 설정하여 필요한 데이터만 정확하게 받으세요.
### Filtered stream
게시물이 게시되는 대로 거의 실시간으로 전달받으세요. 최대 1,000개의 필터링 규칙을 정의하여 일치하는 게시물만 수신할 수 있습니다.
```bash theme={null}
# Add a rule
curl -X POST "https://api.x.com/2/tweets/search/stream/rules" \
-H "Authorization: Bearer $TOKEN" \
-d '{"add": [{"value": "from:xdevelopers"}]}'
# Connect to stream
curl "https://api.x.com/2/tweets/search/stream" \
-H "Authorization: Bearer $TOKEN"
```
[filtered stream에 대해 자세히 알아보기 →](/x-api/posts/filtered-stream/introduction)
### Full-archive search
공개 게시물의 전체 기록을 검색하세요 — 2006년까지. 사용자, 키워드, 날짜 등에 대한 연산자로 쿼리를 빌드하세요.
```bash theme={null}
curl "https://api.x.com/2/tweets/search/all?query=AI%20lang:en" \
-H "Authorization: Bearer $TOKEN"
```
### 지표
노출수, 좋아요, 리포스트, 답글, 비디오 조회수 등의 참여도 지표에 액세스합니다.
[검색에 대해 자세히 알아보기 →](/x-api/posts/search/introduction)
***
## 빠른 시작
[console.x.com](https://console.x.com)에서 가입하고 앱을 만드세요.
앱 전용 요청을 위한 Bearer Token을 생성하세요.
사용자 조회를 시도해 보세요:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## 도구 & 라이브러리
비동기 지원이 있는 공식 Python 라이브러리입니다.
공식 TypeScript/JavaScript 라이브러리입니다.
대화형 API 탐색기입니다.
[모든 라이브러리 둘러보기 →](/tools-and-libraries)
***
## 지원
커뮤니티와 X 팀의 도움을 받으세요.
FAQ 및 문제 해결 가이드입니다.
# X API 개요
Source: https://docs.x.com/ko/x-api/overview
게시물, 사용자, Spaces, Direct Message, 리스트, 트렌드, 미디어, 컴플라이언스, 스트리밍 및 웹훅 엔드포인트를 다루는 X API v2 전체 레퍼런스입니다.
X API는 X의 공개 대화에 프로그래밍 방식으로 액세스할 수 있게 해줍니다. 아래의 모든 엔드포인트는 [사용량 기반](/x-api/introduction) 요금제에서 사용할 수 있습니다. Enterprise 전용으로 표시된 엔드포인트는 [Enterprise](/enterprise-api/introduction) 요금제가 필요합니다.
***
## 엔드포인트
게시물을 검색, 검색 및 게시합니다. 타임라인, 스레드 및 인용 게시물에 액세스하세요.
프로필을 조회하고 팔로우, 차단 및 뮤트를 관리하세요.
개인 메시지를 보내고 받습니다.
라이브 오디오 대화 및 참가자를 찾습니다.
큐레이션된 계정 리스트를 생성하고 관리합니다.
게시물에 좋아요를 누르거나 취소합니다. 누가 게시물에 좋아요를 눌렀는지 조회합니다.
위치별 트렌딩 토픽과 개인화된 트렌드.
이미지, 비디오, GIF를 업로드합니다. 자막 및 메타데이터를 관리합니다.
커뮤니티를 조회 및 검색합니다.
커뮤니티 노트를 생성, 평가 및 검색합니다.
뉴스 기사를 검색하고 조회합니다.
배치 컴플라이언스 작업 및 컴플라이언스 스트림.
***
## 스트리밍 및 실시간
필터 규칙과 일치하는 게시물을 실시간으로 받아보세요.
팔로우, 좋아요, 프로필 업데이트와 같은 실시간 활동 이벤트를 구독하세요.
HTTP 콜백을 통해 이벤트 데이터를 받으세요.
***
## Enterprise 전용
이러한 엔드포인트에는 [Enterprise 요금제](/enterprise-api/introduction)가 필요합니다.
전체 firehose 및 언어별 스트림.
모든 좋아요 또는 샘플링된 좋아요를 실시간으로 스트리밍합니다.
고급 연산자를 지원하는 고성능 필터링 스트리밍.
대규모 게시물 및 미디어 참여 지표.
실시간 사용자 이벤트 구독.
웹훅을 통한 filtered stream 전달.
***
## 빠른 시작
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
자격 증명을 받고 몇 분 안에 API를 호출하세요.
공식 Python 및 TypeScript 라이브러리.
# Filtered Stream 연산자
Source: https://docs.x.com/ko/x-api/posts/filtered-stream/integrate/operators
X API v2 Filtered Stream 연산자 전체 레퍼런스로, 스트림 규칙에 사용할 수 있는 keyword, has:, is:, from:, lang: 및 Enterprise 전용 시맨틱 embedding: 연산자를 예제와 함께 다루고 액세스 티어별 제한도 정리합니다.
이 페이지는 Filtered Stream의 [규칙 작성](/x-api/posts/filtered-stream/integrate/build-a-rule) 시 사용할 수 있는 연산자의 전체 목록을 제공합니다.
## 개요
연산자는 특정 게시물 속성을 매칭하는 데 사용됩니다. 두 가지 유형이 있습니다:
* **독립형 연산자(Standalone operators)** — 단독으로 또는 다른 연산자와 함께 사용 가능
* **결합 필수 연산자(Conjunction-required operators)** — 최소 하나의 독립형 연산자와 함께 사용해야 함
대부분의 연산자는 Pay-per-use와 Enterprise 모두에서 사용할 수 있습니다. 시맨틱 임베딩 등 일부 고급 연산자는 추가 티어 액세스가 포함된 Enterprise가 필요합니다.
***
## 키워드 및 구문 연산자
| Operator | Type | Summary | Example |
| :---------------------- | :--------- | :-------------------------------- | :------------------------------------ |
| `keyword` | Standalone | 게시물 본문 내 키워드를 매칭(토큰화된 매칭) | `pepsi OR cola OR "coca cola"` |
| `emoji` | Standalone | 게시물 본문 내 이모지를 매칭 | `(😃 OR 😡) 😬` |
| `"exact phrase"` | Standalone | 게시물 본문 내 정확한 구문을 매칭 | `("X API" OR #v2) -"filtered stream"` |
| `"keyword1 keyword2"~N` | Standalone | 근접 매칭 — 키워드 간 거리가 N 토큰 이내(최대 N=6) | `"social media"~5` |
***
## 엔티티 연산자
| Operator | Type | Summary | Example |
| :------- | :--------- | :----------------------- | :--------------------------- |
| `#` | Standalone | 해시태그를 포함한 게시물을 매칭(정확 매칭) | `#thankunext #fanart` |
| `@` | Standalone | 사용자명을 멘션한 게시물을 매칭 | `(@XDevelopers OR @api) -@x` |
| `$` | Standalone | 캐시태그를 포함한 게시물을 매칭 | `$twtr OR @XDevelopers -$fb` |
***
## 사용자 연산자
| Operator | Type | Summary | Example |
| :------------------- | :--------- | :--------------------------- | :------------------------------ |
| `from:` | Standalone | 특정 사용자가 작성한 게시물을 매칭 | `from:XDevelopers OR from:api` |
| `to:` | Standalone | 특정 사용자에 대한 답글 게시물을 매칭 | `to:XDevelopers OR to:api` |
| `retweets_of:` | Standalone | 특정 사용자의 리포스트를 매칭 | `retweets_of:XDevelopers` |
| `from_affiliate_of:` | Standalone | 특정 사용자의 제휴 계정이 작성한 게시물을 매칭 | `from_affiliate_of:XDevelopers` |
| `to_affiliate_of:` | Standalone | 특정 사용자의 제휴 계정에 대한 답글 게시물을 매칭 | `to_affiliate_of:XDevelopers` |
***
## URL 연산자
| Operator | Type | Summary | Example |
| :----------------- | :--------- | :---------------------------------------------- | :------------------------------ |
| `url:` | Standalone | URL에 대한 토큰화된 매칭(`url` 또는 `expanded_url` 필드와 매칭) | `url:"https://developer.x.com"` |
| `url_title:` | — | 확장된 URL HTML 제목 메타데이터에 대한 키워드 매칭 | `url_title:snow` |
| `url_description:` | — | 확장된 페이지 설명 메타데이터에 대한 키워드 매칭 | `url_description:weather` |
| `url_contains:` | — | URL 내용에 대한 리터럴 매칭 | `url_contains:photos` |
***
## 컨텍스트 및 엔티티 연산자
| Operator | Type | Summary | Example |
| :----------------- | :--------- | :----------------------- | :------------------------------------------------ |
| `context:` | Standalone | 특정 도메인/엔티티 쌍을 가진 게시물을 매칭 | `context:10.799022225751871488` or `context:47.*` |
| `entity:` | Standalone | 특정 엔티티 문자열 값을 가진 게시물을 매칭 | `entity:"Michael Jordan"` |
| `conversation_id:` | Standalone | 특정 대화 스레드의 게시물을 매칭 | `conversation_id:1334987486343299072` |
***
## 사용자 프로필 연산자
| Operator | Type | Summary | Example |
| :-------------- | :--------- | :--------------------- | :--------------------------------------------- |
| `bio:` | Standalone | 게시물 작성자의 bio 내 키워드를 매칭 | `bio:developer OR bio:"data engineer"` |
| `bio_name:` | Standalone | 게시물 작성자의 이름 내 키워드를 매칭 | `bio_name:phd OR bio_name:md` |
| `bio_location:` | Standalone | 게시물 작성자의 위치 내 키워드를 매칭 | `bio_location:"big apple" OR bio_location:nyc` |
***
## 위치 연산자
| Operator | Type | Summary | Example |
| :--------------- | :--------- | :------------------ | :---------------------------------------------------------- |
| `place:` | Standalone | 특정 위치로 태깅된 게시물을 매칭 | `place:"new york city" OR place:seattle` |
| `place_country:` | Standalone | 국가 코드와 일치하는 게시물을 매칭 | `place_country:US OR place_country:MX` |
| `point_radius:` | Standalone | 한 지점의 반경 내 게시물을 매칭 | `point_radius:[2.355128 48.861118 16km]` |
| `bounding_box:` | Standalone | 경계 상자 내 게시물을 매칭 | `bounding_box:[-105.301758 39.964069 -105.178505 40.09455]` |
***
## 게시물 유형 연산자
| Operator | Type | Summary | Example |
| :------------- | :------------------- | :------------------------- | :------------------------------ |
| `is:retweet` | Conjunction required | 리포스트를 매칭 | `data @XDevelopers -is:retweet` |
| `is:reply` | Conjunction required | 답글을 매칭 | `from:XDevelopers is:reply` |
| `is:quote` | Conjunction required | 인용 게시물을 매칭 | `"sentiment analysis" is:quote` |
| `is:verified` | Conjunction required | 인증된 작성자의 게시물을 매칭 | `#nowplaying is:verified` |
| `-is:nullcast` | Conjunction required | 프로모션 게시물을 제외(반드시 부정형으로 사용) | `"mobile games" -is:nullcast` |
***
## 콘텐츠 유형 연산자
| Operator | Type | Summary | Example |
| :--------------- | :------------------- | :----------------------------- | :----------------------------------- |
| `has:hashtags` | Conjunction required | 해시태그가 포함된 게시물을 매칭 | `from:XDevelopers -has:hashtags` |
| `has:cashtags` | Conjunction required | 캐시태그가 포함된 게시물을 매칭 | `#stonks has:cashtags` |
| `has:links` | Conjunction required | 링크가 포함된 게시물을 매칭 | `from:XDevelopers has:links` |
| `has:mentions` | Conjunction required | 멘션이 포함된 게시물을 매칭 | `#nowplaying has:mentions` |
| `has:media` | Conjunction required | 미디어(사진, GIF, 동영상)가 포함된 게시물을 매칭 | `(kittens OR puppies) has:media` |
| `has:images` | Conjunction required | 이미지가 포함된 게시물을 매칭 | `#meme has:images` |
| `has:video_link` | Conjunction required | 네이티브 X 동영상이 포함된 게시물을 매칭 | `#icebucketchallenge has:video_link` |
| `has:geo` | Conjunction required | 지오로케이션 데이터가 포함된 게시물을 매칭 | `recommend #paris has:geo` |
***
## 샘플링 및 언어 연산자
| Operator | Type | Summary | Example |
| :-------- | :------------------- | :-------------------- | :------------------------------- |
| `sample:` | Conjunction required | 임의의 백분율 샘플(1-100)을 반환 | `#nowplaying @spotify sample:15` |
| `lang:` | Conjunction required | 특정 언어로 분류된 게시물을 매칭 | `recommend #paris lang:en` |
***
## 사용자 지표 연산자
| Operator | Type | Summary | Example |
| :----------------- | :--- | :----------------------------- | :---------------------------- |
| `min_followers:` | — | 지정된 팔로워 수 이상을 가진 사용자의 게시물을 매칭 | `min_followers:1000` |
| `followers_count:` | — | 팔로워 수가 지정 범위에 속하는 사용자의 게시물을 매칭 | `followers_count:1000..10000` |
| `tweets_count:` | — | 게시물 수가 지정 범위에 속하는 사용자의 게시물을 매칭 | `tweets_count:1000..10000` |
| `following_count:` | — | 팔로잉 수가 지정 범위에 속하는 사용자의 게시물을 매칭 | `following_count:1000..10000` |
| `listed_count:` | — | 지정된 수의 리스트에 포함된 사용자의 게시물을 매칭 | `listed_count:10..100` |
***
## 게시물 참조 연산자
| Operator | Type | Summary | Example |
| :---------------------- | :--- | :------------------------- | :----------------------------------------- |
| `in_reply_to_tweet_id:` | — | 특정 게시물에 대한 답글을 매칭 | `in_reply_to_tweet_id:1539382664746020864` |
| `retweets_of_tweet_id:` | — | 특정 게시물의 리포스트를 매칭 | `retweets_of_tweet_id:1539382664746020864` |
| `source:` | — | 특정 소스 애플리케이션에서 작성된 게시물을 매칭 | `source:"X for iPhone"` |
***
## 논리 연산자
| Operator | Summary | Example |
| :---------- | :-------------- | :------------------------- |
| `OR` | 표현식 사이의 논리 OR | `cat OR dog` |
| Space (AND) | 표현식 사이의 논리 AND | `cat dog` (둘 다 필요) |
| `()` | 복잡한 표현식을 위한 그룹화 | `(cat OR dog) -is:retweet` |
| `-` | 부정/제외 | `cat -grumpy` |
***
## 임베딩 연산자
**Enterprise 전용 — Embedding 티어 필요**
`embedding:` 및 `embedding_threshold:` 연산자는 Filtered Stream에 대한 Embedding 티어 액세스가 프로비저닝된 Enterprise 계정에서만 사용할 수 있습니다. 지원되지 않는 티어에서는 규칙 생성이 "unavailable operator" 오류로 거부됩니다. 활성화하려면 담당 계정 담당자에게 문의하세요.
이 연산자는 신경망 임베딩 모델을 사용하여 정확한 키워드 일치를 요구하는 대신 쿼리에 대한 *시맨틱 유사도*로 게시물을 매칭합니다.
| Operator | Type | Summary | Example |
| :------------------------- | :------------------- | :------------------------------------------------------------ | :--------------------------------------------------------------- |
| `embedding:"query"` | Standalone | 쿼리와 시맨틱적으로 유사한 게시물을 매칭합니다. 여러 단어로 된 쿼리는 따옴표로 묶어야 합니다. | `embedding:"climate change policy"` |
| `embedding_threshold:X.XX` | Conjunction required | 매칭을 위한 최소 코사인 유사도(0.0–1.0). 기본값은 `0.3`. 0.3–0.6 사이의 값을 사용하세요. | `embedding:"cryptocurrency regulation" embedding_threshold:0.45` |
### 주요 요구 사항 및 참고 사항
* `embedding_threshold:`는 규칙 내에서 **단독으로** 사용할 수 없습니다. `embedding:`(또는 다른 독립형 연산자)과 함께 사용하세요.
* `embedding:`을 **부정하지 마세요**(예: `-embedding:"..."`는 지원되지 않음).
* 짧은 키워드보다 길고 설명적인 자연어 쿼리가 더 나은 결과를 제공합니다.
* 임베딩 쿼리 처리는 비동기적입니다 — 새로 생성한 규칙은 매칭을 시작하기까지 몇 초가 걸릴 수 있습니다.
* 게시물이 임베딩 규칙으로 매칭되면, 전달되는 페이로드의 `matching_rules` 항목에 `embedding_similarity` 및 `embedding_threshold`가 포함됩니다([Matching Posts to Rules](/x-api/posts/filtered-stream/integrate/matching-returned-tweets) 참조).
**예시 규칙:**
* `embedding:"electric vehicle announcements" lang:en -is:retweet has:links`
* `embedding:"natural disaster relief" embedding_threshold:0.45 has:media`
* `embedding:"renewable energy" embedding_threshold:0.4 OR embedding:"solar power investment"`
***
## 지원되는 언어
`lang:` 연산자는 다음 BCP 47 언어 코드를 지원합니다:
| Language | Code | Language | Code | Language | Code |
| :------- | :--- | :------- | :--- | :------- | :------ |
| 암하라어 | `am` | 그리스어 | `el` | 포르투갈어 | `pt` |
| 아랍어 | `ar` | 구자라트어 | `gu` | 루마니아어 | `ro` |
| 아르메니아어 | `hy` | 히브리어 | `iw` | 러시아어 | `ru` |
| 바스크어 | `eu` | 힌디어 | `hi` | 세르비아어 | `sr` |
| 벵골어 | `bn` | 헝가리어 | `hu` | 중국어 간체 | `zh-CN` |
| 불가리아어 | `bg` | 인도네시아어 | `in` | 슬로바키아어 | `sk` |
| 카탈로니아어 | `ca` | 이탈리아어 | `it` | 슬로베니아어 | `sl` |
| 크로아티아어 | `hr` | 일본어 | `ja` | 스페인어 | `es` |
| 체코어 | `cs` | 칸나다어 | `kn` | 스웨덴어 | `sv` |
| 덴마크어 | `da` | 한국어 | `ko` | 타밀어 | `ta` |
| 네덜란드어 | `nl` | 라트비아어 | `lv` | 텔루구어 | `te` |
| 영어 | `en` | 리투아니아어 | `lt` | 태국어 | `th` |
| 에스토니아어 | `et` | 말라얄람어 | `ml` | 중국어 번체 | `zh-TW` |
| 핀란드어 | `fi` | 마라티어 | `mr` | 터키어 | `tr` |
| 프랑스어 | `fr` | 노르웨이어 | `no` | 우크라이나어 | `uk` |
| 독일어 | `de` | 페르시아어 | `fa` | 우르두어 | `ur` |
| 조지아어 | `ka` | 폴란드어 | `pl` | 베트남어 | `vi` |
***
## 다음 단계
규칙 구문과 모범 사례를 알아보세요
Filtered Stream 시작하기
스트리밍 연결 끊김을 처리하세요
# 암호화 기초
Source: https://docs.x.com/ko/xchat/cryptography-primer
구현 세부 사항 없이 X Chat의 종단 간 암호화를 뒷받침하는 ECDH, 공개 키 암호화, 디지털 서명 개념을 학습합니다.
이 기초 문서는 X Chat의 뒤에 있는 암호화 아이디어를 개념적 수준에서 설명합니다. 개발을 위해 이 정도의 깊이가 반드시 필요한 것은 아닙니다—[Chat XDK](/xchat/xchat-xdk)가 암호화, 복호화, 서명, 키 저장을 대신 수행합니다—하지만 앱을 설계하거나 동작을 디버그할 때 이러한 멘탈 모델이 도움이 됩니다.
구현할 준비가 되면 전체 안내를 위해 [시작하기](/xchat/getting-started)를, 개별 경로를 위해 사이드바의 [API 참조](/x-api/chat/get-chat-conversations)를 사용하세요.
**이 암호화를 직접 구현하지 않습니다.** Chat XDK가 처리합니다. 이 페이지는 이해를 위한 것이며 API 체크리스트가 아닙니다.
***
## 큰 그림
X Chat은 계층화된 암호화 시스템을 사용하며, 다음과 같이 동작합니다:
1. **메시지**는 **대화 키**로 암호화됩니다 (빠른 대칭 암호화)
2. **대화 키**는 각 참가자의 **신원 공개 키**로 암호화됩니다 (비대칭 키 교환)
3. **메시지는** **서명 키**로 **서명**되어 수신자가 누가 보냈는지, 그리고 변조되지 않았는지 검증할 수 있습니다
대칭 암호화는 대량의 메시지 트래픽에 효율적이며, 비대칭 암호화는 주로 대화 키를 **안전하게 배포**하는 데 사용됩니다.
```mermaid theme={null}
flowchart TB
subgraph "Message Encryption"
A[Your Message] --> B[Encrypt with Conversation Key]
B --> C[Encrypted Message]
end
subgraph "Key Distribution"
D[Conversation Key] --> E[Encrypt with Recipient's Public Key]
E --> F[Encrypted Key for Recipient]
end
subgraph "Authentication"
C --> G[Sign with Your Private Key]
G --> H[Signature]
end
```
제품 흐름상 X는 읽을 수 있는 메시지 내용이나 원시 대화 키가 아닌 **암호문과 키 봉투**를 전송합니다. 앱은 암호화에 Chat XDK를, 키 등록 및 이 암호화된 페이로드의 송수신에는 [Chat API](/xchat/introduction)(Python/TypeScript의 XDK 또는 HTTPS 사용)를 사용합니다. 이러한 구성 요소가 어떻게 조합되는지는 [시작하기](/xchat/getting-started)를 참조하세요.
***
## 키 유형 설명
X Chat은 각각 특정한 목적을 가진 세 가지 유형의 키 재료를 사용합니다.
### 1. 신원 키페어
**용도:** 사용자 간에 대화 키를 안전하게 교환
| 구성 요소 | 설명 |
| :---------- | :--------------------------------------- |
| **신원 공개 키** | 다른 사람과 공유되며, 대화 키를 사용자에게 *암호화*하는 데 사용됩니다 |
| **신원 개인 키** | 비밀로 유지되며, 사용자에게 전송된 대화 키를 복호화하는 데 사용됩니다 |
누군가 사용자를 대화에 추가하면 사용자의 신원 공개 키를 사용하여 대화 키를 암호화합니다. 오직 사용자의 신원 개인 키만이 이를 복호화할 수 있습니다.
공개 키는 플랫폼의 **공개 키** API를 통해 등록 및 조회됩니다 (API 참조의 암호화 키 참조). 개인 키는 Chat XDK 내부에 유지됩니다 (예: [보안 키 백업](#보안-키-백업-분산-키-저장) 또는 신중하게 보호된 키 blob).
### 2. 서명 키페어
**용도:** 메시지를 사용자가 작성했음을 증명
| 구성 요소 | 설명 |
| :---------- | :--------------------------------- |
| **서명 공개 키** | 다른 사람과 공유되며, 사용자의 서명을 검증하는 데 사용됩니다 |
| **서명 개인 키** | 비밀로 유지되며, 사용자의 메시지에 서명하는 데 사용됩니다 |
메시지를 보내면 사용자의 서명 개인 키로 서명됩니다. 수신자는 사용자의 서명 공개 키(공개 키 API를 통해서도 게시됨)를 사용하여 검증합니다. Chat XDK는 메시지를 암호화하는 과정에서 서명하며, 발신자의 공개 키 자료를 제공하면 복호화 시 검증할 수 있습니다.
### 3. 대화 키
**용도:** 특정 대화 내에서 메시지(및 미디어)를 암호화 및 복호화
| 속성 | 설명 |
| :----------- | :------------------------------------ |
| **대칭** | 동일한 키로 암호화 및 복호화 |
| **대화별** | 각 대화마다 자체 키가 있음 |
| **참가자 간 공유** | 대화를 읽어야 하는 모든 참가자가 사본을 가짐 |
| **버전 관리됨** | 키는 교체될 수 있으며, 앱은 시간 경과에 따라 버전을 추적해야 함 |
대화 키는 대화가 설정될 때 또는 키가 교체될 때 생성됩니다. 각 참가자는 자신의 신원 공개 키로 만들어진 **암호화된 사본**을 받습니다. 자신의 사본을 한 번 복호화하면 **원시** 대화 키를 보관해 두고 빠른 메시지 (및 [미디어](/xchat/media)) 암호화에 사용합니다. 대화의 이러한 사본 설정은 Chat XDK와 대화 **키** 엔드포인트를 함께 사용하여 수행되며, [시작하기](/xchat/getting-started#4-set-up-conversation-keys)에서 자세히 다룹니다.
***
## 암호화가 개념적으로 작동하는 방식
### 메시지 보내기
"Hello, how are you?"라고 입력합니다.
앱은 이 채팅의 원시 대화 키(설정 또는 이전 키 배포 이벤트로부터)를 올바른 키 버전으로 사용합니다.
Chat XDK가 대화 키로 메시지를 암호화합니다. 결과는 해당 키 없이는 쓸모없는 암호문입니다.
Chat XDK가 사용자의 서명 개인 키로 암호화된 페이로드에 서명하여, 사용자가 이 정확한 내용을 작성했음을 증명합니다.
앱은 암호화된 페이로드와 서명을 Chat API의 **메시지 전송** 엔드포인트를 통해 X로 보냅니다. X는 평문으로 읽을 수 없는 바이트를 저장하고 전달합니다.
### 메시지 받기
앱은 [웹훅 또는 활동 스트림](/xchat/real-time-events)을 통해, 또는 이력을 위한 대화 **이벤트**를 읽어 X로부터 암호문을 수신합니다.
캐시된 원시 키를 사용하거나, 이것이 신규이거나 교체된 경우 키 배포(키 변경) 이벤트에서 사본을 복호화하여 획득합니다.
Chat XDK가 발신자의 서명 공개 키(및 관련 신원 바인딩)를 사용하여 서명을 확인하므로, 누가 보냈고 수정되지 않았음을 알 수 있습니다.
Chat XDK가 대화 키로 복호화합니다. 이제 "Hello, how are you?"를 읽을 수 있습니다.
암호화, 전송, 수신, 복호화 구현은 [시작하기](/xchat/getting-started)와 [Chat XDK](/xchat/xchat-xdk) 참조에 있습니다.
***
## 키 배포 설명
종단 간 암호화의 핵심 과제는 **키 배포**입니다. 즉, X(또는 관찰자)가 해당 키를 평문으로 볼 수 **없도록** 참가자가 어떻게 대화 키를 얻는가입니다.
### 초기 키 설정
메시지 전달을 위해 대화가 준비될 때:
1. 임의의 대화 키가 (Chat XDK 내에서) 생성됩니다
2. **각 참가자**에 대해 해당 키는 참가자의 **신원 공개 키**로 암호화됩니다
3. 이 암호화된 사본은 X의 Chat API를 통해 저장 및 전송됩니다
4. 각 참가자는 (Chat XDK 내에서) 자신의 신원 개인 키로 **자신의** 사본을 복호화합니다
X는 원시 대화 키가 아닌 **래핑된** 사본만 처리합니다.
### 키 변경 이벤트
대화 키가 교체되면(예: 멤버십이 변경될 때) 참가자는 각 멤버에 대한 새로운 암호화된 사본과 함께 **키 변경** 이벤트를 수신합니다.
앱은 다음을 수행해야 합니다:
1. 실시간 이벤트 또는 대화 이력에서 키 변경 자료를 감지
2. 새 대화 키(및 버전)를 복호화하고 저장
3. 이후 전송에는 최신 버전을 사용
[시작하기](/xchat/getting-started#6-receive-and-decrypt)와 [실시간 이벤트](/xchat/real-time-events)는 이러한 이벤트가 실제로 어디에 나타나는지 설명합니다.
***
## 보안 키 백업: 분산 키 저장
**개인** 신원 및 서명 키는 신중하게 저장되어야 합니다. X Chat에는 **보안 키 백업** 시스템(Juicebox로 구현됨)이 포함되어 있어, 어떤 단일 서버에도 전체 비밀을 제공하지 않고도 여러 기기에서 패스코드로 키를 복구할 수 있습니다.
### 전통적인 키 저장의 문제
| 접근 방식 | 문제 |
| :------------- | :----------------------------- |
| 기기에만 저장 | 기기 분실 = 키 분실 = 메시지 이력 접근 상실 |
| 일반 클라우드 백업에 저장 | 공급자가 키 자료에 접근할 수 있음 |
| 긴 키를 기억 | 사람은 엔트로피가 높은 키를 안정적으로 기억할 수 없음 |
### 보안 키 백업의 해결 방식
보안 키 백업은 **비밀 공유**와 **패스코드 보호**를 결합합니다:
1. 개인 키는 **여러 조각으로 나뉩니다**
2. 조각은 **독립적인 realm**(별도의 서버)에 보관됩니다
3. **어떤 단일 realm**도 혼자서 키를 재구성할 충분한 정보를 갖지 않습니다
4. 복구에는 사용자의 **패스코드**와 **충분한 realm**의 협력이 필요합니다
5. 잘못된 패스코드는 추측을 늦추기 위해 **속도 제한**됩니다
```mermaid theme={null}
flowchart LR
A[Your Private Keys] --> B[Split into Shares]
B --> C[Realm 1 Share A]
B --> D[Realm 2 Share B]
B --> E[Realm 3 Share C]
subgraph Recovery
F[Your Passcode + Multiple Realms] --> G[Reconstruct Keys]
end
```
단일 주체가 전체 비밀을 보유하지 않고도 복구 가능성(새 기기 + 패스코드)을 얻을 수 있습니다.
일반적인 경로에서는 키 백업 서버를 직접 구성하지 않습니다. Chat XDK에는 백업 클라이언트가 포함되어 있으며, realm 구성은 공개 키 레코드의 \*\*`juicebox_config`\*\*로 X API에서 반환됩니다 (이 필드 이름은 기반 구현인 Juicebox에서 따온 것입니다). 최초 패스코드 저장과 이후 잠금 해제는 Chat XDK 호출입니다—시작하기의 [기존 키로 초기화](/xchat/getting-started#2-initialize-the-chat-xdk-with-existing-keys) 및 [키 생성 및 등록](/xchat/getting-started#3-create-and-register-keys-first-time-setup)을 참조하세요. 일부 앱(특히 서버와 봇)은 보안 키 백업 대신 내보낸 키 blob을 사용합니다. 그 자료는 비밀번호처럼 보호하세요.
***
## 서명 설명
모든 X Chat 메시지에는 다음을 지원하는 **디지털 서명**이 포함됩니다:
1. **진위성** — 발신자의 서명 개인 키로 생성되었음
2. **무결성** — 서명 후에 암호화된 내용이 수정되지 않았음
### 서명이 개념적으로 작동하는 방식
| 동작 | 사용된 키 | 결과 |
| :----- | :----------- | :---------------------- |
| **서명** | 발신자의 서명 개인 키 | 이 정확한 암호화된 메시지에 바인딩된 서명 |
| **검증** | 발신자의 서명 공개 키 | 서명이 메시지 및 키와 일치함을 확인 |
서명된 자료의 무엇이든 변경되면 검증이 실패합니다. 오직 서명 개인 키를 가진 사람만이 해당 키에 대한 유효한 서명을 생성할 수 있습니다.
### 앱에서
Chat XDK는 발신 메시지를 암호화할 때 서명하고, 수신 메시지를 복호화할 때 발신자의 공개 키 자료(공개 키 API에서 가져옴)로 검증합니다. 검증은 **기본적으로 필수**입니다: 명시적으로 검사를 비활성화(권장하지 않음)하지 않는 한 SDK는 검증되지 않은 서명 이벤트를 거부합니다. 세부 사항은 [Chat XDK](/xchat/xchat-xdk) 참조에 있습니다.
### 서명된 상태 변경 (action signatures)
메시지만 서명되는 자료가 아닙니다. 대화 상태를 변경하는 모든 호출(대화 키 추가 또는 교체, 그룹 생성, 멤버 추가)에는 하나 이상의 **action signatures**가 포함되어야 합니다: 발신자는 변경 사항이 정확히 무엇을 하는지 설명하는 페이로드에 서명하고(키 변경의 경우 이 페이로드에는 새 대화 키 자체가 포함됨), API는 서명이 누락되거나 잘못된 형식이면 요청을 거부합니다.
서버는 평문 대화 키를 보유하지 않으므로 키 변경의 서명을 암호학적으로 검사할 수 없습니다. 대신 서명된, 인코딩된 변경 설명이 받은 요청과 일치하는지 검증합니다. **암호학적** 검사는 가장자리에서 발생합니다: 각 수신자의 Chat XDK가 키 변경 이벤트를 복호화할 때 발신자의 서명 공개 키에 대해 서명을 검증합니다. Chat XDK의 `prepare` 메서드는 이러한 서명을 자동으로 생성합니다—그룹 생성 및 멤버 추가는 **두 개**(키 변경과 그룹 액션)를 반환하며, 둘 다 전송되어야 합니다.
서명은 이벤트 내용에 바인딩되며 불변입니다: 서명이 검증되지 않는 이벤트는 나중에 유효해질 수 없습니다. 처리 방법은 [문제 해결](/xchat/troubleshooting)을 참조하세요.
***
## 보안 속성
### X Chat이 방어하는 것
| 위협 | 보호 |
| :---------------------------- | :----------------------------- |
| **X가 메시지 본문을 읽는 것** | 콘텐츠는 X로 전송되기 전에 암호화됩니다 |
| **네트워크 도청자** | 전송 보안과 종단 간 암호화된 콘텐츠 |
| **메시지 변조** | 서명이 수정을 감지합니다 |
| **사소한 발신자 사칭** | 유효한 서명에는 발신자의 서명 개인 키가 필요합니다 |
| **단일 서버 키 도난 (보안 키 백업 사용 시)** | 조각이 realm 전체에 분산되고 패스코드로 보호됩니다 |
### X Chat이 방어하지 **않는** 것
| 위협 | 이유 |
| :---------- | :------------------------------------------------ |
| **손상된 기기** | 잠금 해제된 클라이언트에서 평문과 키가 노출될 수 있습니다 |
| **메타데이터** | X는 누가 누구에게 언제 메시지를 보냈는지 알 수 있습니다—메시지 텍스트는 알지 못합니다 |
| **순방향 비밀성** | 신원 키의 손상은 그 키로 래핑된 대화 키를 노출할 수 있습니다 |
| **손상 후 보안** | 키를 교체해도 이력을 다시 쓰지는 않습니다 |
***
## 용어집
| 용어 | 정의 |
| :--------------- | :---------------------------------------- |
| **대칭 암호화** | 동일한 키로 암호화 및 복호화 (메시지 및 미디어 스트림에 사용) |
| **비대칭 암호화** | 암호화와 복호화를 위한 서로 다른 키 (대화 키 래핑에 사용) |
| **공개 키** | 공유해도 안전; 누군가에게 *암호화*하거나 그들의 서명을 검증하는 데 사용 |
| **개인 키** | 비밀로 유지되어야 함; 복호화 또는 서명에 사용 |
| **키페어** | 연결된 공개 키와 개인 키 |
| **ECDH / ECIES** | 대화 키를 신원 키로 래핑할 때 사용되는 알고리즘 |
| **ECDSA** | 메시지 작성자 확인에 사용되는 서명 알고리즘 |
| **P-256** | X Chat에서 사용되는 타원 곡선 (secp256r1) |
| **대화 키** | 하나의 대화 참가자가 공유하는 대칭 키 (시간 경과에 따라 버전 관리됨) |
| **비밀 공유** | 재구성하기 위해 여러 조각이 필요하도록 비밀을 분할하는 것 |
| **Realm** | 키 자료의 한 조각을 보관하는 독립적인 보안 키 백업 서버 |
***
## 다음 단계
단계별로 키 구현, 전송, 수신
암호화 SDK 메서드 및 타입
제품 개요 및 아키텍처
암호화된 이벤트가 전달되는 방식
# Chat API 시작하기
Source: https://docs.x.com/ko/xchat/getting-started
Python, TypeScript, Go, Rust, C#, Java용 Chat XDK로 종단 간 암호화된 X Chat 메시징을 구축하는 단계별 튜토리얼입니다.
X에서 종단 간 암호화된 다이렉트 메시지를 주고받으세요: 키를 설정하고, 대화를 초기화하고, 메시지를 보내고, 수신 트래픽을 복호화합니다.
X Chat 앱은 두 가지 구성 요소를 함께 사용합니다:
| 구성 요소 | 역할 |
| :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
| **[Chat XDK](/xchat/xchat-xdk)** | 암호화, 복호화, 서명 및 개인 키 저장 (보안 키 백업 또는 키 blob) |
| **X API** | 공개 키, 대화 키, 메시지 및 이벤트—[Python](/xdks/python/overview) 또는 [TypeScript](/xdks/typescript/overview) XDK를 통해서나, 사용자 액세스 토큰을 사용한 HTTPS로 제공 |
**사전 요구 사항**
* [개발자 계정](https://developer.x.com/en/portal/petition/essential/basic-info) 및 OAuth 2.0으로 구성된 앱
* `dm.read`, `dm.write`, `tweet.read`, `users.read`가 포함된 사용자 액세스 토큰
***
## 1. 종속성 설치
```bash theme={null}
pip install chatxdk xdk
```
PyPI 패키지는 `chatxdk`이며, `chat_xdk`로 임포트합니다. Python 3.10+ 필요.
```bash theme={null}
npm install @xdevplatform/chat-xdk @xdevplatform/xdk
npm install juicebox-sdk # optional peer dependency — required for setup()/unlock() secure key backup
```
컴파일된 WASM 엔진이 `@xdevplatform/chat-xdk`에 포함되어 있어 빌드 단계가 없습니다. Node.js 18+ 필요.
```toml theme={null}
[dependencies]
# chat-xdk-core is not yet on crates.io — use the git dependency
chat-xdk-core = { git = "https://github.com/xdevplatform/chat-xdk", tag = "v0.2.1" }
reqwest = { version = "0.12", features = ["blocking", "json"] }
serde_json = "1"
base64 = "0.22"
uuid = { version = "1", features = ["v4"] }
# Required until thrift 0.24 is released on crates.io
[patch.crates-io]
thrift = { git = "https://github.com/apache/thrift.git", rev = "deb36fa409849de45973b04ffc3ce49d277ca90a" }
```
```bash theme={null}
go get github.com/xdevplatform/chat-xdk/go/chatxdk
```
미리 컴파일된 정적 라이브러리가 포함되어 있습니다 (macOS arm64/amd64, Linux amd64 glibc/musl). C 컴파일러는 필요하지만 Rust는 필요 없습니다. Go 1.21+ 필요.
```bash theme={null}
dotnet add package XDevPlatform.ChatXdk
```
패키지는 자체 완결형입니다. macOS (arm64, x64), Linux (x64), Windows (x64)용 네이티브 라이브러리가 포함되어 있습니다. .NET 8+ 필요.
```xml theme={null}
com.xchatxdk0.2.1
```
Maven Central에서 제공됩니다. jar에 macOS (arm64, x64), Linux (x64), Windows (x64)용 네이티브 라이브러리가 번들되어 있어 `jna.library.path` 설정이 필요 없습니다. `com.x.chatxdk`에서 임포트하세요. JDK 17+ 필요.
**사용자** OAuth 2.0 액세스 토큰으로 API 클라이언트를 생성합니다:
```python theme={null}
from xdk import Client
client = Client(access_token="YOUR_OAUTH2_USER_TOKEN")
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
const client = new Client({ accessToken: 'YOUR_OAUTH2_USER_TOKEN' });
```
```rust theme={null}
let access_token = std::env::var("X_ACCESS_TOKEN")?;
let http = reqwest::blocking::Client::new();
let auth = format!("Bearer {access_token}");
```
```go theme={null}
accessToken := os.Getenv("X_ACCESS_TOKEN")
httpClient := &http.Client{Timeout: 30 * time.Second}
```
```csharp theme={null}
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", Environment.GetEnvironmentVariable("X_ACCESS_TOKEN"));
```
```java theme={null}
String accessToken = System.getenv("X_ACCESS_TOKEN");
HttpClient http = HttpClient.newHttpClient();
```
***
## 2. 기존 키로 Chat XDK 초기화
이 단계는 **이미 보유한 키를 로드**합니다—이 신원이 이전에 최초 설정을 완료한 경우 사용하세요:
* **보안 키 백업:** 공개 키 레코드의 `juicebox_config`로 SDK를 구성한 다음, 패스코드로 `unlock`하여 개인 키를 복구합니다 (예: 새 기기에서).
* **키 blob:** 이전에 `export_keys`로 내보낸 blob으로 `import_keys`를 호출합니다.
그런 다음 등록된 공개 키 버전(레코드의 `public_key_version`)을 설정합니다.
**처음 설정하시나요?** 동일한 방식으로 SDK를 구성하되 `unlock`/`import_keys`는 건너뛰고, [3단계](#3-키-생성-및-등록-최초-설정)로 계속 진행하여 키를 생성, 백업, 등록하세요.
```python theme={null}
import json
from chat_xdk import Chat
resp = client.chat.get_user_public_keys(
"YOUR_USER_ID",
public_key_fields=[
"public_key_version", "public_key", "signing_public_key",
"identity_public_key_signature", "juicebox_config",
],
)
record = resp.data[0]
signing_key_version = str(record["public_key_version"])
chat = Chat(json.dumps(record["juicebox_config"]))
chat.unlock("YOUR_PASSCODE") # recovers keys stored by setup() during first-time setup (step 3)
chat.set_key_version(signing_key_version)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const resp = await client.chat.getUserPublicKeys('YOUR_USER_ID', {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key',
'identity_public_key_signature', 'juicebox_config',
],
});
const record = resp.data[0];
const signingKeyVersion = String(record.public_key_version);
const chat = await createChat({
juiceboxConfig: JSON.stringify(record.juicebox_config),
getAuthToken: async (realmId) => getRealmTokenFromYourBackend(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(signingKeyVersion);
```
```rust theme={null}
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use chat_xdk_core::ChatCore;
let mut chat = ChatCore::new();
let blob = B64.decode(std::env::var("PRIVATE_KEYS_B64")?)?;
let signing_key_version = std::env::var("SIGNING_KEY_VERSION").unwrap_or_else(|_| "1".into());
chat.import_keys(&blob)?;
chat.set_key_version(&signing_key_version);
```
```go theme={null}
import "github.com/xdevplatform/chat-xdk/go/chatxdk"
chat := chatxdk.New()
defer chat.Close()
blob, err := chatxdk.Base64ToBytes(os.Getenv("PRIVATE_KEYS_B64"))
if err != nil {
log.Fatal(err)
}
if err := chat.ImportKeys(blob); err != nil {
log.Fatal(err)
}
signingKeyVersion := os.Getenv("SIGNING_KEY_VERSION")
if signingKeyVersion == "" {
signingKeyVersion = "1"
}
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
using ChatXdk;
using var chat = new Chat();
var signingKeyVersion = Environment.GetEnvironmentVariable("SIGNING_KEY_VERSION") ?? "1";
chat.ImportKeys(Convert.FromBase64String(
Environment.GetEnvironmentVariable("PRIVATE_KEYS_B64")!));
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
import com.x.chatxdk.Chat;
String signingKeyVersion = Optional.ofNullable(System.getenv("SIGNING_KEY_VERSION")).orElse("1");
try (Chat chat = new Chat()) {
chat.importKeys(Base64.getDecoder().decode(System.getenv("PRIVATE_KEYS_B64")));
chat.setKeyVersion(signingKeyVersion);
}
```
서버 및 봇 샘플에서는 종종 **키 blob**(`export_keys` / `import_keys`)을 사용합니다. 클라이언트 앱에서는 종종 **보안 키 백업**(패스코드로 `setup` / `unlock`)을 사용합니다. 두 경로 모두에 대해 [Chat XDK](/xchat/xchat-xdk) 참조를 확인하세요.
**직접 만든 키를 가져오시나요?** `import_keys`는 Chat XDK의 `export_keys`가 생성한 불투명 blob만 허용합니다—이는 전체 키 상태의 버전 관리된 비공개 직렬화이며, 원시 또는 PEM으로 인코딩된 P-256 키가 아닙니다. 이 blob은 직접 구성할 수 없습니다: `generate_keypairs`([3단계](#3-키-생성-및-등록-최초-설정))로 키를 생성하고, blob을 한 번 내보내 base64로 인코딩하여 저장하세요. 수작업으로 만들거나 수정한 blob은 가져오기에 실패합니다.
***
## 3. 키 생성 및 등록 (최초 설정)
[2단계](#2-기존-키로-chat-xdk-초기화)에서 기존 키를 로드했다면 이 단계를 건너뛰세요. 그렇지 않은 경우, 새 신원에 대한 일회성 설정은 **세 가지 작업**을 수행합니다:
1. **키페어 생성** — `generate_keypairs`가 신원 및 서명 키페어를 생성합니다.
2. **공개 키 등록** — 다른 사람이 사용자에게 암호화하고 서명을 검증할 수 있도록 등록 페이로드를 공개 키 추가 엔드포인트에 POST합니다.
3. **개인 키 저장** — 패스코드로 `setup`하면 보안 키 백업에 기록됩니다(클라이언트). 또는 `export_keys`가 안전하게 저장할 키 blob을 반환합니다(서버 및 봇).
```python theme={null}
from xdk.chat.models import AddUserPublicKeyRequest
registration = chat.generate_keypairs()
pk = registration.public_key
client.chat.add_user_public_key(
"YOUR_USER_ID",
AddUserPublicKeyRequest(
public_key={
"identity_public_key_signature": pk.identity_public_key_signature,
"public_key": pk.public_key,
"public_key_fingerprint": pk.public_key_fingerprint,
"registration_method": pk.registration_method,
"signing_public_key": pk.signing_public_key,
"signing_public_key_signature": pk.signing_public_key_signature,
},
version=registration.version,
generate_version=registration.generate_version,
),
)
chat.setup("YOUR_PASSCODE")
chat.set_key_version(str(registration.version or signing_key_version))
```
```typescript theme={null}
const registration = chat.generateKeypairs();
const pk = registration.publicKey;
await client.chat.addUserPublicKey('YOUR_USER_ID', {
public_key: {
identity_public_key_signature: pk.identityPublicKeySignature,
public_key: pk.publicKey,
public_key_fingerprint: pk.publicKeyFingerprint,
registration_method: pk.registrationMethod,
signing_public_key: pk.signingPublicKey,
signing_public_key_signature: pk.signingPublicKeySignature,
},
version: registration.version,
generate_version: registration.generateVersion,
});
await chat.setup('YOUR_PASSCODE');
chat.setKeyVersion(String(registration.version ?? signingKeyVersion));
```
```rust theme={null}
let registration = chat.generate_keypairs()?;
let body = serde_json::to_value(®istration)?;
let resp = http
.post(format!("https://api.x.com/2/users/{user_id}/public_keys"))
.header("Authorization", &auth)
.json(&body)
.send()?;
if !resp.status().is_success() {
anyhow::bail!("register keys: {}", resp.text()?);
}
let _blob = chat.export_keys()?; // store securely
```
```go theme={null}
registration, err := chat.GenerateKeypairs()
if err != nil {
log.Fatal(err)
}
regJSON, _ := json.Marshal(registration)
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/users/"+userID+"/public_keys",
bytes.NewReader(regJSON))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
privateKeysB64, _ := chat.ExportKeys() // store securely
_ = privateKeysB64
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
var registration = chat.GenerateKeypairs();
var regJson = System.Text.Json.JsonSerializer.Serialize(registration);
using var content = new StringContent(regJson, Encoding.UTF8, "application/json");
using var regResp = await http.PostAsync(
$"https://api.x.com/2/users/{Uri.EscapeDataString(userId)}/public_keys", content);
regResp.EnsureSuccessStatusCode();
var blob = chat.ExportKeys(); // store securely
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
var registration = chat.generateKeypairs();
String regJson = new ObjectMapper().writeValueAsString(registration);
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/users/" + userId + "/public_keys"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(regJson))
.build();
HttpResponse regResp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (regResp.statusCode() >= 300) {
throw new RuntimeException("register keys: " + regResp.body());
}
byte[] blob = chat.exportKeys(); // store securely
chat.setKeyVersion(signingKeyVersion);
```
보안 키 백업에 강력한 패스코드를 사용하세요. 패스코드나 보호되지 않은 키 blob을 분실하면 이전 메시지를 복호화할 수 없게 될 수 있습니다.
***
## 4. 대화 키 설정
사용자 ID, 서명 키 버전, 그리고 모든 참가자의 신원 공개 키와 함께 \*\*`prepare_conversation_key_change`\*\*를 호출합니다. 한 번의 호출로 새로운 대화 키가 생성되고, 각 참가자에 대해 암호화되며, 변경 사항이 서명됩니다. 결과를 **대화 키 추가** 엔드포인트(`POST /2/chat/conversations/{id}/keys`)에 POST합니다—본문에는 `conversation_key_version`, `conversation_participant_keys`(SDK `encrypted_key` → API `encrypted_conversation_key`), 그리고 **`action_signatures`**(필수; 없으면 API가 호출을 거부함)가 필요합니다. 전송에 사용할 **원시** 대화 키를 보관하세요.
응답은 표준 대화 ID(`data.conversation_id`—1:1의 경우 하이픈으로 연결된 쌍, 또는 그룹의 경우 g- 접두사가 붙은 ID)와 키 변경의 `data.sequence_id`를 반환합니다. 클라이언트 측에서 재구성하는 대신 이후 요청에 반환된 ID를 사용하세요. 같은 호출은 나중에 키를 **교체**하기도 합니다: 기존 대화 ID를 `prepare_conversation_key_change`에 전달하고 최신 키 버전과 함께 POST합니다. 대화 키가 노출되었다고 의심될 때 교체하세요—교체는 **향후** 메시지만 보호합니다. 이전 키 버전으로 암호화된 메시지는 그 버전을 보유한 사람이라면 누구나 계속 읽을 수 있습니다.
**래핑하기 전에 가져온 키를 검증하세요.** `prepare_conversation_key_change`는 새 대화 키를 전달된 공개 키로 암호화합니다. 대체된 신원 키가 대화 키를 받지 못하도록, 각 가져온 레코드를 먼저 `verify_key_binding(identity, signing, signature)`로 확인하세요—공개 키 API의 `public_key`, `signing_public_key`, `identity_public_key_signature` 필드를 전달합니다.
```python theme={null}
def public_key_input(user_id: str) -> dict:
r = client.chat.get_user_public_keys(
user_id, public_key_fields=["public_key_version", "public_key"]
).data[0]
return {"user_id": user_id, "public_key": r["public_key"], "key_version": r["public_key_version"]}
prepared = chat.prepare_conversation_key_change(
"YOUR_USER_ID",
signing_key_version,
[public_key_input("YOUR_USER_ID"), public_key_input("RECIPIENT_USER_ID")],
# conversation_id=None for a new 1:1; pass the id to rotate later
)
resp = client.chat.add_conversation_keys(
"RECIPIENT_USER_ID",
{
"conversation_key_version": prepared["conversation_key_version"],
"conversation_participant_keys": [
{
"user_id": pk["user_id"],
"encrypted_conversation_key": pk["encrypted_key"],
"public_key_version": pk["public_key_version"],
}
for pk in prepared["participant_keys"]
],
"action_signatures": [
{
"message_id": sig["message_id"],
"encoded_message_event_detail": sig["encoded_message_event_detail"],
"message_event_signature": {
"signature": sig["signature"],
"public_key_version": sig["public_key_version"],
"signature_version": sig["signature_version"],
},
}
for sig in prepared["action_signatures"]
],
},
)
conversation_id = resp.data["conversation_id"] # canonical id for later requests
sequence_id = resp.data["sequence_id"]
conv_key = prepared["conversation_key"]
conv_key_version = prepared["conversation_key_version"]
```
```typescript theme={null}
async function publicKeyInput(userId: string) {
const r = (await client.chat.getUserPublicKeys(userId, {
publicKeyFields: ['public_key_version', 'public_key'],
})).data[0];
return { userId, publicKey: r.public_key, keyVersion: r.public_key_version };
}
// Omit conversationId for a new 1:1; pass the id to rotate later
const prepared = chat.prepareConversationKeyChange({
senderId: 'YOUR_USER_ID',
signingKeyVersion,
publicKeys: [
await publicKeyInput('YOUR_USER_ID'),
await publicKeyInput('RECIPIENT_USER_ID'),
],
});
const resp = await client.chat.addConversationKeys('RECIPIENT_USER_ID', {
conversation_key_version: prepared.conversationKeyVersion,
conversation_participant_keys: prepared.participantKeys.map((pk) => ({
user_id: pk.userId,
encrypted_conversation_key: pk.encryptedKey,
public_key_version: pk.publicKeyVersion,
})),
action_signatures: prepared.actionSignatures.map((sig) => ({
message_id: sig.messageId,
encoded_message_event_detail: sig.encodedMessageEventDetail,
message_event_signature: {
signature: sig.signature,
public_key_version: sig.publicKeyVersion,
signature_version: sig.signatureVersion,
},
})),
});
const conversationId = resp.data.conversation_id; // canonical id for later requests
const sequenceId = resp.data.sequence_id;
const convKey = prepared.conversationKey;
const convKeyVersion = prepared.conversationKeyVersion;
```
```rust theme={null}
// public_key_inputs: Vec from GET public keys
// (user_id, public_key, key_version ← public_key_version)
// new 1:1; set params.conversation_id = Some(id) to rotate later
let prepared = chat.prepare_conversation_key_change(
ConversationKeyChangeParams::new(&sender_id, &signing_key_version, public_key_inputs),
)?;
let participant_keys: Vec<_> = prepared
.participant_keys
.iter()
.map(|pk| {
serde_json::json!({
"user_id": pk.user_id,
"encrypted_conversation_key": pk.encrypted_key,
"public_key_version": pk.public_key_version,
})
})
.collect();
let action_signatures: Vec<_> = prepared
.action_signatures
.iter()
.map(|sig| {
serde_json::json!({
"message_id": sig.message_id,
"encoded_message_event_detail": sig.encoded_message_event_detail,
"message_event_signature": {
"signature": sig.signature,
"public_key_version": sig.public_key_version,
"signature_version": sig.signature_version,
},
})
})
.collect();
let body = serde_json::json!({
"conversation_key_version": prepared.conversation_key_version,
"conversation_participant_keys": participant_keys,
"action_signatures": action_signatures,
});
let resp: serde_json::Value = http
.post(format!("https://api.x.com/2/chat/conversations/{recipient_id}/keys"))
.header("Authorization", &auth)
.json(&body)
.send()?
.json()?;
// Canonical id for later requests
let conversation_id = resp["data"]["conversation_id"].as_str().unwrap().to_string();
// conversation_key is Option; encrypt_message wants owned bytes
let conv_key = prepared.conversation_key.expect("key present").to_bytes();
let conv_key_version = prepared.conversation_key_version;
```
```go theme={null}
// KeyVersion comes from the public_key_version field on each record
prepared, err := chat.PrepareConversationKeyChange(chatxdk.ConversationKeyChangeParams{
SenderID: myUserID,
SigningKeyVersion: signingKeyVersion,
PublicKeys: []chatxdk.PublicKeyInput{
{UserID: myUserID, PublicKey: myIdentityPubB64, KeyVersion: myKeyVersion},
{UserID: recipientID, PublicKey: theirIdentityPubB64, KeyVersion: theirKeyVersion},
},
// ConversationID empty for a new 1:1; pass the id to rotate later
})
var parts []map[string]string
for _, pk := range prepared.ParticipantKeys {
parts = append(parts, map[string]string{
"user_id": pk.UserID,
"encrypted_conversation_key": pk.EncryptedKey,
"public_key_version": pk.PublicKeyVersion,
})
}
var sigs []map[string]any
for _, sig := range prepared.ActionSignatures {
sigs = append(sigs, map[string]any{
"message_id": sig.MessageID,
"encoded_message_event_detail": sig.EncodedMessageEventDetail,
"message_event_signature": map[string]string{
"signature": sig.Signature,
"public_key_version": sig.PublicKeyVersion,
"signature_version": sig.SignatureVersion,
},
})
}
body, _ := json.Marshal(map[string]any{
"conversation_key_version": prepared.ConversationKeyVersion,
"conversation_participant_keys": parts,
"action_signatures": sigs,
})
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/chat/conversations/"+recipientID+"/keys",
bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
// Response data.conversation_id is the canonical id for later requests
// prepared.ConversationKey feeds EncryptMessage
_ = resp
```
```csharp theme={null}
// KeyVersion comes from the public_key_version field on each record
var prepared = chat.PrepareConversationKeyChange(new ConversationKeyChangeParams {
SenderId = myUserId,
SigningKeyVersion = signingKeyVersion,
PublicKeys = new[] {
new PublicKeyInput { UserId = myUserId, PublicKey = myPk, KeyVersion = myVer },
new PublicKeyInput { UserId = recipientId, PublicKey = theirPk, KeyVersion = theirVer },
},
}); // ConversationId null for a new 1:1; pass the id to rotate later
var keysBody = new {
conversation_key_version = prepared.ConversationKeyVersion,
conversation_participant_keys = prepared.ParticipantKeys.Select(pk => new {
user_id = pk.UserId,
encrypted_conversation_key = pk.EncryptedKey,
public_key_version = pk.PublicKeyVersion,
}),
action_signatures = prepared.ActionSignatures.Select(sig => new {
message_id = sig.MessageId,
encoded_message_event_detail = sig.EncodedMessageEventDetail,
message_event_signature = new {
signature = sig.Signature,
public_key_version = sig.PublicKeyVersion,
signature_version = sig.SignatureVersion,
},
}),
};
var json = System.Text.Json.JsonSerializer.Serialize(keysBody);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await http.PostAsync(
$"https://api.x.com/2/chat/conversations/{Uri.EscapeDataString(recipientId)}/keys",
content);
resp.EnsureSuccessStatusCode();
var data = System.Text.Json.JsonDocument.Parse(await resp.Content.ReadAsStringAsync())
.RootElement.GetProperty("data");
string conversationId = data.GetProperty("conversation_id").GetString()!; // canonical id
byte[] convKey = prepared.ConversationKey!;
string convKeyVersion = prepared.ConversationKeyVersion;
```
```java theme={null}
// keyVersion comes from the public_key_version field on each record
PublicKeyInput mine = new PublicKeyInput();
mine.userId = myUserId; mine.publicKey = myIdentityPubB64; mine.keyVersion = myKeyVersion;
PublicKeyInput theirs = new PublicKeyInput();
theirs.userId = recipientId; theirs.publicKey = theirIdentityPubB64; theirs.keyVersion = theirKeyVersion;
ConversationKeyChangeParams keyParams = new ConversationKeyChangeParams();
keyParams.senderId = myUserId;
keyParams.signingKeyVersion = signingKeyVersion;
keyParams.publicKeys = List.of(mine, theirs);
// keyParams.conversationId null for a new 1:1; set the id to rotate later
PreparedConversationChange prepared = chat.prepareConversationKeyChange(keyParams);
List> parts = new ArrayList<>();
for (var pk : prepared.participantKeys) {
parts.add(Map.of(
"user_id", pk.userId,
"encrypted_conversation_key", pk.encryptedKey,
"public_key_version", pk.publicKeyVersion));
}
List> sigs = new ArrayList<>();
for (var sig : prepared.actionSignatures) {
sigs.add(Map.of(
"message_id", sig.messageId,
"encoded_message_event_detail", sig.encodedMessageEventDetail,
"message_event_signature", Map.of(
"signature", sig.signature,
"public_key_version", sig.publicKeyVersion,
"signature_version", sig.signatureVersion)));
}
ObjectMapper mapper = new ObjectMapper();
String body = mapper.writeValueAsString(Map.of(
"conversation_key_version", prepared.conversationKeyVersion,
"conversation_participant_keys", parts,
"action_signatures", sigs));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/conversations/" + recipientId + "/keys"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString());
JsonNode data = mapper.readTree(resp.body()).path("data");
String conversationId = data.path("conversation_id").asText(); // canonical id
byte[] convKey = prepared.conversationKey;
String convKeyVersion = prepared.conversationKeyVersion;
```
***
## 5. 메시지 보내기
**원시** 대화 키 바이트로 암호화합니다. 전송 요청에서 다음과 같이 매핑합니다:
| Chat XDK 필드 | 요청 본문 필드 |
| :---------------------------------------------------------------------------- | :-------------------------------- |
| `encrypted_content` / `encryptedContent` / `EncryptedContent` | `encoded_message_create_event` |
| `encoded_event_signature` / `encodedEventSignature` / `EncodedEventSignature` | `encoded_message_event_signature` |
| 생성한 ID | `message_id` |
API가 요구할 때 URL 경로에 **하이픈으로 연결된** 대화 ID를 사용하세요(`:` → `-`). SDK 자체는 유연합니다: `encrypt_message`와 `encrypt_reply`는 보유하고 있는 어떤 형태의 ID든 허용합니다—이벤트의 `A:B`, 목록이나 URL 경로의 `A-B`(어떤 순서든), 또는 그저 수신자의 사용자 ID—그리고 서명 전에 정규화합니다. 그룹 ID(`g` 접두사)는 그대로 통과됩니다.
```python theme={null}
import uuid
from xdk.chat.models import SendMessageRequest
message_id = str(uuid.uuid4())
payload = chat.encrypt_message(
message_id,
"YOUR_USER_ID",
"CONVERSATION_ID",
conv_key,
"Hello!",
conv_key_version,
signing_key_version,
)
client.chat.send_message(
"RECIPIENT_USER_ID",
SendMessageRequest(
message_id=message_id,
encoded_message_create_event=payload.encrypted_content,
encoded_message_event_signature=payload.encoded_event_signature,
),
)
```
```typescript theme={null}
import { randomUUID } from 'crypto';
const messageId = randomUUID();
const payload = chat.encryptMessage({
messageId,
senderId: 'YOUR_USER_ID',
conversationId: 'CONVERSATION_ID',
conversationKey: convKey,
text: 'Hello!',
conversationKeyVersion: convKeyVersion,
signingKeyVersion,
});
await client.chat.sendMessage('RECIPIENT_USER_ID', {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
});
```
```rust theme={null}
use chat_xdk_core::EncryptMessageParams;
let message_id = uuid::Uuid::new_v4().to_string();
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id,
&sender_id,
&conversation_id,
conv_key,
"Hello!",
&conv_key_version,
&signing_key_version,
))?;
let body = serde_json::json!({
"message_id": message_id,
"encoded_message_create_event": payload.encrypted_content,
"encoded_message_event_signature": payload.encoded_event_signature,
});
let path_id = conversation_id.replace(':', "-");
http.post(format!("https://api.x.com/2/chat/conversations/{path_id}/messages"))
.header("Authorization", &auth)
.json(&body)
.send()?;
```
```go theme={null}
messageID := uuid.NewString()
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID,
SenderID: senderID,
ConversationID: conversationID,
ConversationKey: convKey,
Text: "Hello!",
ConversationKeyVersion: convKeyVersion,
SigningKeyVersion: signingKeyVersion,
})
body, _ := json.Marshal(map[string]string{
"message_id": messageID,
"encoded_message_create_event": payload.EncryptedContent,
"encoded_message_event_signature": payload.EncodedEventSignature,
})
pathID := strings.ReplaceAll(conversationID, ":", "-")
req, _ := http.NewRequest(http.MethodPost,
"https://api.x.com/2/chat/conversations/"+pathID+"/messages",
bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
_ = resp
```
```csharp theme={null}
var messageId = Guid.NewGuid().ToString();
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId,
SenderId = senderId,
ConversationId = conversationId,
ConversationKey = convKey,
Text = "Hello!",
ConversationKeyVersion = convKeyVersion,
SigningKeyVersion = signingKeyVersion,
});
var sendJson = System.Text.Json.JsonSerializer.Serialize(new Dictionary {
["message_id"] = messageId,
["encoded_message_create_event"] = payload.EncryptedContent,
["encoded_message_event_signature"] = payload.EncodedEventSignature,
});
using var content = new StringContent(sendJson, Encoding.UTF8, "application/json");
var pathId = conversationId.Replace(':', '-');
using var resp = await http.PostAsync(
$"https://api.x.com/2/chat/conversations/{Uri.EscapeDataString(pathId)}/messages",
content);
resp.EnsureSuccessStatusCode();
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = UUID.randomUUID().toString();
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = convKey;
params.text = "Hello!";
params.conversationKeyVersion = convKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
String pathId = conversationId.replace(':', '-');
String sendJson = new ObjectMapper().writeValueAsString(Map.of(
"message_id", params.messageId,
"encoded_message_create_event", payload.encryptedContent,
"encoded_message_event_signature", payload.encodedEventSignature));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/conversations/" + pathId + "/messages"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(sendJson))
.build();
http.send(req, HttpResponse.BodyHandlers.ofString());
```
***
## 6. 수신 및 복호화
실시간 트래픽에는 [웹훅 또는 활동 스트림](/xchat/real-time-events)을, 이력 조회에는 대화 **이벤트**의 페이지 처리를 사용하세요.
* 실시간 페이로드 필드: `encoded_event`, 선택적 `conversation_key_change_event`
* 이력: `GET /2/chat/conversations/{id}/events` — 모든 이벤트에 대해 \*\*`decrypt_events`\*\*와 `meta.conversation_key_events`를 함께 사용하는 것이 좋음
* 서명 검증을 위해 발신자의 공개 키를 복호화에 전달합니다 (API 필드를 `SigningKeyEntry`로 매핑; [Chat XDK](/xchat/xchat-xdk) 참조)
* JavaScript는 camelCase 이벤트 유형(`message`)을 사용합니다; 다른 언어는 `"Message"`와 JSON의 snake\_case 필드를 사용합니다
```python theme={null}
conversation_keys = {} # conversation_id -> { version: key_bytes }
def signing_keys_for(user_id: str) -> list[dict]:
resp = client.chat.get_user_public_keys(
user_id,
public_key_fields=[
"public_key_version", "public_key", "signing_public_key", "identity_public_key_signature",
],
)
return [
{
"user_id": user_id,
"public_key_version": r["public_key_version"],
"public_key": r["signing_public_key"],
"identity_public_key": r["public_key"],
"identity_public_key_signature": r["identity_public_key_signature"],
}
for r in resp.data
]
def handle_payload(payload: dict):
cid = payload["conversation_id"]
if payload.get("conversation_key_change_event"):
conversation_keys[cid] = chat.extract_conversation_keys(
[payload["conversation_key_change_event"]]
)["keys"]
event = chat.decrypt_event(
payload["encoded_event"],
conversation_keys.get(cid, {}),
signing_keys_for(payload["sender_id"]),
)
if event.get("type") == "Message" and event.get("content", {}).get("content_type") == "Text":
print(event["sender_id"], event["content"]["text"], event.get("verified"))
```
```typescript theme={null}
const conversationKeys = new Map>();
async function signingKeysFor(userId: string) {
const resp = await client.chat.getUserPublicKeys(userId, {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key', 'identity_public_key_signature',
],
});
return resp.data.map((r: {
public_key_version: string;
public_key: string;
signing_public_key: string;
identity_public_key_signature: string;
}) => ({
userId,
publicKeyVersion: r.public_key_version,
publicKey: r.signing_public_key,
identityPublicKey: r.public_key,
identityPublicKeySignature: r.identity_public_key_signature,
}));
}
async function handlePayload(payload: {
conversation_id: string;
encoded_event: string;
sender_id: string;
conversation_key_change_event?: string;
}) {
const cid = payload.conversation_id;
if (payload.conversation_key_change_event) {
conversationKeys.set(
cid,
chat.extractConversationKeys([payload.conversation_key_change_event]).keys,
);
}
const event = chat.decryptEvent(
payload.encoded_event,
conversationKeys.get(cid) ?? {},
await signingKeysFor(payload.sender_id),
);
if (event.type === 'message' && event.content?.contentType === 'text') {
console.log(event.senderId, event.content.text, event.verified);
}
}
```
```rust theme={null}
// Build Vec from GET /2/users/{id}/public_keys
// (public_key_version, public_key, signing_public_key, identity_public_key_signature)
if let Some(kc) = key_change_b64.as_deref() {
let extracted = chat.extract_conversation_keys(&[kc]);
conv_keys.extend(extracted.keys);
}
let event = chat.decrypt_event(&encoded_event, &conv_keys, &sender_signing_keys)?;
```
```go theme={null}
if keyChange != "" {
extracted, _ := chat.ExtractConversationKeys([]string{keyChange})
for v, k := range extracted.Keys {
convKeys[v] = k
}
}
event, err := chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys)
if err == nil && event.Type == "Message" {
fmt.Println(event.AsMessage().Text())
}
```
```csharp theme={null}
if (!string.IsNullOrEmpty(keyChangeB64))
{
var extracted = chat.ExtractConversationKeys(new[] { keyChangeB64 });
foreach (var kv in extracted.Keys)
convKeys[kv.Key] = kv.Value;
}
var evt = chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys);
if (evt.GetProperty("type").GetString() == "Message")
Console.WriteLine(evt.GetProperty("content").GetProperty("text").GetString());
```
```java theme={null}
if (keyChangeB64 != null && !keyChangeB64.isEmpty()) {
var extracted = chat.extractConversationKeys(List.of(keyChangeB64));
convKeys.putAll(extracted.keys);
}
JsonNode evt = chat.decryptEvent(encodedEvent, convKeys, senderSigningKeys);
if ("Message".equals(evt.path("type").asText())) {
System.out.println(evt.path("content").path("text").asText());
}
```
모든 언어에 대한 전체 폴링-응답 봇 예제: [chat-xdk/examples](https://github.com/xdevplatform/chat-xdk/tree/main/examples).
***
## 모범 사례
* 원시 대화 키와 발신자 공개 키를 캐시하고, 서명 검증 실패 시 갱신하세요
* `event_uuid`로 실시간 전달을 중복 제거하세요
* 페이지네이션이 완료될 때까지 이벤트 이력을 페이지 처리하여 키 변경 메타데이터를 놓치지 마세요
* 프로덕션에서 패스코드, 개인 키, 메시지 평문을 로그에 남기지 마세요
* 웹 앱에서는 OAuth 토큰(및 키 백업 realm 토큰 발급)을 서버에 유지하세요; 개인 키는 클라이언트 Chat XDK에만 보관하는 것이 좋습니다
***
## 다음 단계
모든 언어 바인딩의 메서드 및 타입
암호화된 이미지 및 파일 첨부
다자간 대화 및 메타데이터
웹훅 및 활동 전달
# 그룹 대화
Source: https://docs.x.com/ko/xchat/groups
공유 대화 키, 암호화된 제목, 멤버 관리, 서명된 메시지를 갖춘 다자간 X Chat 그룹 대화를 생성합니다.
그룹 채팅은 1:1 X Chat과 **동일한 암호화 모델**을 사용합니다: 멤버가 공유하는 하나의 **대화 키**를 각 멤버의 **신원 공개 키**로 래핑하고, Chat XDK가 메시지를 암호화하고 서명합니다. 달라지는 것은 **멤버십**, **대화를 생성하는 방식**, 그리고 종종 대화의 **암호화된 제목/아바타** 필드입니다.
1:1 흐름은 [시작하기](/xchat/getting-started)에 있습니다. 엔드포인트 세부 사항은 **API 참조 → 대화 및 메시지** 아래에 있습니다.
***
## 그룹과 1:1의 차이점
| 주제 | 1:1 | 그룹 |
| :---- | :--------------------- | :----------------------------------- |
| 식별 | 경로에서 종종 상대방 사용자 ID로 지정 | 대화 ID가 일반적으로 `g`로 시작 |
| 생성 | 사용자에 대한 키 + 메시징 | 그룹 생성 / 초기화 API, 그런 다음 키 |
| 참가자 | 나 + 상대방 한 명 | 여러 사용자; 멤버십이 변경 가능 |
| 메타데이터 | 최소 | 이름, 아바타 등은 **암호문**일 수 있음 (대화 키로 복호화) |
| 키 교체 | 덜 빈번 | 사람이 참여하거나 떠날 때 흔함 |
암호화는 여전히: 키와 페이로드에는 **Chat XDK**를, 그룹 생성, 참가자 키 래핑 게시, 메시지 전송, 이벤트 로드에는 **X API**를 사용합니다.
***
## 그룹 생성 및 키 설정
1. `POST /2/chat/conversations/group/initialize`로 그룹 ID를 발급합니다 — 응답의 `data.conversation_id`가 이후 모든 곳에서 사용하는 g-접두사 ID입니다.
2. 각 멤버의 신원 공개 키와 `public_key_version`을 로드합니다 (**암호화 키** 아래 `GET` 공개 키 경로; [`GET /2/users/public_keys`](/x-api/users/get-public-keys-for-multiple-users)는 한 요청으로 여러 사용자를 가져옴). 사용하기 전에 `verify_key_binding`으로 각 레코드를 검증하세요 ([시작하기](/xchat/getting-started#4-set-up-conversation-keys)의 경고 참조).
3. **모든** 멤버(자신 포함), g-접두사 ID, 멤버/관리자 ID 목록으로 \*\*`prepare_group_create`\*\*를 한 번 실행합니다. 한 번의 호출로 대화 키를 생성하고, 모든 멤버에 대해 래핑하고, 생성에 서명합니다 — **두 개**의 action signature(대화 키 변경과 그룹 생성)를 반환합니다.
4. 그룹 멤버/관리자, `conversation_key_version`, `conversation_participant_keys`(SDK **`encrypted_key`** → API **`encrypted_conversation_key`**), 그리고 **두 개 모두**의 `action_signatures`와 함께 `POST /2/chat/conversations/group`을 호출합니다. 검증 실패는 안정적이고 사람이 읽을 수 있는 메시지로 반환됩니다. 예: `"Too many members: adding these members would exceed the allowed group size."` 또는 `"Cannot add all members: one or more of the requested members cannot be added to this conversation."`.
5. 암호화/복호화를 위해 **원시** 대화 키와 **버전**을 보관하세요.
`prepare_group_create`에 전달하는 `title`과 `avatar_url`은 서명되어 그룹 생성 이벤트에 그대로 임베드되며, 서버는 이를 요청과 대조합니다 — 그래서 POST 본문의 `group_name` / `group_avatar_url` 값은 SDK에 전달한 것과 **바이트 단위로 동일**해야 합니다. 그렇지 않으면 호출이 서명 검증에 실패합니다.
```python theme={null}
prepared = chat.prepare_group_create(
"YOUR_USER_ID", signing_key_version, member_public_keys,
group_id, # g-prefixed id from POST /2/chat/conversations/group/initialize
member_ids, admin_ids, title="Project team",
)
# POST /2/chat/conversations/group with group_members, group_admins,
# conversation_key_version, conversation_participant_keys, and BOTH
# entries of prepared["action_signatures"]
```
```typescript theme={null}
const prepared = chat.prepareGroupCreate({
senderId: myUserId, signingKeyVersion, publicKeys: memberPublicKeys,
conversationId: groupId, // g-prefixed id from POST /2/chat/conversations/group/initialize
memberIds, adminIds, title: 'Project team',
});
// prepared.actionSignatures has two entries — send both
```
```rust theme={null}
let mut params = GroupCreateParams::new(
&sender_id, &signing_key_version, member_public_keys,
&group_id, member_ids, admin_ids,
);
params.title = Some("Project team".into());
let prepared = chat.prepare_group_create(params)?;
// prepared.action_signatures has two entries — send both
```
```go theme={null}
prepared, err := chat.PrepareGroupCreate(chatxdk.GroupCreateParams{
SenderID: myUserID, SigningKeyVersion: signingKeyVersion,
PublicKeys: memberPublicKeys, ConversationID: groupID,
MemberIDs: memberIDs, AdminIDs: adminIDs, Title: "Project team",
})
// prepared.ActionSignatures has two entries — send both
_ = prepared
_ = err
```
```csharp theme={null}
var prepared = chat.PrepareGroupCreate(new GroupCreateParams {
SenderId = myUserId, SigningKeyVersion = signingKeyVersion,
PublicKeys = memberPublicKeys, ConversationId = groupId,
MemberIds = memberIds, AdminIds = adminIds, Title = "Project team",
});
// prepared.ActionSignatures has two entries — send both
```
```java theme={null}
GroupCreateParams params = new GroupCreateParams();
params.senderId = myUserId;
params.signingKeyVersion = signingKeyVersion;
params.publicKeys = memberPublicKeys;
params.conversationId = groupId;
params.memberIds = memberIds;
params.adminIds = adminIds;
params.title = "Project team";
PreparedConversationChange prepared = chat.prepareGroupCreate(params);
// prepared.actionSignatures has two entries — send both
```
참가자 키와 action signature의 본문 매핑(`message_id`, `encoded_message_event_detail`, 중첩된 `message_event_signature`)은 [시작하기 — 대화 키](/xchat/getting-started#4-set-up-conversation-keys)의 키 POST와 동일합니다.
멤버십이 변경될 때, 새 멤버 ID와 함께 현재 로스터(멤버, 관리자, 대기 중인 멤버, 설정된 경우 현재 제목/아바타/TTL)를 사용하여 \*\*`prepare_group_members_change`\*\*를 호출합니다. 대화 키를 교체하고, 그룹 생성처럼 **두 개**의 action signature를 반환합니다 — 모두 **멤버 추가**(`POST /2/chat/conversations/{id}/members`)에 POST하세요. 그런 다음 **키 변경** 트래픽이 예상됩니다: 이를 [시작하기의 키 교체](/xchat/getting-started#6-receive-and-decrypt)처럼 처리하세요(`extract_conversation_keys` / `decrypt_events`, 그런 다음 최신 버전으로 암호화).
`prepare_group_members_change`는 전달한 로스터에게만 래핑된 **새로운** 대화 키를 생성하므로, 새 멤버는 새 키 버전을 받고 이전 버전으로 전송된 메시지를 복호화할 수 없습니다. 반대로는 성립하지 않습니다: 교체는 **이전** 버전에 대한 접근을 결코 취소하지 않습니다 — 이미 이전 키를 보유한 사람은 누구나 그 키로 암호화된 메시지를 계속 읽을 수 있습니다. 대화 키가 노출되었다고 의심되면 `prepare_conversation_key_change`로 교체하세요. 이는 향후 메시지만 보호합니다.
***
## 암호화된 그룹 메타데이터
일부 대화 필드(예: 표시 **이름** 또는 **아바타 URL**)는 대화 키 아래 **암호화된** 상태로 도착할 수 있습니다. 이것은 `encrypt_message`가 **아닙니다**; 일반 Chat XDK의 **`encrypt` / `decrypt`** 쌍입니다 (UTF-8 문자열 입력, base64 암호문 출력, **원시** 대화 키 사용).
특정 필드가 암호화되어 저장되는지 여부는 그것을 쓰는 클라이언트가 결정합니다: `prepare_group_create`는 제공한 그대로 제목에 서명하고 전송합니다(대화 키는 그 호출이 생성하기 전까지 존재하지 않으므로, 생성 시점의 제목은 그것으로 암호화될 수 없습니다). 필드가 암호문인 대화를 읽을 때, 필드가 쓰여진 시점에 활성화되어 있던 키 버전과 `decrypt`로 복호화하세요.
```python theme={null}
# Decrypt a field from the conversation object (name may vary by API shape)
group_name = chat.decrypt(conversation["group_name"], raw_conv_key)
# Encrypt before update if your API accepts ciphertext metadata
encrypted_name = chat.encrypt("Project team", raw_conv_key)
```
```typescript theme={null}
const groupName = chat.decrypt(conversation.groupName, rawConvKey);
const encryptedName = chat.encrypt('Project team', rawConvKey);
```
```rust theme={null}
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let group_name = chat.decrypt(&conversation_group_name_b64, &conv_key)?;
let encrypted_name = chat.encrypt("Project team", &conv_key)?;
```
```go theme={null}
groupName, err := chat.Decrypt(conversationGroupNameB64, rawConvKey)
encryptedName, err := chat.Encrypt("Project team", rawConvKey)
_ = groupName
_ = encryptedName
```
```csharp theme={null}
string groupName = chat.Decrypt(conversationGroupNameB64, rawConvKey);
string encryptedName = chat.Encrypt("Project team", rawConvKey);
```
```java theme={null}
String groupName = chat.decrypt(conversationGroupNameB64, rawConvKey);
String encryptedName = chat.encrypt("Project team", rawConvKey);
```
해당 메타데이터에 적용되는 **현재** 대화 키 버전을 사용하세요. 키가 교체되었다면, 필드가 쓰여진 시점에 활성화되어 있던 버전으로 복호화하세요(또는 메타데이터가 항상 교체 시 재작성되는 경우 제품 규칙을 따르세요).
***
## 메시지 및 이벤트
원시 대화 키를 가지고 있다면, 그룹에서 송수신은 1:1과 동일합니다:
* **전송:** `encrypt_message` → 메시지 전송 API ([시작하기](/xchat/getting-started#5-send-a-message))
* **수신:** 이벤트 API 또는 [실시간 전달](/xchat/real-time-events) → `decrypt_event` / `decrypt_events`
* **미디어:** 그룹 대화 ID와 함께 [미디어](/xchat/media)
멤버십 기반 교체 이후에는 항상 **최신** 키 버전으로 암호화하세요.
***
## 체크리스트
1. `POST /2/chat/conversations/group/initialize`로 g-접두사 ID를 발급합니다
2. **모든** 멤버로 `prepare_group_create`를 호출; 참가자 키 래핑과 **두 개 모두**의 action signature를 `POST /2/chat/conversations/group`에 POST
3. 원시 키 + 버전을 캐시; 키 변경 이벤트 시 업데이트
4. 멤버십 변경 시, `prepare_group_members_change`(두 개의 서명) → `POST /2/chat/conversations/{id}/members`
5. 필드가 암호문일 때 `decrypt`로 그룹 메타데이터를 복호화
6. 1:1과 동일한 패턴으로 송수신
# Chat API 소개
Source: https://docs.x.com/ko/xchat/introduction
Chat XDK 클라이언트 측 암호화로 X에서 종단 간 암호화 및 서명된 다이렉트 메시지를 주고받는 X Chat API 개요입니다.
**Chat API**를 사용하면 X에서 **종단 간 암호화된** 다이렉트 메시지를 주고받을 수 있습니다. 메시지 본문은 클라이언트에서 암호화되며, X는 암호문만 라우팅할 뿐 평문 내용을 읽을 수 없습니다. 메시지는 또한 **서명**되어 수신자가 발신자를 검증할 수 있습니다.
***
## 앱에 필요한 구성 요소
| 구성 요소 | 역할 |
| :------------------------------- | :----------------------------------------------------------------------------------------- |
| **[Chat XDK](/xchat/xchat-xdk)** | 키 생성, 암호화/복호화, 서명/검증, 선택적 패스코드 보호 보안 키 백업 (Python, JS, Rust, Go, C#, Java) |
| **X API 접근** | 공개 키, 대화 키, 메시지, 이벤트, 미디어—**[XDK](/xdks/python/overview)**(Python/TypeScript) 또는 HTTPS로 제공 |
| **전송** | 실시간 이벤트를 위한 [웹훅 또는 활동 스트림](/xchat/real-time-events); 이력 조회를 위한 이벤트 API |
전체 구현은 \*\*[시작하기](/xchat/getting-started)\*\*를 참조하세요. 개념만 확인하려면 \*\*[암호화 기초](/xchat/cryptography-primer)\*\*를 참조하세요.
***
## 암호화 동작 방식 (개요)
1. **신원(identity)** 및 **서명(signing)** 키페어를 생성하고, 개인 키를 안전하게 저장합니다 (보안 키 백업 또는 보호된 blob 사용).
2. 다른 사람이 사용자와 대화 키를 교환하고 서명을 검증할 수 있도록 **공개 키를 게시**합니다.
3. 각 참가자에게 암호화된 사본을 게시하여 **대화 키**를 공유합니다.
4. 발신 메시지를 **암호화하고 서명**하여, X에는 암호문만 전송합니다.
5. 웹훅, 스트림 또는 이벤트 이력을 통해 암호문을 **수신**합니다.
6. Chat XDK로 **검증하고 복호화**합니다.
***
## 유용한 엔드포인트
사이드바의 **API 참조** 아래에 그룹화되어 있으며, 다음을 포함합니다:
* 공개 키 — 등록 및 조회
* 대화 및 메시지 — 대화 목록/조회, 키 추가/교체, 이벤트, 전송, 입력 중, 읽음, 그룹 멤버십
* 미디어 — 암호화된 첨부 파일 업로드 및 다운로드 ([가이드](/xchat/media))
***
## 인증 참고 사항
DM 관련 스코프(`dm.read`, `dm.write`, 필요에 따라 `users.read` / `tweet.read`; 업로드에는 `media.write`)와 함께 **OAuth 2.0 사용자 컨텍스트**를 사용하세요. 사용자에 대한 X Chat 활동을 이용하려면 해당 사용자의 승인이 필요합니다. 보안 키 백업 구성은 **본인**의 공개 키 레코드(`juicebox_config` 필드)에 반환됩니다. 시작하기를 참조하세요.
***
## 다음 단계
1. [암호화 기초](/xchat/cryptography-primer) — E2EE 개념에 대한 선택적 배경 지식
2. [시작하기](/xchat/getting-started) — 키 구현, 전송 및 수신
3. [Chat XDK](/xchat/xchat-xdk) — 암호화 SDK 참조
4. 필요한 주제에 따라 [실시간 이벤트](/xchat/real-time-events), [미디어](/xchat/media), 또는 [문제 해결](/xchat/troubleshooting)
# 미디어 및 첨부 파일
Source: https://docs.x.com/ko/xchat/media
Chat XDK 스트림 암호화와 미디어 업로드 엔드포인트로 X Chat에서 이미지와 파일 첨부를 암호화, 업로드, 전송, 다운로드, 복호화합니다.
이미지 및 기타 파일은 텍스트와 **동일한 대화 키**를 사용합니다. Chat XDK로 바이트를 암호화하고(`encrypt_stream` / `decrypt_stream`), **`/2/chat/media/upload`** 경로(사이드바 **API 참조 → 미디어**)로 업로드한 다음, `encrypt_message`에 \*\*`media_hash_key`\*\*를 첨부합니다.
업로드 시 DM 스코프와 함께 \*\*`media.write`\*\*를 포함하세요. 경로에는 하이픈으로 연결된 대화 ID를 사용하세요(`:` → `-`). MIME/치수는 **복호화된** 바이트에서 가져오는 것이 좋습니다.
이 경로는 Posts 미디어 모델(`expansions=attachments.media_keys`, `media.fields=variants` 등)이 **아닙니다**. 이러한 매개변수는 **Posts**에 적용됩니다; E2EE X Chat blob은 \*\*`media_hash_key`\*\*와 X Chat 미디어 다운로드로 지정됩니다.
```mermaid theme={null}
flowchart LR
A[Plain bytes] --> B[encrypt_stream]
B --> C[Upload 3 steps]
C --> D[media_hash_key]
D --> E[encrypt_message + send]
F[GET media] --> G[decrypt_stream]
G --> H[Plain bytes]
```
***
## 암호화
```python theme={null}
from chat_xdk import detect_mime_type, detect_image_dimensions
with open("photo.jpg", "rb") as f:
plaintext = f.read()
mime = detect_mime_type(plaintext)
dims = detect_image_dimensions(plaintext)
width, height = dims if dims else (0, 0)
encrypted_blob = chat.encrypt_stream(plaintext, raw_conv_key)
```
```typescript theme={null}
import { detectMimeType, detectImageDimensions } from '@xdevplatform/chat-xdk';
import { readFile } from 'fs/promises';
const plaintext = await readFile('photo.jpg');
const mime = detectMimeType(plaintext);
const dims = detectImageDimensions(plaintext);
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;
const encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
```
```rust theme={null}
use chat_xdk_core::{detect_image_dimensions, detect_mime_type};
let plaintext = std::fs::read("photo.jpg")?;
let _mime = detect_mime_type(&plaintext);
let dims = detect_image_dimensions(&plaintext);
let (width, height) = dims.map(|d| (d.width as i64, d.height as i64)).unwrap_or((0, 0));
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let encrypted_blob = chat.encrypt_stream(&plaintext, &conv_key)?;
```
```go theme={null}
plaintext, err := os.ReadFile("photo.jpg")
mime, _ := chatxdk.DetectMimeType(plaintext)
dims, _ := chatxdk.DetectImageDimensions(plaintext)
_ = mime
encrypted, err := chat.EncryptStream(plaintext, rawConvKey)
_ = dims
_ = encrypted
```
```csharp theme={null}
using ChatXdk;
byte[] plaintext = await File.ReadAllBytesAsync("photo.jpg");
string? mime = ChatXdkUtilities.DetectMimeType(plaintext);
var dims = ChatXdkUtilities.DetectImageDimensions(plaintext);
int width = (int)(dims?.Width ?? 0);
int height = (int)(dims?.Height ?? 0);
byte[] encryptedBlob = chat.EncryptStream(plaintext, rawConvKey);
```
```java theme={null}
import com.x.chatxdk.ChatXdkUtilities;
import com.x.chatxdk.Types.ImageDimensions;
byte[] plaintext = Files.readAllBytes(Path.of("photo.jpg"));
String mime = ChatXdkUtilities.detectMimeType(plaintext);
ImageDimensions dims = ChatXdkUtilities.detectImageDimensions(plaintext);
int width = dims != null ? (int) dims.width : 0;
int height = dims != null ? (int) dims.height : 0;
byte[] encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
```
`encrypt_stream` / `decrypt_stream`은 전체 페이로드를 메모리에서 처리합니다. 큰 파일의 경우 `stream_encryptor()` / `stream_decryptor()`가 증분 객체(`StreamEncryptor` / `StreamDecryptor`)를 반환합니다: `push`로 청크를 공급한 다음 `finish`를 한 번 호출하세요—`finish`는 스트림이 잘렸으면 오류를 냅니다.
***
## 업로드
| 단계 | 메서드 | 경로 |
| :-- | :----- | :----------------------------------- |
| 초기화 | `POST` | `/2/chat/media/upload/initialize` |
| 추가 | `POST` | `/2/chat/media/upload/{id}/append` |
| 완료 | `POST` | `/2/chat/media/upload/{id}/finalize` |
**API 참조 → 미디어** 아래의 OpenAPI 페이지에 있는 요청 본문을 사용하세요. 크기가 필요한 곳에는 **암호화된** blob 크기를 사용하는 것이 좋습니다. 완료는 첨부 및 다운로드용 \*\*`media_hash_key`\*\*를 반환합니다. 일시적인 `5xx`는 백오프로 재시도하세요. Python/TypeScript는 미디어 헬퍼가 존재할 때 XDK를 사용할 수 있습니다; 그렇지 않으면 어떤 언어에서든 Bearer 토큰과 함께 POST하세요.
***
## 첨부 파일과 함께 전송
미디어 첨부와 함께 암호화한 다음, 메시지 전송 본문을 POST합니다([시작하기](/xchat/getting-started#5-send-a-message)와 동일한 필드 매핑).
```python theme={null}
import uuid
from xdk.chat.models import SendMessageRequest
message_id = str(uuid.uuid4())
payload = chat.encrypt_message(
message_id,
sender_id,
conversation_id,
raw_conv_key,
caption or "",
conversation_key_version,
signing_key_version,
attachments=[{
"attachment_type": "media",
"media_hash_key": media_hash_key,
"width": width,
"height": height,
"filesize_bytes": len(plaintext),
"filename": "photo.jpg",
}],
)
client.chat.send_message(
conversation_id.replace(":", "-"),
SendMessageRequest(
message_id=message_id,
encoded_message_create_event=payload.encrypted_content,
encoded_message_event_signature=payload.encoded_event_signature,
),
)
```
```typescript theme={null}
const messageId = crypto.randomUUID();
const payload = chat.encryptMessage({
messageId,
senderId,
conversationId,
conversationKey: rawConvKey,
text: caption || '',
conversationKeyVersion,
signingKeyVersion,
attachments: [{
attachmentType: 'media',
mediaHashKey: mediaHashKey,
width,
height,
filesizeBytes: plaintext.byteLength,
filename: 'photo.jpg',
}],
});
await client.chat.sendMessage(conversationId.replace(/:/g, '-'), {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
});
```
```rust theme={null}
// Set attachments on EncryptMessageParams per chat_xdk_core AttachmentDescriptor::Media
let payload = chat.encrypt_message(params_with_media_attachment)?;
let body = serde_json::json!({
"message_id": message_id,
"encoded_message_create_event": payload.encrypted_content,
"encoded_message_event_signature": payload.encoded_event_signature,
});
let path_id = conversation_id.replace(':', "-");
http.post(format!("https://api.x.com/2/chat/conversations/{path_id}/messages"))
.header("Authorization", &auth)
.json(&body)
.send()?;
```
```go theme={null}
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawConvKey, Text: caption,
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
Attachments: []chatxdk.AttachmentDescriptor{{
AttachmentType: "media",
MediaHashKey: mediaHashKey,
Width: width,
Height: height,
FilesizeBytes: int64(len(plaintext)),
Filename: "photo.jpg",
}},
})
// POST payload.EncryptedContent / EncodedEventSignature to /2/chat/conversations/{id}/messages
```
```csharp theme={null}
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId,
SenderId = senderId,
ConversationId = conversationId,
ConversationKey = rawConvKey,
Text = caption ?? "",
ConversationKeyVersion = conversationKeyVersion,
SigningKeyVersion = signingKeyVersion,
// Attachments = media descriptor with MediaHashKey, Width, Height,
// FilesizeBytes, and Filename (as in the Go tab above)
});
// POST EncryptedContent / EncodedEventSignature as for text messages
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawConvKey;
params.text = caption != null ? caption : "";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
// params.attachments — media type with mediaHashKey, width, height, filename
SendPayload payload = chat.encryptMessage(params);
// POST to /2/chat/conversations/{id}/messages
```
***
## 다운로드 및 복호화
경로: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/download-chat-media). 응답 본문은 암호문입니다. 수신 메시지에서는 복호화된 첨부 파일 / `media_hashes`에서 `media_hash_key`를 읽습니다.
**이벤트의 키 버전으로 키를 선택하세요.** 각 복호화된 메시지 이벤트에는 콘텐츠가 암호화된 `keyVersion`(JS; 다른 바인딩은 `key_version`)이 포함됩니다. 최신이 아닌 **해당** 버전의 대화 키—`conversationKeys.keys[event.keyVersion]`—로 첨부 파일을 복호화하세요. 키 교체 이후(예: 멤버 추가)에는 최신 키가 오래된 메시지에 첨부된 미디어를 복호화할 수 없습니다.
```python theme={null}
keys = result["conversation_keys"]["keys"]
key_for_media = keys[event["key_version"]] # not the latest version
plaintext = chat.decrypt_stream(encrypted_blob, key_for_media)
```
```typescript theme={null}
const keys = result.conversationKeys.keys;
const keyForMedia = keys[event.keyVersion]; // not the latest version
const plaintext = chat.decryptStream(encryptedBlob, keyForMedia);
```
```python theme={null}
import requests
from chat_xdk import detect_mime_type
api_id = conversation_id.replace(":", "-")
url = f"https://api.x.com/2/chat/media/{api_id}/{media_hash_key}"
r = requests.get(url, headers={"Authorization": f"Bearer {access_token}"})
r.raise_for_status()
plaintext = chat.decrypt_stream(r.content, raw_conv_key)
mime = detect_mime_type(plaintext) or "application/octet-stream"
```
```typescript theme={null}
import { detectMimeType } from '@xdevplatform/chat-xdk';
const apiId = conversationId.replace(/:/g, '-');
const res = await fetch(
`https://api.x.com/2/chat/media/${apiId}/${mediaHashKey}`,
{ headers: { Authorization: `Bearer ${accessToken}` } },
);
const encryptedBlob = new Uint8Array(await res.arrayBuffer());
const plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
const mime = detectMimeType(plaintext) ?? 'application/octet-stream';
```
```rust theme={null}
let api_id = conversation_id.replace(':', "-");
let encrypted_blob = http
.get(format!("https://api.x.com/2/chat/media/{api_id}/{media_hash_key}"))
.header("Authorization", &auth)
.send()?
.bytes()?;
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let plaintext = chat.decrypt_stream(&encrypted_blob, &conv_key)?;
```
```go theme={null}
url := fmt.Sprintf("https://api.x.com/2/chat/media/%s/%s",
strings.ReplaceAll(conversationID, ":", "-"), mediaHashKey)
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := http.DefaultClient.Do(req)
// read body into []byte → chat.DecryptStream(encryptedBlob, rawConvKey)
_ = resp
_ = err
```
```csharp theme={null}
var apiId = conversationId.Replace(':', '-');
byte[] encryptedBlob = await http.GetByteArrayAsync(
$"https://api.x.com/2/chat/media/{apiId}/{mediaHashKey}");
byte[] plaintext = chat.DecryptStream(encryptedBlob, rawConvKey);
string? mime = ChatXdkUtilities.DetectMimeType(plaintext);
```
```java theme={null}
String apiId = conversationId.replace(':', '-');
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.x.com/2/chat/media/" + apiId + "/" + mediaHashKey))
.header("Authorization", "Bearer " + accessToken)
.GET()
.build();
byte[] encryptedBlob = http.send(req, HttpResponse.BodyHandlers.ofByteArray()).body();
byte[] plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
String mime = ChatXdkUtilities.detectMimeType(plaintext);
```
***
## 팁
* 미디어가 암호화된 시점과 동일한 **대화 키 버전**을 사용하세요
* 평문 미디어나 원시 키를 로그에 남기지 마세요
* MIME은 복호화 **후**에 감지하세요
* 웹 클라이언트: 가능하면 클라이언트에서 암호화/복호화; OAuth 토큰은 서버에 유지하세요
각 미디어 경로의 전체 요청 및 응답 스키마는 사이드바의 **API 참조 → 미디어**에 있습니다 (업로드 초기화, 청크 추가, 업로드 완료, 미디어 다운로드).
# 실시간 X Chat 이벤트
Source: https://docs.x.com/ko/xchat/real-time-events
웹훅 또는 활동 스트림으로 chat.received, chat.sent 등 암호화된 X Chat 활동을 수신하고 Chat XDK로 페이로드를 복호화합니다.
X는 페이로드에 **암호문**을 포함하여 **`chat.received`**, **`chat.sent`** 및 관련 X Chat 활동을 전달합니다. [Chat XDK](/xchat/xchat-xdk)로 복호화하세요.
| 계층 | 역할 |
| :----------------- | :---------------------------------------------------------------------------------------------------------- |
| **X Activity API** | `GET /2/activity/stream`; `POST` / `GET` / `PUT` / `DELETE` `/2/activity/subscriptions` (작업별 OpenAPI 보안 참조) |
| **웹훅** | 자체 HTTPS URL에서 종료하는 경우 선택적 `POST` / `GET` `/2/webhooks` 및 `PUT` / `DELETE` `/2/webhooks/{webhook_id}` 경로 |
| **Chat XDK** | `extract_conversation_keys`, `decrypt_event` / `decrypt_events` |
비공개 X Chat 이벤트 유형은 모니터링하는 사용자에 대한 승인이 필요합니다. 암호화된 X Chat 파일 첨부는 \*\*`media_hash_key`\*\*와 X Chat 미디어 다운로드를 사용합니다—Post API의 `expansions=attachments.media_keys` / `media.fields=variants`가 아닙니다.
***
## 이벤트 유형
| 이벤트 | 시점 |
| :----------------------- | :--------------------------- |
| `chat.received` | 구독된 사용자가 암호화된 DM을 수신할 때 |
| `chat.sent` | 구독된 사용자가 암호화된 DM을 보낼 때 |
| `chat.conversation_join` | 구독된 사용자가 그룹에 참여할 때 (제공되는 경우) |
***
## 1. 전달 방식 선택
**활동 스트림 (봇에 종종 가장 간단함):** 앱 Bearer 토큰과 함께 `GET /2/activity/stream`을 사용합니다 (OpenAPI에 따라 선택적 `backfill_minutes`, `start_time`, `end_time`). 클라이언트 측에서 `chat.received` / `chat.sent`를 필터링하세요.
**활동 구독:** 다음으로 지속적인 구독을 관리합니다:
* `POST /2/activity/subscriptions` — 생성
* `GET /2/activity/subscriptions` — 목록 (페이지네이션됨)
* `PUT /2/activity/subscriptions/{subscription_id}` — 업데이트
* `DELETE /2/activity/subscriptions/{subscription_id}` 또는 `DELETE /2/activity/subscriptions?ids=` — 삭제
요청 본문과 필요한 스코프는 각 경로의 OpenAPI 작업에 정의되어 있습니다. X Activity API (XAA) 구독을 생성하려면 모니터링하는 사용자에 대한 **사용자 컨텍스트 승인**(관련 스코프를 포함한 OAuth 2.0 사용자 컨텍스트, 예: 채팅 이벤트의 경우 `dm.read`)이 필요합니다.
**웹훅:** HTTPS 엔드포인트에서 이벤트를 종료하는 경우, `POST /2/webhooks`로 웹훅을 등록하고 CRC 챌린지를 통과한 다음 `webhook_id`를 참조하여 `POST /2/activity/subscriptions`로 활동 구독을 생성합니다 (OpenAPI의 Webhooks 및 Activity 작업 참조). Python/TypeScript XDK는 SDK 버전에 포함되어 있을 때 웹훅 및 활동에 대한 헬퍼를 노출할 수 있습니다.
```python theme={null}
from xdk import Client
# Stream (app token) — exact helper names depend on your XDK version
stream_client = Client(bearer_token="YOUR_BEARER_TOKEN")
# for event in stream_client.activity.stream():
# handle_payload(event) # see "Decrypt with the Chat XDK" below
# Or create a subscription — requires user-context auth for the monitored user
client = Client(access_token="YOUR_OAUTH2_USER_TOKEN")
client.activity.create_subscription({
"event_type": "chat.received",
"filter": {"user_id": "USER_ID_TO_MONITOR"},
})
```
```typescript theme={null}
import { Client } from '@xdevplatform/xdk';
// Creating a subscription requires user-context auth for the monitored user
const client = new Client({ accessToken: 'YOUR_OAUTH2_USER_TOKEN' });
await client.activity.createSubscription({
event_type: 'chat.received',
filter: { user_id: 'USER_ID_TO_MONITOR' },
});
// Stream: client.activity.stream() when available in your SDK version
```
발신 사본이 필요한 경우 `chat.sent`도 구독하세요. 다른 언어: 동일한 `/2/activity/*` HTTPS 경로를 직접 호출하세요 (구독 생성에는 사용자 컨텍스트 토큰, 스트림에는 앱 Bearer 토큰).
***
## 2. CRC (웹훅 전용)
웹훅을 사용하는 경우, 소비자 시크릿을 사용한 토큰의 HMAC-SHA256으로 챌린지-응답 검사(GET `crc_token`)에 응답하세요. 이는 웹훅 제품이 기대하는 JSON 형태(일반적으로 `sha256=`)여야 합니다.
***
## 3. Chat XDK로 복호화
실시간 필드: **`payload.encoded_event`**, 선택적 **`payload.conversation_key_change_event`**. \*\*`event_uuid`\*\*로 중복을 제거하세요.
JavaScript는 camelCase 이벤트 유형(`message`)을 사용합니다; 다른 바인딩은 `"Message"`와 snake\_case 필드를 사용합니다.
```python theme={null}
from chat_xdk import Chat
chat = Chat(JUICEBOX_CONFIG_JSON)
chat.unlock("YOUR_PASSCODE")
chat.set_key_version(SIGNING_KEY_VERSION)
conversation_keys = {}
def signing_keys(user_id: str):
resp = api_client.chat.get_user_public_keys(
user_id,
public_key_fields=[
"public_key_version", "public_key", "signing_public_key", "identity_public_key_signature",
],
)
return [
{
"user_id": user_id,
"public_key_version": r["public_key_version"],
"public_key": r["signing_public_key"],
"identity_public_key": r["public_key"],
"identity_public_key_signature": r["identity_public_key_signature"],
}
for r in resp.data
]
data = body.get("data") or {}
if data.get("event_type") in ("chat.received", "chat.sent"):
p = data.get("payload") or {}
cid = p.get("conversation_id")
if p.get("conversation_key_change_event"):
conversation_keys[cid] = chat.extract_conversation_keys(
[p["conversation_key_change_event"]]
)["keys"]
ev = chat.decrypt_event(
p["encoded_event"],
conversation_keys.get(cid, {}),
signing_keys(p["sender_id"]),
)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: JUICEBOX_CONFIG_JSON,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(SIGNING_KEY_VERSION);
const conversationKeys = new Map>();
async function signingKeys(userId: string) {
const resp = await apiClient.chat.getUserPublicKeys(userId, {
publicKeyFields: [
'public_key_version', 'public_key', 'signing_public_key', 'identity_public_key_signature',
],
});
return resp.data.map((r: any) => ({
userId,
publicKeyVersion: r.public_key_version,
publicKey: r.signing_public_key,
identityPublicKey: r.public_key,
identityPublicKeySignature: r.identity_public_key_signature,
}));
}
const data = body?.data ?? {};
if (data.event_type === 'chat.received' || data.event_type === 'chat.sent') {
const p = data.payload ?? {};
const cid = p.conversation_id as string;
if (p.conversation_key_change_event) {
conversationKeys.set(
cid,
chat.extractConversationKeys([p.conversation_key_change_event]).keys,
);
}
const ev = chat.decryptEvent(
p.encoded_event,
conversationKeys.get(cid) ?? {},
await signingKeys(p.sender_id),
);
}
```
```rust theme={null}
// chat: ChatCore or Chat, already unlocked / keys imported
if let Some(kc) = key_change.as_deref() {
let extracted = chat.extract_conversation_keys(&[kc]);
conv_keys.extend(extracted.keys);
}
// sender_signing_keys from GET /2/users/{sender_id}/public_keys
let event = chat.decrypt_event(&encoded_event, &conv_keys, &sender_signing_keys)?;
```
```go theme={null}
if keyChange != "" {
extracted, _ := chat.ExtractConversationKeys([]string{keyChange})
for v, k := range extracted.Keys {
convKeys[v] = k
}
}
event, err := chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys)
if err == nil && event.Type == "Message" {
fmt.Println(event.AsMessage().Text())
}
```
```csharp theme={null}
if (!string.IsNullOrEmpty(keyChangeB64))
{
var extracted = chat.ExtractConversationKeys(new[] { keyChangeB64 });
foreach (var kv in extracted.Keys)
convKeys[kv.Key] = kv.Value;
}
var evt = chat.DecryptEvent(encodedEvent, convKeys, senderSigningKeys);
if (evt.GetProperty("type").GetString() == "Message")
Console.WriteLine(evt.GetProperty("content").GetProperty("text").GetString());
```
```java theme={null}
if (keyChangeB64 != null && !keyChangeB64.isEmpty()) {
var extracted = chat.extractConversationKeys(List.of(keyChangeB64));
convKeys.putAll(extracted.keys);
}
JsonNode evt = chat.decryptEvent(encodedEvent, convKeys, senderSigningKeys);
if ("Message".equals(evt.path("type").asText())) {
System.out.println(evt.path("content").path("text").asText());
}
```
이력: [`GET /2/chat/conversations/{id}/events`](/x-api/chat/get-chat-conversation-events) + **`decrypt_events`** — [시작하기](/xchat/getting-started#6-receive-and-decrypt)를 참조하세요.
***
## 페이로드 형태 (실시간)
```json theme={null}
{
"data": {
"event_type": "chat.received",
"event_uuid": "0f52b591-4b7e-4f13-92cd-30e6b2a3f18a",
"payload": {
"conversation_id": "1215441834412953600-1843439638876491776",
"sender_id": "1843439638876491776",
"encoded_event": "BASE64_ENCODED_MESSAGE_EVENT",
"conversation_key_version": "1782945126642",
"conversation_key_change_event": "BASE64_ENCODED_KEY_CHANGE_EVENT"
}
}
}
```
***
## 관행
* 플랫폼 요구 사항에 따라 웹훅 서명을 검증하세요
* 대화 키와 발신자 공개 키를 캐시하세요
* 의존 메시지를 복호화하기 전에 키 변경 blob을 적용하세요
* `event_uuid`로 중복을 제거하세요
# 문제 해결
Source: https://docs.x.com/ko/xchat/troubleshooting
Chat XDK 오류, 안전한 키 백업 복구, 복호화 실패 등 X Chat 암호화와 관련된 흔한 문제를 진단합니다.
이 페이지는 **X Chat 암호화와 Chat XDK에 특화된** 문제—키, 보안 키 백업, 복호화/검증, 그리고 암호화된 전송 페이로드 구축—를 다룹니다.
웹훅, OAuth, HTTP 상태 코드 및 속도 제한은 일반 [X API](/x-api/introduction) 및 [인증](/fundamentals/authentication/overview) 문서를 사용하세요.
***
## 키 및 보안 키 백업
### 잠금 해제 실패 (잘못된 패스코드)
* 패스코드가 `setup`에서 사용한 것과 일치하는지 확인하세요
* 시도 사이에 기다리세요; realm은 잘못된 추측에 대해 속도 제한을 두고 너무 많은 실패 후에는 복구를 잠글 수 있습니다
```python theme={null}
try:
chat.unlock(passcode)
except ValueError as e:
print(e) # may mention InvalidPin or guesses remaining
```
```typescript theme={null}
try {
await chat.unlock(passcode);
} catch (e) {
console.error((e as Error).message);
}
```
```rust theme={null}
chat.unlock(passcode_bytes).await?;
```
```go theme={null}
if err := chat.Unlock(passcode, juiceboxConfigJSON); err != nil {
log.Println(err)
}
```
```csharp theme={null}
try { chat.Unlock(passcode, juiceboxConfigJson); }
catch (Exception e) { Console.WriteLine(e.Message); }
```
```java theme={null}
try { chat.unlock(passcode, juiceboxConfigJson); }
catch (Exception e) { System.out.println(e.getMessage()); }
```
### 키가 로드되지 않아 암호화 또는 복호화 실패
먼저 개인 키를 로드한 다음, X의 레코드에서 공개 키 **버전**을 설정하세요.
```python theme={null}
chat.unlock(passcode) # or: chat.import_keys(blob)
chat.set_key_version(signing_key_version)
```
```typescript theme={null}
await chat.unlock(passcode);
chat.setKeyVersion(signingKeyVersion);
```
```rust theme={null}
chat.import_keys(&blob)?;
chat.set_key_version(&signing_key_version);
```
```go theme={null}
blob, _ := chatxdk.Base64ToBytes(privateKeysB64)
_ = chat.ImportKeys(blob)
chat.SetKeyVersion(signingKeyVersion)
```
```csharp theme={null}
chat.ImportKeys(blobBytes);
chat.SetKeyVersion(signingKeyVersion);
```
```java theme={null}
chat.importKeys(blobBytes);
chat.setKeyVersion(signingKeyVersion);
```
### 메시지에 대한 대화 키 누락
해당 메시지의 `conversation_key_version`에 대한 **원시** 키가 없습니다.
1. `extract_conversation_keys`로 `conversation_key_change_event`(실시간 이벤트) 또는 `meta.conversation_key_events`(이력)의 키 자료를 복호화하거나, **또는** `decrypt_events`에 그 blob을 포함하세요
2. 해당 버전에 대해 대화 키가 추가되었고 여전히 참가자인지 확인하세요 ([시작하기](/xchat/getting-started#4-set-up-conversation-keys) 참조)
### 상대방에게 공개 키가 없음
아직 온보딩을 마치지 않았을 수 있습니다. 그들이 등록한 후, **API 참조 → 암호화 키**에서 `public_key`, `signing_public_key`, `identity_public_key_signature`, `public_key_version`을 로드하세요.
***
## 복호화 및 서명
### 복호화 실패
* 오래되었거나 잘못된 **원시** 대화 키, 또는 잘못된 키 버전
* 불완전한 `encoded_event` 문자열
* 이벤트 유형이 복호화 가능한 콘텐츠로 처리할 수 있는 암호화된 메시지가 아님
### 서명 검증 실패
검증은 **기본적으로 실패-폐쇄**입니다(`reject_unverified = true`): SDK는 이미 검증되지 않은 서명 이벤트를 거부하므로, 여기서 실패가 발생한다면 검사를 켜야 한다는 뜻이 아니라 검증 입력이 잘못되었다는 뜻입니다. 일반적인 원인:
* **발신자**에 대한 서명 키 항목이 누락되었거나 불완전함 (Chat XDK가 요구하는 모든 필드—[Chat XDK](/xchat/xchat-xdk) 참조 참조)
* 발신자가 버전을 교체함—공개 키를 다시 가져오세요
* 허용된 최소값보다 낮은 키 버전은 절대 검증되지 않습니다
`set_reject_unverified` 세터는 이 기본값을 **비활성화**(`false`, 권장하지 않음)하기 위해 존재합니다. 이전에 비활성화했다면 실패-폐쇄 기본값으로 복원하세요:
```python theme={null}
chat.set_reject_unverified(True)
```
```typescript theme={null}
chat.setRejectUnverified(true);
```
```rust theme={null}
chat.set_reject_unverified(true);
```
```go theme={null}
chat.SetRejectUnverified(true)
```
```csharp theme={null}
chat.SetRejectUnverified(true);
```
```java theme={null}
chat.setRejectUnverified(true);
```
### 오래된 이벤트가 영구적으로 검증에 실패함
**오래된** 이벤트에서 `signature missing or no matching signing key`나 ECDSA 불일치 같은 오류는 영구적입니다. 서명은 불변이며 이벤트 자체에서 서명된 페이로드를 재구축하여 검증되므로, 다른 바이트로 서명된 (또는 서명되지 않은) 이벤트는 이후 로드 시마다 실패합니다—재시도, 키 갱신, 또는 API 호출로도 치유할 수 없습니다. 이러한 이벤트를 재시도 가능한 오류가 아닌 툼스톤으로 취급하세요. 대화 키를 교체하면 그 시점 이후부터 깨끗하고 검증 가능한 이력이 시작됩니다; 새 메시지는 영향을 받지 않습니다.
***
## 전송 페이로드 구축
이 실수들은 X Chat 암호화에 특화된 것입니다 (일반 HTTP 오류가 아님):
| 이슈 | 해결 |
| :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
| 잘못된 키 바이트 | API의 암호화된 키 문자열이 아니라 **원시** 대화 키 바이트를 Chat XDK에 전달하세요 |
| 잘못된 JSON 필드 이름 | `encrypted_content` → `encoded_message_create_event` 및 `encoded_event_signature` → `encoded_message_event_signature`로 매핑하세요 |
| 메시지 ID 누락 | `message_id`를 직접 생성하고 요청 본문에 같은 값을 보내세요 |
| 버전 불일치 | `conversation_key_version`을 사용하는 키에 맞추고; 서명 키 버전을 `set_key_version` / 공개 키 레코드에 맞추세요 |
| 경로 ID 형식 | URL 경로에는 여전히 하이픈으로 연결된 대화 ID가 필요합니다(`:` → `-`), 하지만 서명 시 SDK는 어떤 형태든 허용합니다: `A:B`, `A-B`(둘 중 어떤 순서든), 또는 그저 수신자 사용자 ID—모두 동일한 서명된 바이트로 정규화됩니다 |
### 상태 변경 호출에서 API가 400을 반환함
모든 상태 변경 채팅 호출—대화 키 추가 또는 교체, 그룹 생성, 멤버 추가—에는 API 경계에서 검증되는 요청 본문의 \*\*`action_signatures`\*\*가 필요합니다. 누락되거나 잘못된 형식의 항목(각각 `message_id`, `encoded_message_event_detail`, 그리고 `signature`, `public_key_version`, `signature_version`이 있는 `message_event_signature`가 필요함)은 즉시 HTTP 400 problem-details 응답을 반환합니다. SDK prepare 메서드(`prepare_conversation_key_change`, `prepare_group_create`, `prepare_group_members_change`)를 사용하고 반환된 **모든** 서명을 보내세요—그룹 생성과 멤버 추가는 두 개를 반환합니다.
***
## 미디어 암호화 및 복호화
* 첨부 파일을 참조하는 메시지와 **동일한** 대화 키(및 버전)를 사용하세요
* `decrypt_stream`을 실행하기 전까지 다운로드 응답을 **암호문**으로 취급하세요
* MIME 유형은 복호화 **후**에 추론하세요; 다운로드 `Content-Type`은 종종 실제 이미지 유형이 아닙니다
세부 사항: [미디어](/xchat/media).
***
## 안전한 디버깅
암호화 실패를 조사할 때:
* 대화 ID, 이벤트 ID, 키 **버전**만 로그에 남기세요
* 평문, 패스코드, 개인 키, 또는 전체 키 blob을 로그에 **남기지 마세요**
* `set_key_version`이 공개 키 레코드의 `public_key_version`과 일치하는지 확인하세요
* 불완전한 이력의 경우, 복호화하기 전에 키 변경 메타데이터를 건너뛰지 않도록 **모든** 이벤트 페이지를 페이지 처리하세요
# Chat XDK 참조
Source: https://docs.x.com/ko/xchat/xchat-xdk
지원 언어 전반에서 X Chat의 키 관리, 암호화, 복호화, 서명을 처리하는 암호화 SDK인 Chat XDK 레퍼런스입니다.
**Chat XDK**는 X Chat을 위한 키 관리, 암호화, 복호화 및 서명을 처리합니다. X HTTP API를 호출하지 **않습니다**—[Python](/xdks/python/overview) 또는 [TypeScript](/xdks/typescript/overview) **XDK**와 함께 사용하거나, 사용자 액세스 토큰과 HTTPS와 함께 사용하세요.
앱 안내: [시작하기](/xchat/getting-started). 샘플 봇: [chat-xdk/examples](https://github.com/xdevplatform/chat-xdk/tree/main/examples).
### 설치
```bash theme={null}
pip install chatxdk
```
PyPI 패키지는 `chatxdk`이며, `chat_xdk`로 임포트합니다. Python 3.10+ 필요.
```bash theme={null}
npm install @xdevplatform/chat-xdk
npm install juicebox-sdk # optional peer dependency — required for setup()/unlock() secure key backup
```
컴파일된 WASM 엔진이 패키지에 포함되어 있어 빌드 단계가 없습니다. Node.js 18+ 필요.
```toml theme={null}
[dependencies]
# chat-xdk-core is not yet on crates.io — use the git dependency.
# It exports both ChatCore and the async secure-key-backup Chat type.
chat-xdk-core = { git = "https://github.com/xdevplatform/chat-xdk", tag = "v0.2.1" }
# Required until thrift 0.24 is released on crates.io
[patch.crates-io]
thrift = { git = "https://github.com/apache/thrift.git", rev = "deb36fa409849de45973b04ffc3ce49d277ca90a" }
```
```bash theme={null}
go get github.com/xdevplatform/chat-xdk/go/chatxdk
```
미리 컴파일된 정적 라이브러리가 포함되어 있습니다 (macOS arm64/amd64, Linux amd64 glibc/musl). C 컴파일러는 필요하지만 Rust는 필요 없습니다. Go 1.21+ 필요.
```bash theme={null}
dotnet add package XDevPlatform.ChatXdk
```
패키지는 자체 완결형입니다. macOS (arm64, x64), Linux (x64), Windows (x64)용 네이티브 라이브러리가 포함되어 있습니다. .NET 8+ 필요.
```xml theme={null}
com.xchatxdk0.2.1
```
Maven Central에서 제공됩니다. jar에 macOS (arm64, x64), Linux (x64), Windows (x64)용 네이티브 라이브러리가 번들되어 있어 `jna.library.path` 설정이 필요 없습니다. `com.x.chatxdk`에서 임포트하세요. JDK 17+ 필요.
***
## 빠른 시작
백로그를 복호화하고, 키를 캐시하고, 이벤트 하나를 복호화하고, 회신을 암호화합니다. [시작하기](/xchat/getting-started)에서와 같이 전송 본문을 [`POST /2/chat/conversations/{id}/messages`](/x-api/chat/send-chat-message)에 연결하세요.
```python theme={null}
from chat_xdk import Chat
chat = Chat(juicebox_config_json) # or Chat() + import_keys(blob)
chat.unlock("YOUR_PASSCODE")
chat.set_key_version(signing_key_version)
result = chat.decrypt_events(raw_events, signing_keys)
for dm in result["messages"]:
ev = dm["event"]
if ev.get("type") == "Message":
print(ev.get("sender_id"), ev.get("content", {}).get("text"))
cached = result["conversation_keys"]["keys"]
event = chat.decrypt_event(one_event_b64, cached, sender_signing_keys)
raw_key = cached[result["conversation_keys"]["latest_version"]]
payload = chat.encrypt_message(
message_id, sender_id, conversation_id, raw_key, "Hi!",
conversation_key_version, signing_key_version,
)
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: juiceboxConfigJson,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(signingKeyVersion);
const result = chat.decryptEvents(rawEvents, signingKeys);
for (const dm of result.messages) {
if (dm.event.type === 'message') {
console.log(dm.event.senderId, dm.event.content?.text);
}
}
const cached = result.conversationKeys.keys;
const event = chat.decryptEvent(oneEventB64, cached, senderSigningKeys);
const rawKey = cached[result.conversationKeys.latestVersion!];
const payload = chat.encryptMessage({
messageId, senderId, conversationId, conversationKey: rawKey, text: 'Hi!',
conversationKeyVersion, signingKeyVersion,
});
```
```rust theme={null}
// ChatCore + import_keys, or chat_xdk_core::Chat + unlock().await
let result = chat.decrypt_events(&raw_events, &signing_keys);
let cached = &result.conversation_keys.keys;
let event = chat.decrypt_event(one_event_b64, cached, &sender_signing_keys)?;
// cached values are XChatConversationKey; encrypt_message wants owned bytes
let latest = result.conversation_keys.latest_version.as_deref().unwrap_or_default();
let conv_key = cached[latest].to_bytes();
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id, &sender_id, &conversation_id, conv_key, "Hi!",
&conversation_key_version, &signing_key_version,
))?;
```
```go theme={null}
chat := chatxdk.New()
defer chat.Close()
blob, _ := chatxdk.Base64ToBytes(privateKeysB64)
_ = chat.ImportKeys(blob)
chat.SetKeyVersion(signingKeyVersion)
result, err := chat.DecryptEvents(rawEvents, signingKeys)
cached := result.ConversationKeys.Keys
event, err := chat.DecryptEvent(oneEventB64, cached, senderSigningKeys)
rawKey := cached[*result.ConversationKeys.LatestVersion]
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawKey, Text: "Hi!",
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
})
_ = event
_ = payload
_ = err
```
```csharp theme={null}
using var chat = new Chat();
chat.ImportKeys(privateKeyBytes);
chat.SetKeyVersion(signingKeyVersion);
var result = chat.DecryptEvents(rawEvents, signingKeys);
var cached = result.ConversationKeys.Keys;
var evt = chat.DecryptEvent(oneEventB64, cached, senderSigningKeys);
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId, SenderId = senderId, ConversationId = conversationId,
ConversationKey = rawKey, Text = "Hi!",
ConversationKeyVersion = conversationKeyVersion, SigningKeyVersion = signingKeyVersion,
});
```
```java theme={null}
try (Chat chat = new Chat()) {
chat.importKeys(privateKeyBytes);
chat.setKeyVersion(signingKeyVersion);
DecryptEventsResult result = chat.decryptEvents(rawEvents, signingKeys);
Map cached = result.conversationKeys.keys;
JsonNode event = chat.decryptEvent(oneEventB64, cached, senderSigningKeys);
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawKey;
params.text = "Hi!";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
}
```
***
## 라이프사이클 및 키
SDK를 구성하고, 개인 키를 저장하며(패스코드로 보호되는 보안 키 백업 또는 로컬 키 blob), Chat API에 **공개** 키를 등록하고, 잠금 해제 또는 가져오기 후 등록된 **공개 키 버전**을 설정하세요. 보안 키 백업은 **Juicebox**로 구현되어 있으며, 관련 구성 필드가 그 이름을 갖는 것도 그 때문입니다. 기기/앱 신원당 한 번 `generate_keypairs`를 호출하고, 등록 페이로드를 공개 키 엔드포인트에 POST하세요. 모든 바인딩에서 보안 키 백업을 위해 `setup` / `unlock`(및 관련 패스코드 헬퍼)을 사용하세요. `export_keys` / `import_keys`(봇 및 서버용 원시 키 blob 지속)는 **네이티브 바인딩에서만** 사용 가능합니다—Python, Go, .NET, JVM, Rust. JS/WASM 바인딩은 원시 키 내보내기 또는 가져오기를 노출하지 않습니다: 브라우저에서 인스턴스에 접근하는 모든 스크립트가 신원을 유출할 수 있으므로, JS는 키를 보안 키 백업 내부에 유지합니다. 요청당 백업 realm 왕복을 피하고자 하는 JS 서버는 요청 전반에 걸쳐 잠금 해제된 하나의 `Chat` 인스턴스를 재사용하거나, 키 blob이 지원되는 네이티브 바인딩을 실행해야 합니다.
```python theme={null}
from chat_xdk import Chat
# Secure key backup (client)
chat = Chat(juicebox_config_json)
chat.setup("YOUR_PASSCODE") # first time — generates keypairs
# chat.unlock("YOUR_PASSCODE") # later sessions
chat.set_key_version(version) # from add-public-key / get-public-keys response
reg = chat.get_public_keys() # or registration fields from generate_keypairs
# Key blob (server / bot)
chat2 = Chat()
chat2.import_keys(secret_blob)
chat2.set_key_version(version)
blob = chat2.export_keys() # treat as a password
```
```typescript theme={null}
import { createChat } from '@xdevplatform/chat-xdk';
const chat = await createChat({
juiceboxConfig: juiceboxConfigJson,
getAuthToken: async (realmId) => getRealmToken(realmId),
});
await chat.setup('YOUR_PASSCODE');
// await chat.unlock('YOUR_PASSCODE');
chat.setKeyVersion(version);
const publics = chat.getPublicKeys();
// JS/WASM stores keys only through secure key backup — there is no raw key
// export/import here. For key-blob persistence, use a native binding.
```
```rust theme={null}
// chat_xdk_core::Chat — async secure key backup unlock, or ChatCore + import_keys
chat.setup("YOUR_PASSCODE").await?;
// chat.unlock("YOUR_PASSCODE").await?;
chat.set_key_version(&version);
let publics = chat.get_public_keys()?;
let blob = chat.export_keys()?;
chat.import_keys(&blob)?;
```
```go theme={null}
chat := chatxdk.New()
defer chat.Close()
// Prefer ImportKeys for servers; secure key backup unlock where supported
keyBlob, _ := chatxdk.Base64ToBytes(privateKeysB64)
if err := chat.ImportKeys(keyBlob); err != nil {
log.Fatal(err)
}
chat.SetKeyVersion(version)
publics, err := chat.GetPublicKeys()
blob, err := chat.ExportKeys()
_ = publics
_ = blob
_ = err
```
```csharp theme={null}
using var chat = new Chat();
chat.ImportKeys(privateKeyBytes);
// or secure key backup setup / unlock when config is available
chat.SetKeyVersion(version);
var publics = chat.GetPublicKeys();
var blob = chat.ExportKeys();
```
```java theme={null}
try (Chat chat = new Chat()) {
chat.importKeys(privateKeyBytes);
chat.setKeyVersion(version);
var publics = chat.getPublicKeys();
byte[] blob = chat.exportKeys();
}
```
보안 키 백업 구성은 세 가지 형태를 허용합니다: X API의 `juicebox_config` 객체(권장—그대로 전달), 전체 `sdk_config` 래퍼, 또는 순수한 `token_map`.
선택 사항: 서명 검증은 **기본적으로 켜져 있습니다**(`reject_unverified = true`)—비활성화하려면 `set_reject_unverified(false)`를 호출하세요(권장하지 않음); 백업 realm 구성이 변경되면 `update_config`; UI 상태를 위해 `is_unlocked` / `has_identity_key`. 전체 필드 목록은 [chat-xdk 저장소](https://github.com/xdevplatform/chat-xdk)의 스텁에 있습니다.
***
## 대화 키
세 가지 **prepare** 메서드는 각각 하나의 호출로 키 변경에 필요한 모든 것을 수행합니다: 새 대화 키를 생성하고, 각 참가자(전달한 공개 키에서)에 대해 암호화하고, 변경 사항에 서명합니다. 모두 동일한 **`PreparedConversationChange`** 형태를 반환하며, POST할 준비가 되어 있습니다—`conversation_participant_keys`에서 SDK 필드 `encrypted_key`를 \*\*`encrypted_conversation_key`\*\*로 이름을 바꾸고, action signature를 필수 **`action_signatures`** 본문 필드로 매핑하세요.
| 시나리오 | 메서드 | 반환되는 action signature |
| :------------------------------------------------------------ | :-------------------------------- | :-------------------- |
| 1:1 시작(대화 ID 생략—SDK가 파생함) 또는 어떤 대화의 키든 교체(ID 전달) | `prepare_conversation_key_change` | 1 |
| 그룹 생성 (`POST /2/chat/conversations/group/initialize`로 발급된 ID) | `prepare_group_create` | 2—둘 다 전송 |
| 그룹에 멤버 추가 | `prepare_group_members_change` | 2—둘 다 전송 |
`encrypt_message`와 미디어를 위해 **원시** 키 바이트를 보관하세요; API의 암호화된 봉투를 암호화에 전달하지 마세요.
**래핑하기 전에 가져온 키를 검증하세요.** prepare 메서드는 전달된 공개 키로 새 대화 키를 암호화합니다. 대체된 신원 키가 대화 키를 받지 못하도록, 전달하기 전에 각 가져온 레코드—공개 키 API의 `public_key`, `signing_public_key`, `identity_public_key_signature` 필드—에 대해 `verify_key_binding(identity, signing, signature)`를 호출하세요.
`{ keys, latest_version }`를 재구축하려면 키 변경 이벤트 페이로드에 `extract_conversation_keys`를 사용하세요. `decrypt_conversation_key`는 단일 ECIES blob을 언래핑합니다.
```python theme={null}
# One entry per participant public key, from the public-keys API:
# participants = [
# {"user_id": "1215441834412953600", "public_key": "BASE64_IDENTITY_PUBLIC_KEY", "key_version": "1733889755256"},
# {"user_id": "1843439638876491776", "public_key": "BASE64_IDENTITY_PUBLIC_KEY", "key_version": "1766181805686"},
# ]
prepared = chat.prepare_conversation_key_change(my_user_id, signing_key_version, participants)
# prepared["conversation_key"] — raw bytes for encrypt_message
# prepared["participant_keys"] — per-user wraps; rename encrypted_key → encrypted_conversation_key on POST
# prepared["action_signatures"] — required on the POST body
extracted = chat.extract_conversation_keys(key_change_blobs)
keys = extracted["keys"]
latest = extracted["latest_version"]
raw = keys[latest]
one = chat.decrypt_conversation_key(encrypted_blob)
```
```typescript theme={null}
const prepared = chat.prepareConversationKeyChange({
senderId: myUserId, signingKeyVersion, publicKeys: participants,
});
// prepared.conversationKey — Uint8Array for encryptMessage
// prepared.participantKeys / prepared.actionSignatures — POST body fields
const extracted = chat.extractConversationKeys(keyChangeBlobs);
const raw = extracted.keys[extracted.latestVersion!];
const one = chat.decryptConversationKey(encryptedBlob);
```
```rust theme={null}
let prepared = chat.prepare_conversation_key_change(
ConversationKeyChangeParams::new(&my_user_id, &signing_key_version, participants),
)?;
let extracted = chat.extract_conversation_keys(&key_change_blobs);
let latest = extracted.latest_version.as_deref().unwrap_or_default();
let raw = &extracted.keys[latest];
let one = chat.decrypt_conversation_key(&encrypted_blob)?;
```
```go theme={null}
prepared, err := chat.PrepareConversationKeyChange(chatxdk.ConversationKeyChangeParams{
SenderID: myUserID, SigningKeyVersion: signingKeyVersion, PublicKeys: participants,
})
// prepared.ConversationKey feeds EncryptMessage
// prepared.ParticipantKeys / prepared.ActionSignatures — POST body fields
extracted, err := chat.ExtractConversationKeys(keyChangeBlobs)
one, err := chat.DecryptConversationKey(encryptedBlob)
_ = prepared
_ = extracted
_ = one
_ = err
```
```csharp theme={null}
var prepared = chat.PrepareConversationKeyChange(new ConversationKeyChangeParams {
SenderId = myUserId, SigningKeyVersion = signingKeyVersion, PublicKeys = participants,
});
var extracted = chat.ExtractConversationKeys(keyChangeBlobs);
var raw = extracted.Keys[extracted.LatestVersion];
var one = chat.DecryptConversationKey(encryptedBlob);
```
```java theme={null}
ConversationKeyChangeParams keyParams = new ConversationKeyChangeParams();
keyParams.senderId = myUserId;
keyParams.signingKeyVersion = signingKeyVersion;
keyParams.publicKeys = participants;
PreparedConversationChange prepared = chat.prepareConversationKeyChange(keyParams);
ConversationKeyBundle extracted = chat.extractConversationKeys(keyChangeBlobs);
byte[] raw = extracted.keys.get(extracted.latestVersion);
byte[] one = chat.decryptConversationKey(encryptedBlob);
```
그룹 생성 및 멤버 추가의 경우, 각 메서드가 필요로 하는 매개변수를 전달하세요(`prepare_group_create`에는 멤버/관리자 ID 목록; `prepare_group_members_change`에는 새 로스터와 현재 로스터)—샘플은 [그룹](/xchat/groups#create-the-group-and-establish-keys)을 참조하세요. 둘 다 **두 개**의 action signature를 반환합니다; POST는 둘 다 포함해야 합니다.
***
## 복호화
\*\*`decrypt_events`\*\*는 이력과 백로그용입니다: 스트림에서 대화 키를 가져오고, 복호화된 메시지를 반환하며, 전체 배치가 실패하는 대신 이벤트별 오류를 **수집**합니다. \*\*`decrypt_event`\*\*는 이미 키 캐시가 있을 때 단일 실시간 이벤트용입니다; 실패 시 예외를 발생/던집니다.
SDK가 발신자를 검증할 수 있도록 **서명 키**를 전달하세요. API 공개 키 필드를 `SigningKeyEntry`에 매핑합니다: `public_key_version` → `public_key_version`(같은 이름), `signing_public_key` → `public_key`, `public_key` → `identity_public_key`, 그리고 `identity_public_key_signature`와 `user_id`. 검증은 기본적으로 필수입니다: 서명 키 목록을 생략하거나 빈 목록을 전달해도 이를 건너뛰지 **않습니다**—서명된 이벤트는 실패합니다(`decrypt_events`의 경우 `errors`에 수집, `decrypt_event`의 경우 던져짐). 실제로 검증을 건너뛰려면 먼저 `set_reject_unverified(false)`를 호출해야 합니다(프로덕션에서는 권장하지 않음).
```python theme={null}
signing_keys = [{
"user_id": uid,
"public_key_version": row["public_key_version"],
"public_key": row["signing_public_key"],
"identity_public_key": row["public_key"],
"identity_public_key_signature": row["identity_public_key_signature"],
} for row in api_public_keys]
result = chat.decrypt_events(raw_events, signing_keys)
for idx, msg in (result.get("errors") or {}).items():
log.warning("event %s failed: %s", idx, msg)
for dm in result["messages"]:
ev = dm["event"]
if ev.get("type") == "Message":
text = ev.get("content", {}).get("text")
cached = result["conversation_keys"]["keys"]
live = chat.decrypt_event(one_event_b64, cached, signing_keys_for_sender)
```
```typescript theme={null}
const signingKeys = apiPublicKeys.map((row) => ({
userId: uid,
publicKeyVersion: row.public_key_version,
publicKey: row.signing_public_key,
identityPublicKey: row.public_key,
identityPublicKeySignature: row.identity_public_key_signature,
}));
const result = chat.decryptEvents(rawEvents, signingKeys);
for (const [idx, msg] of Object.entries(result.errors ?? {})) {
console.warn(`event ${idx} failed: ${msg}`);
}
const cached = result.conversationKeys.keys;
const live = chat.decryptEvent(oneEventB64, cached, signingKeysForSender);
```
```rust theme={null}
let result = chat.decrypt_events(&raw_events, &signing_keys);
for (idx, msg) in &result.errors {
eprintln!("event {idx} failed: {msg}");
}
let cached = &result.conversation_keys.keys;
let live = chat.decrypt_event(one_event_b64, cached, &signing_keys_for_sender)?;
```
```go theme={null}
result, err := chat.DecryptEvents(rawEvents, signingKeys)
for idx, msg := range result.Errors {
log.Printf("event %s failed: %s", idx, msg)
}
cached := result.ConversationKeys.Keys
live, err := chat.DecryptEvent(oneEventB64, cached, signingKeysForSender)
_ = live
_ = err
```
```csharp theme={null}
var result = chat.DecryptEvents(rawEvents, signingKeys);
foreach (var kv in result.Errors) { /* kv.Key = event index, kv.Value = error */ }
var cached = result.ConversationKeys.Keys;
var live = chat.DecryptEvent(oneEventB64, cached, signingKeysForSender);
```
```java theme={null}
DecryptEventsResult result = chat.decryptEvents(rawEvents, signingKeys);
Map cached = result.conversationKeys.keys;
JsonNode live = chat.decryptEvent(oneEventB64, cached, signingKeysForSender);
```
***
## 암호화 및 전송 헬퍼
\*\*`encrypt_message`\*\*는 텍스트 메시지를 위한 서명된 암호문을 만듭니다(선택적 엔티티, `media_hash_key`를 통한 첨부, TTL, 알림 플래그). 반환된 페이로드를 메시지 전송 본문에 매핑하세요: `encrypted_content` → **`encoded_message_create_event`**, `encoded_event_signature` → **`encoded_message_event_signature`**, 그리고 **`message_id`**.
회신과 반응에는 **`encrypt_reply`**, **`encrypt_add_reaction`**, \*\*`encrypt_remove_reaction`\*\*을 사용하세요(`sequence_id`는 부모를 대상으로 함). \*\*`encrypt` / `decrypt`\*\*는 대화 키 아래의 UTF-8 메타데이터용입니다(예: 암호화된 그룹 이름)—메시지 봉투용이 아닙니다. \*\*`encrypt_stream` / `decrypt_stream`\*\*은 첨부 바이트를 암호화합니다; [미디어](/xchat/media) 참조. 저수준 \*\*`sign` / `verify` / `verify_key_binding`\*\*은 고급 흐름을 지원합니다; 대화 키 변경, 그룹 생성, 멤버 추가는 [prepare 메서드](#conversation-keys)에 의해 서명됩니다.
`encrypt_message` / `encrypt_reply`에 전달되는 대화 ID는 보유하고 있는 어떤 형태든 될 수 있습니다—이벤트의 `A:B`, 목록이나 URL 경로의 `A-B`(어떤 순서든), 또는 순수한 수신자 사용자 ID—SDK가 서명 전에 정규화합니다. 그룹 ID(`g` 접두사)는 그대로 통과됩니다.
```python theme={null}
payload = chat.encrypt_message(
message_id, sender_id, conversation_id, raw_conversation_key, "Hello",
conversation_key_version, signing_key_version,
# Optional keyword args: entities, attachments, should_notify, ttl_msec
)
body = {
"message_id": message_id,
"encoded_message_create_event": payload["encrypted_content"],
"encoded_message_event_signature": payload["encoded_event_signature"],
}
# POST body to /2/chat/conversations/{id}/messages
reply = chat.encrypt_reply(
reply_message_id, sender_id, conversation_id, raw_conversation_key,
"Sounds good", conversation_key_version, signing_key_version,
parent_sequence_id, # reply_to_sequence_id — the message being replied to
)
name_ct = chat.encrypt("Group title", raw_conversation_key)
title = chat.decrypt(name_ct, raw_conversation_key)
```
```typescript theme={null}
const payload = chat.encryptMessage({
messageId, senderId, conversationId, conversationKey: rawConversationKey, text: 'Hello',
conversationKeyVersion, signingKeyVersion,
});
const body = {
message_id: messageId,
encoded_message_create_event: payload.encryptedContent,
encoded_message_event_signature: payload.encodedEventSignature,
};
const reply = chat.encryptReply({
messageId: replyMessageId, senderId, conversationId, conversationKey: rawConversationKey,
text: 'Sounds good', conversationKeyVersion, signingKeyVersion,
replyToSequenceId: parentSequenceId, // the message being replied to
});
const nameCt = chat.encrypt('Group title', rawConversationKey);
const title = chat.decrypt(nameCt, rawConversationKey);
```
```rust theme={null}
// conv_key: XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let payload = chat.encrypt_message(EncryptMessageParams::new(
&message_id, &sender_id, &conversation_id, conv_key.to_bytes(), "Hello",
&conversation_key_version, &signing_key_version,
))?;
// Map payload fields into the send-message JSON body as above
let name_ct = chat.encrypt("Group title", &conv_key)?;
let title = chat.decrypt(&name_ct, &conv_key)?;
```
```go theme={null}
payload, err := chat.EncryptMessage(chatxdk.EncryptMessageParams{
MessageID: messageID, SenderID: senderID, ConversationID: conversationID,
ConversationKey: rawKey, Text: "Hello",
ConversationKeyVersion: conversationKeyVersion, SigningKeyVersion: signingKeyVersion,
})
// body: message_id, encoded_message_create_event, encoded_message_event_signature
nameCt, err := chat.Encrypt("Group title", rawKey)
title, err := chat.Decrypt(nameCt, rawKey)
_ = payload
_ = title
_ = err
```
```csharp theme={null}
var payload = chat.EncryptMessage(new EncryptMessageParams {
MessageId = messageId, SenderId = senderId, ConversationId = conversationId,
ConversationKey = rawKey, Text = "Hello",
ConversationKeyVersion = conversationKeyVersion, SigningKeyVersion = signingKeyVersion,
});
// Map EncryptedContent / EncodedEventSignature into the send-message body
var nameCt = chat.Encrypt("Group title", rawKey);
var title = chat.Decrypt(nameCt, rawKey);
```
```java theme={null}
EncryptMessageParams params = new EncryptMessageParams();
params.messageId = messageId;
params.senderId = senderId;
params.conversationId = conversationId;
params.conversationKey = rawKey;
params.text = "Hello";
params.conversationKeyVersion = conversationKeyVersion;
params.signingKeyVersion = signingKeyVersion;
SendPayload payload = chat.encryptMessage(params);
// Map to encoded_message_create_event / encoded_message_event_signature on POST
String nameCt = chat.encrypt("Group title", rawKey);
String title = chat.decrypt(nameCt, rawKey);
```
***
## 미디어 스트림
텍스트에 사용된 것과 **동일한** 대화 키로 파일 바이트를 암호화하고, Chat 미디어 API를 통해 업로드하며, `encrypt_message`에 \*\*`media_hash_key`\*\*를 첨부하세요. 이것은 Posts 미디어 모델(`expansions=attachments.media_keys`)이 아닙니다. 전체 업로드/다운로드 흐름: [미디어](/xchat/media).
```python theme={null}
ciphertext = chat.encrypt_stream(file_bytes, raw_conversation_key)
# Upload `ciphertext`; the `media_hash_key` you attach on encrypt_message
# comes from the media-upload finalize step, not from encrypt_stream.
plain = chat.decrypt_stream(ciphertext, raw_conversation_key)
```
```typescript theme={null}
const ciphertext = chat.encryptStream(fileBytes, rawConversationKey);
// Upload `ciphertext`; mediaHashKey comes from the upload finalize step.
const plain = chat.decryptStream(ciphertext, rawConversationKey);
```
```rust theme={null}
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let ciphertext = chat.encrypt_stream(&file_bytes, &conv_key)?;
let plain = chat.decrypt_stream(&ciphertext, &conv_key)?;
```
```go theme={null}
ciphertext, err := chat.EncryptStream(fileBytes, rawKey)
plain, err := chat.DecryptStream(ciphertext, rawKey)
_ = plain
_ = err
```
```csharp theme={null}
var ciphertext = chat.EncryptStream(fileBytes, rawKey);
var plain = chat.DecryptStream(ciphertext, rawKey);
```
```java theme={null}
byte[] ciphertext = chat.encryptStream(fileBytes, rawKey);
byte[] plain = chat.decryptStream(ciphertext, rawKey);
```
### 큰 미디어를 위한 증분 스트리밍
큰 파일의 경우, 전체 페이로드를 메모리에 보관하지 마세요: `stream_encryptor()` / `stream_decryptor()`는 청크(각 약 1 MB)로 `push(chunk)`를 통해 공급한 다음 마지막에 `finish()`를 한 번 호출하는 `StreamEncryptor` / `StreamDecryptor`를 반환합니다. 복호화 시 `finish()`는 잘린 스트림을 감지합니다(마지막 프레임 전에 입력이 끝났으면 실패), 그러므로 성공하기 전까지 푸시된 평문을 완료된 것으로 취급하지 마세요.
**JS/WASM 전용:** `finish()`는 기본 WASM 객체를 소비하고 해제합니다—`finish()` 후에는 절대 `free()`를 호출하지 마세요(예외를 던집니다). `finish()` *이전*에 스트림을 포기하는 경우에만 `free()`를 호출하세요(예: 오류 경로에서).
```python theme={null}
enc = chat.stream_encryptor(raw_conversation_key)
chunks = [enc.push(chunk) for chunk in read_in_chunks(file_bytes, 1 << 20)]
chunks.append(enc.finish())
ciphertext = b"".join(chunks)
dec = chat.stream_decryptor(raw_conversation_key)
out = [dec.push(chunk) for chunk in read_in_chunks(ciphertext, 1 << 20)]
out.append(dec.finish()) # raises on truncation
plain = b"".join(out)
```
```typescript theme={null}
const enc = chat.streamEncryptor(rawConversationKey);
const parts: Uint8Array[] = [];
try {
for (const chunk of readInChunks(fileBytes, 1 << 20)) parts.push(enc.push(chunk));
parts.push(enc.finish()); // consumes + frees enc — do not call enc.free() after this
} catch (e) {
enc.free(); // only when abandoning before finish()
throw e;
}
const ciphertext = concat(parts);
```
***
## 유틸리티
Base64/hex 헬퍼, MIME 감지, 이미지 치수는 모듈 수준 함수(Python/JS/Rust/Go) 또는 `ChatXdkUtilities`(C#/Java)로 사용할 수 있습니다—추가 라이브러리를 가져오지 않고 첨부 파일 메타데이터를 구축할 때 유용합니다.
```python theme={null}
from chat_xdk import (
bytes_to_base64, base64_to_bytes, bytes_to_hex, hex_to_bytes,
detect_mime_type, detect_image_dimensions,
)
b64 = bytes_to_base64(raw)
raw2 = base64_to_bytes(b64)
hexed = bytes_to_hex(raw)
raw3 = hex_to_bytes(hexed)
mime = detect_mime_type(file_bytes)
w, h = detect_image_dimensions(file_bytes)
```
```typescript theme={null}
import { bytesToBase64, base64ToBytes, bytesToHex, hexToBytes, detectMimeType, detectImageDimensions } from '@xdevplatform/chat-xdk';
const b64 = bytesToBase64(raw);
const raw2 = base64ToBytes(b64);
const hexed = bytesToHex(raw);
const raw3 = hexToBytes(hexed);
const mime = detectMimeType(fileBytes);
const dims = detectImageDimensions(fileBytes);
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;
```
```rust theme={null}
let b64 = chat_xdk_core::bytes_to_base64(&raw);
let raw2 = chat_xdk_core::base64_to_bytes(&b64)?;
let hexed = chat_xdk_core::bytes_to_hex(&raw);
let raw3 = chat_xdk_core::hex_to_bytes(&hexed);
let mime = chat_xdk_core::detect_mime_type(&file_bytes);
let dims = chat_xdk_core::detect_image_dimensions(&file_bytes);
let (w, h) = dims.map(|d| (d.width, d.height)).unwrap_or((0, 0));
```
```go theme={null}
b64, _ := chatxdk.BytesToBase64(raw)
raw2, err := chatxdk.Base64ToBytes(b64)
hexed, err := chatxdk.BytesToHex(raw)
raw3, err := chatxdk.HexToBytes(hexed)
mime, _ := chatxdk.DetectMimeType(fileBytes)
dims, _ := chatxdk.DetectImageDimensions(fileBytes)
w, h := dims.Width, dims.Height
_ = b64
_ = raw2
_ = hexed
_ = raw3
_ = mime
_ = w
_ = h
_ = err
```
```csharp theme={null}
var b64 = ChatXdkUtilities.BytesToBase64(raw);
var raw2 = ChatXdkUtilities.Base64ToBytes(b64);
var hexed = ChatXdkUtilities.BytesToHex(raw);
var raw3 = ChatXdkUtilities.HexToBytes(hexed);
var mime = ChatXdkUtilities.DetectMimeType(fileBytes);
var dims = ChatXdkUtilities.DetectImageDimensions(fileBytes);
var w = dims?.Width ?? 0;
var h = dims?.Height ?? 0;
```
```java theme={null}
String b64 = ChatXdkUtilities.bytesToBase64(raw);
byte[] raw2 = ChatXdkUtilities.base64ToBytes(b64);
String hexed = ChatXdkUtilities.bytesToHex(raw);
byte[] raw3 = ChatXdkUtilities.hexToBytes(hexed);
String mime = ChatXdkUtilities.detectMimeType(fileBytes);
ImageDimensions wh = ChatXdkUtilities.detectImageDimensions(fileBytes);
long width = wh.width, height = wh.height;
```
***
## 중요한 타입
이러한 개념적 타입은 언어 전반에 걸쳐 나타납니다(정확한 필드 이름은 다릅니다; JS는 종종 `message`와 같은 camelCase 이벤트 판별자를 사용합니다):
* **SendPayload** — `encrypt_message` 및 관련 암호화 헬퍼의 반환값; Chat API 전송 본문에 매핑.
* **PublicKeyRegistrationPayload** — 공개 키 추가 API를 위한 `generate_keypairs` / 공개 키 게터의 출력.
* **SigningKeyEntry** — 서명 검증을 위해 복호화에 전달되는 발신자 공개 자료.
* **PreparedConversationChange** — 세 가지 prepare 메서드의 출력: 파생되거나 전달된 `conversation_id`, 원시 `conversation_key` 바이트, `conversation_key_version`, `participant_keys`(`user_id`, `encrypted_key`, `public_key_version`), 그리고 `action_signatures`(`message_id`, `encoded_message_event_detail`, `signature`, `signature_version`, `public_key_version`, 선택적 `signature_payload`—키 변경 서명에서는 해당 페이로드가 평문 키를 포함하므로 생략됨).
* **DecryptEventsResult** — 메시지, 선택적 오류, 그리고 추출된 `conversation_keys`.
전체 필드 목록은 [chat-xdk 저장소](https://github.com/xdevplatform/chat-xdk)의 언어 스텁(`docs/API.md`, `*.pyi`, `index.d.ts`)을 사용하세요.
***
## 오류
Python은 일반적으로 설명적인 메시지와 함께 \*\*`ValueError`\*\*를 발생시킵니다(예: 잘못된 패스코드). TypeScript/JavaScript는 \*\*`Error`\*\*를 던집니다. Go는 `(value, error)`를 반환합니다. 이력의 경우 하나의 잘못된 이벤트가 배치를 중단시키지 않도록 \*\*`decrypt_events`\*\*를 선호하세요; 부분적 실패에 대해서는 errors 컬렉션을 검사하세요.
일부 검증 오류는 **영구적**입니다. 서명은 불변이며 이벤트 자체에서 서명된 페이로드를 재구축하여 검증되므로, `signature missing or no matching signing key` 또는 ECDSA 불일치로 실패하는 오래된 이벤트는 이후 로드 시마다 실패합니다—재시도, 키 갱신, 또는 API 호출로도 치유할 수 없습니다. 이러한 것을 일시적 오류가 아닌 툼스톤으로 취급하세요. 대화 키를 교체하면 그 시점 이후부터 깨끗하고 검증 가능한 이력이 시작됩니다.
***
## 다음 단계
Chat XDK를 Chat API에 연결하기
스트림 암호화 및 미디어 REST
웹훅 및 활동 전달
일반적인 실패
# X Developer Platform Livestreams
Source: https://docs.x.com/livestreams
Watch recordings of X Developer Platform livestreams, including product walkthroughs, technical deep dives, AMA sessions, and integration tutorials.
View recordings and replays of previous broadcasts about the X Developer Platform, designed to help the developer community learn and build with our tools.
These include deep dives, getting started guides, and more.
## Past broadcasts
# Make Your First Request
Source: https://docs.x.com/make-your-first-request
Send your first X API v2 request in minutes using cURL or Postman, including authentication, endpoint selection, and parsing the JSON response.
This guide walks you through making your first X API request. You'll need a [developer account with app credentials](/x-api/getting-started/getting-access) before starting.
***
## Quick start with cURL
The fastest way to test the API is with cURL. Let's look up a user:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Replace `$BEARER_TOKEN` with your actual Bearer Token. You'll get a response like:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Step-by-step guide
In the [Developer Console](https://console.x.com), navigate to your app and copy the Bearer Token.
Start with one of these beginner-friendly endpoints:
| Endpoint | What it does |
| :------------------------------------------------ | :--------------------------------- |
| [User lookup](/x-api/users/lookup/introduction) | Get user profile by username or ID |
| [Post lookup](/x-api/posts/lookup/introduction) | Get post by ID |
| [Recent search](/x-api/posts/search/introduction) | Search posts from the last 7 days |
Use cURL, Postman, or your preferred HTTP client:
```bash theme={null}
# Look up a user by username
curl "https://api.x.com/2/users/by/username/xdevelopers" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Responses are JSON. The primary data is in the `data` field:
```json theme={null}
{
"data": {
"id": "2244994945",
"name": "X Developers",
"username": "xdevelopers"
}
}
```
***
## Request more data with fields
By default, endpoints return minimal fields. Use the `fields` parameter to request additional data:
```bash theme={null}
curl "https://api.x.com/2/users/by/username/xdevelopers?user.fields=created_at,description,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
Response:
```json 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 Platform",
"public_metrics": {
"followers_count": 570842,
"following_count": 2048,
"tweet_count": 14052,
"listed_count": 1672
}
}
}
```
[Learn more about fields →](/x-api/fundamentals/fields)
***
## More examples
```bash theme={null}
curl "https://api.x.com/2/tweets/1460323737035677698?tweet.fields=created_at,public_metrics" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/tweets/search/recent?query=from:xdevelopers&tweet.fields=created_at" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
```bash theme={null}
curl "https://api.x.com/2/users/2244994945/tweets?max_results=5" \
-H "Authorization: Bearer $BEARER_TOKEN"
```
***
## Using code instead of cURL
```python theme={null}
import requests
bearer_token = "YOUR_BEARER_TOKEN"
url = "https://api.x.com/2/users/by/username/xdevelopers"
headers = {"Authorization": f"Bearer {bearer_token}"}
response = requests.get(url, headers=headers)
print(response.json())
```
```javascript theme={null}
const bearerToken = "YOUR_BEARER_TOKEN";
const url = "https://api.x.com/2/users/by/username/xdevelopers";
fetch(url, {
headers: { Authorization: `Bearer ${bearerToken}` }
})
.then(res => res.json())
.then(data => console.log(data));
```
For production use, we recommend the official SDKs:
* [Python SDK](/xdks/python/overview)
* [TypeScript SDK](/xdks/typescript/overview)
They handle authentication, pagination, and rate limiting automatically.
***
## Tools for testing
Visual API testing with our collection.
Examples in multiple languages.
Full endpoint documentation.
***
## Troubleshooting
* Check that your Bearer Token is correct
* Ensure the token hasn't been regenerated
* Verify the `Authorization` header format: `Bearer YOUR_TOKEN`
* Your app may not have access to this endpoint
* Some endpoints require user-context authentication (OAuth 1.0a or 2.0)
* Check your app's permissions in the Developer Console
* You've hit a rate limit
* Check the `x-rate-limit-reset` header for when to retry
* Implement exponential backoff in your code
[Full error reference →](/x-api/fundamentals/response-codes-and-errors)
***
## Next steps
Understand OAuth for user-context requests.
Discover what you can build.
Faster development with official libraries.
Ideas for what to create.
# Subscribe to developer news
Source: https://docs.x.com/newsletter
Subscribe to the X Developer Platform newsletter for product updates, new endpoints, deprecations, events, and other news for API developers.
Sign up for emails about the latest news, product updates, and events from the X Developer team.
# X Developer Platform
Source: https://docs.x.com/overview
Build, analyze, and innovate with X's real-time global data. Access posts, users, trends, and more through modern APIs with flexible pay-per-usage pricing.
## Products
Choose the access level that fits your needs.
Credit-based pricing with no commitments. Pay only for what you use.
High-volume endpoints, dedicated account management, and custom rate limits.
Earn free [xAI API](https://docs.x.ai) credits when you purchase X API credits — up to 20% back based on your spend. [Learn more](/x-api/getting-started/pricing#free-xai-api-credits)
***
## Get started
Owned Reads let you access your own data at reduced cost. Requests for your own posts, bookmarks, followers, likes, and more are priced at \$0.001 per resource.
Get your API keys and make your first request in minutes.
Explore endpoints for posts, users, spaces, DMs, lists, and more.
Official Python and TypeScript SDKs for faster development.
***
## Resources
Step-by-step guides for common use cases and integrations.
Official SDKs and community libraries for every language.
Get help from the community and X team.
llms.txt, skill.md, MCP servers, and resources for AI-powered development.
***
## Other products
Programmatically manage ad campaigns, targeting, creatives, and analytics.
# Registro de alterações
Source: https://docs.x.com/pt/changelog
Notas de versão e histórico de versões da X API v2, das APIs Enterprise, da Ads API, dos SDKs, do streaming, dos webhooks e da plataforma para desenvolvedores.
Para se inscrever para receber atualizações, [**"Ative as notificações"**](https://help.x.com/en/managing-your-account/notifications-on-mobile-devices#:~:text=In%20the%20top%20menu,%20you,you%20would%20like%20to%20receive) para [**@API**](https://x.com/api). Você também pode acompanhar este registro de alterações no seu leitor de feeds por meio do [**feed RSS**](https://docs.x.com/changelog/rss.xml).
### Endpoints de rascunho e publicação de Articles
Hoje, adicionamos [novos endpoints](/x-api/articles/introduction) para rascunhar e publicar Articles via X API.
### Eventos de criação e exclusão de Posts para a X Activity API
Hoje, adicionamos os eventos `post.create` e `post.delete` à [X Activity API](https://docs.x.com/x-api/activity/introduction). Agora você pode se inscrever por ID de usuário para receber notificações em tempo real quando um usuário cria ou exclui um Post.
Para atividade básica de Posts por usuário, use a XAA. Para filtragem avançada por palavras-chave e o conjunto completo de operadores do Filtered Stream, continue usando o [Filtered Stream](/x-api/posts/filtered-stream/introduction).
### Campo `paid_partnership` de Post
Adicionamos suporte para o campo `paid_partnership` em Posts.
* Ao criar um Post via `POST /2/tweets`, defina `"paid_partnership": true` para indicar que o Post é uma parceria paga (ou seja, o autor está declarando que ele contém promoção paga). O Post será rotulado como promoção paga.
* Ao ler Posts, solicite `tweet.fields=paid_partnership` para recuperar o valor (`true` se o autor declarou que o Post contém promoção paga).
### Endpoints de pesquisa migrando para o novo índice de pesquisa
Hoje, migramos os endpoints de pesquisa da X API v2 (`/2/tweets/search/recent`, `/2/tweets/search/all`, `/2/tweets/counts/recent`, `/2/tweets/counts/all`) para o novo índice de pesquisa da plataforma principal do X. Isso traz grandes melhorias de desempenho, uma redução drástica de erros 503 e três novos operadores de precisão: `min\_likes:`, `min\_replies:` e `min\_reposts:`. Observação: os reposts não são mais retornados nos resultados de pesquisa baseados em palavras-chave (o Filtered Stream permanece inalterado). Saiba mais [aqui](https://devcommunity.x.com/t/important-update-x-api-search-endpoints-migrating-to-new-search-index/264595).
### Atualização de preços da X API: "Owned Reads" agora a \$0.001
A partir de 20 de abril de 2026, introduzimos os novos preços de "Owned Reads" a \*\*$0.001 por recurso** (1.000 por $1) para endpoints elegíveis ao acessar seus próprios dados: `GET /2/users/{id}/bookmarks`, `/blocking`, `/muting`, `/pinned_lists`, `/tweets`, `/mentions`, `/liked_tweets`, `/followers`, `/following`, `/owned_lists`, `/followed_lists` e `/list_memberships`. Também atualizamos as escritas — `POST /2/tweets` agora custa $0.015 por post, e os posts contendo uma URL custam $0.20 por Post (respostas invocadas continuam a \$0.01). As ações de seguir, curtir e citar Posts via API foram removidas de todos os níveis self-serve. Saiba mais [aqui](https://devcommunity.x.com/t/x-api-pricing-update-owned-reads-now-0-001-other-changes-effective-april-20-2026/263025).
### Descontinuação do endpoint Account Activity Replay
Hoje, anunciamos a descontinuação de `POST /2/account_activity/replay/webhooks/{webhook_id}/subscriptions/all`, com efeito a partir de 25 de março de 2026 às 12:00 ET. Use o novo endpoint consolidado `POST /2/webhooks/replay` em vez disso — ele oferece funcionalidade idêntica. Saiba mais [aqui](https://devcommunity.x.com/t/deprecation-of-account-activity-replay-endpoint/260354).
### Filtro de direção para assinaturas da X Activity API
Hoje, adicionamos um filtro `direction` opcional às assinaturas da X Activity API. Os assinantes agora podem restringir eventos de DM e chat a `sent`, `received` ou ambos, reduzindo o ruído quando somente eventos enviados ou recebidos são necessários.
### Atualizações no formato de tipos de evento na X Activity API
Hoje, anunciamos mudanças na nomenclatura dos tipos de evento na X Activity API, com efeito a partir de 18 de março de 2026. Os tipos de evento em PascalCase (por exemplo, `ProfileBioUpdate`) estão sendo descontinuados em favor de um formato em minúsculas separado por pontos (por exemplo, `profile.update.bio`). Atualize qualquer filtragem, instruções switch ou lógica de desserialização que dependa dos valores antigos. Saiba mais [aqui](https://devcommunity.x.com/t/updates-to-event-types-format-in-the-x-activity-api/259765).
### Eventos legados de Direct Message na X Activity API
Hoje, adicionamos eventos legados de DM (`dm.received`, `dm.sent`, `dm.read`, `dm.indicate_typing`) à [X Activity API](https://docs.x.com/x-api/activity/introduction). Isso transfere a entrega de eventos de DM da Account Activity API para a pipeline de menor latência da XAA.
### Combate ao spam gerado por LLM
Hoje, fizemos alterações para reduzir respostas automatizadas e de baixa qualidade no X. As respostas programáticas via `POST /2/tweets` agora só são permitidas quando o autor do Post original "invocou" o respondedor (mencionando essa conta com @ ou citando um de seus Posts). Restrições adicionais se aplicam à menção com @ ou à citação programática de usuários. Essas alterações afetam apenas os níveis self-serve — o acesso Enterprise não é impactado. Saiba mais [aqui](https://devcommunity.x.com/t/x-api-v2-update-addressing-llm-generated-spam/257909).
### Lançamento dos preços Pay-Per-Use da X API
Hoje, lançamos oficialmente os preços **Pay-Per-Use da X API** — um modelo flexível baseado em créditos, criado para desenvolvedores indie, startups e entusiastas. Destaques:
* Um novo Developer Console em [console.x.com](https://console.x.com)
* O [XDK (X Developer Kit)](https://docs.x.com/xdks/overview) com SDKs próprios de Python e TypeScript
* Um [Playground](https://github.com/xdevplatform/playground) interativo para testes
* Um [servidor MCP](https://github.com/xdevplatform/xmcp) para modelos de IA
* Ganhe até **20% de volta em créditos da API da xAI/Grok** a cada dólar gasto na X API
Os Public Utility Apps continuam recebendo acesso escalonado gratuito. Usuários recentemente ativos do nível Legacy Free recebem um voucher único de \$10. Os planos Basic e Pro permanecem disponíveis, e os assinantes existentes podem optar pelo Pay-Per-Use. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-launch-of-x-api-pay-per-use-pricing/256476).
### Eventos de Spaces na X Activity API
Hoje, adicionamos eventos do ciclo de vida do Spaces (`spaces.start`, `spaces.end`) à [X Activity API](https://docs.x.com/x-api/activity/introduction). Assine por ID de usuário para ser notificado em tempo real quando um Space começa ou termina.
### Descontinuação de operadores baseados em contagem
Hoje, descontinuamos os operadores `min\_likes`, `min\_replies` e `min\_reposts` em `/2/tweets/search/recent` e `/2/tweets/search/all`. Essa alteração não afeta os operadores equivalentes no Filtered Stream. Estamos avaliando a melhor forma de reativá-los no futuro. Saiba mais [aqui](https://devcommunity.x.com/t/deprecating-count-based-operators-in-the-x-api/254933).
### Suporte a OAuth 2.0 adicionado à Account Activity API v2
Hoje, adicionamos suporte completo a OAuth 2.0 à [Account Activity API v2](https://docs.x.com/x-api/account-activity/introduction). Os desenvolvedores agora podem criar assinaturas usando OAuth 2.0 com escopos granulares (por exemplo, `follow.read`) em vez do modelo tudo-ou-nada de permissões do OAuth 1.0a. As integrações existentes baseadas em OAuth 1.0a continuam funcionando sem interrupção — quando presentes, as permissões de OAuth 1.0a substituem totalmente os escopos do OAuth 2.0. Saiba mais [aqui](https://devcommunity.x.com/t/announcement-oauth2-0-support-added-to-account-activity-api-v2/254633).
### Apresentando o X API Playground
Hoje, apresentamos o [X API Playground](https://github.com/xdevplatform/playground) — um servidor local auto-hospedado que emula os endpoints da X API v2. Desenvolva e teste integrações sem fazer chamadas reais à API nem atingir limites de taxa. Inclui dados simulados realistas, persistência de estado, validação por OpenAPI, simulação de limites de taxa e uma interface web. Instale com `go install github.com/xdevplatform/playground/cmd/playground@latest`. Saiba mais [aqui](https://devcommunity.x.com/t/introducing-x-api-playground-local-development-tool-for-x-api-v2/253442).
### Lançamento dos endpoints de News
Hoje, lançamos os novos [endpoints de News](https://docs.x.com/x-api/news/introduction) na X API v2:
* `GET /2/news/search` — retorna notícias em tendência que correspondem a uma consulta de pesquisa
* `GET /2/news/{id}` — busca uma notícia específica pelo ID
Ambos os endpoints suportam `news.fields` para selecionar campos como `name`, `summary`, `contexts`, `cluster\_posts\_results` e `last\_updated\_at\_ms`. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-news-endpoints-in-the-x-api-v2/251833).
### Lançamento dos XDKs de Python e TypeScript
Hoje, lançamos os XDKs (X Developer Kits) oficiais de [Python](https://docs.x.com/xdks/python/overview) e [TypeScript](https://docs.x.com/xdks/typescript/overview) para a X API v2. Os XDKs cuidam de autenticação (Bearer Token, OAuth 2.0 PKCE, OAuth 1.0a), paginação automática, streaming em tempo real com tratamento de reconexão e cobertura abrangente de todos os endpoints v2. Instale com `pip install xdk` ou `npm install @xdevplatform/xdk`. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-python-and-typescript-xdks-for-the-x-api-v2/250860).
### Filtragem por palavra-chave para assinaturas da X Activity API
Hoje, adicionamos filtragem por palavra-chave às assinaturas da X Activity API. Além da filtragem por ID de usuário, os assinantes agora podem refinar ainda mais a entrega de eventos por palavra-chave — útil para eventos de News e outros tipos de evento em que o alto volume de eventos justifica filtragem adicional.
### Eventos de selo de verificação, selo de afiliado e atualização de @handle na X Activity API
Hoje, expandimos a [X Activity API](https://docs.x.com/x-api/activity/introduction) para entregar tipos adicionais de eventos relacionados a perfis:
* `profile.update.verified` — quando o status de verificação de um usuário muda
* `profile.update.affiliate` — quando o selo de afiliado de um usuário muda
* `profile.update.screenname` — quando um usuário altera seu @handle
### Piloto de preços Pay-Per-Use da X API
Hoje, anunciamos um piloto fechado e limitado para um novo modelo de preços baseado em créditos e em uso. Os desenvolvedores compram créditos antecipadamente e são cobrados por solicitação — sem taxas de assinatura fixas e sem limites mensais de objetos. Tarifas iniciais do piloto: $0.005/Post Read, $0.01/User Read, $0.01/DM Event Read, $0.01/Content Create, $0.01/DM Interaction, $0.015/User Interaction. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-x-api-pay-per-use-pricing-pilot/250253).
### Lançamento da beta aberta da X Activity API
Hoje, lançamos a beta aberta da [X Activity API](https://docs.x.com/x-api/activity/introduction) — um novo conjunto de endpoints para se inscrever em eventos de atividade em tempo real no X com latência abaixo de um segundo. Assine tipos de eventos de perfil (`ProfileBioUpdate`, `ProfilePictureUpdate`, `ProfileBannerUpdate`, `ProfileGeoUpdate`, `ProfileUrlUpdate`), filtre por ID de usuário e receba eventos correspondentes por meio de um stream HTTP persistente (`GET /2/activity/stream`) ou de webhooks. As assinaturas são gerenciadas via `POST /2/activity/subscriptions`. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-x-activity-api-open-beta/250099).
### Edição de Posts via X API
Hoje, lançamos a capacidade de editar Posts recentes de forma programática via X API. Use o endpoint existente `POST /2/posts` com um novo objeto `edit_options` contendo `previous_post_id`. Requisitos: o usuário autenticado deve ter X Premium, o Post deve ser seu e ter sido criado na última hora. Consulte a documentação atualizada em [Create or Edit Post](https://docs.x.com/x-api/posts/create-post). Saiba mais [aqui](https://devcommunity.x.com/t/announcing-post-editing-via-the-x-api/249534).
### Connections API para gerenciar conexões ativas de streaming
Hoje, lançamos a [Connections API](https://docs.x.com/x-api/connections/introduction) para gerenciar conexões ativas de streaming de forma programática:
* `GET /2/connections` — lista conexões de streaming ativas e históricas
* `DELETE /2/connections/all` — encerra todas as conexões de streaming ativas do app
* `DELETE /2/connections/{endpoint_id}` — encerra conexões de um endpoint de streaming específico
* `DELETE /2/connections` — encerra conexões específicas por UUID
Isso ajuda os desenvolvedores a resolver erros de "TooManyConnections" e a limpar conexões obsoletas sem esperar pelos timeouts.
### Community Notes: endpoint Evaluate Note
Hoje, adicionamos o endpoint `POST /2/evaluate_note` à [Community Notes API](https://docs.x.com/x-api/community-notes/introduction). Os AI Note Writers agora podem avaliar uma nota em rascunho antes do envio para receber sinais sobre sua possível utilidade, alinhamento de afirmações/opiniões e outros feedbacks do modelo.
### Lançamento da Filtered Stream Webhooks API
Hoje, lançamos a [Filtered Stream Webhooks API](https://docs.x.com/x-api/webhooks/stream/introduction), que entrega Posts públicos correspondentes de forma assíncrona a um webhook registrado, em vez de exigir uma conexão persistente. As regras são gerenciadas usando os endpoints existentes de `/2/tweets/search/stream/rules`, e os Posts correspondentes (incluindo o histórico de edições) são entregues como JSON ao seu webhook. Disponível para desenvolvedores Enterprise; suporta mais de 25.000 regras por projeto, com regras de até 2.048 caracteres. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-filtered-stream-webhooks-api/248464).
### Remoção dos endpoints Like e Follow do nível Free
Para combater abuso, manipulação da plataforma e engajamento falso, removemos `POST /2/users/:id/likes` e `POST /2/users/:id/following` do nível Free da X API, com efeito imediato. Os níveis pagos (Basic, Pro, Enterprise) não são afetados. Saiba mais [aqui](https://devcommunity.x.com/t/update-to-x-api-free-tier-removal-of-like-and-follow-endpoints/247646).
### Endpoint de consulta de regras do PowerStream
Hoje, adicionamos o endpoint `GET /2/powerstream/rules`, permitindo que os clientes do PowerStream recuperem programaticamente as regras configuradas em suas instâncias do PowerStream.
### Transmissão de Posts da Comunidade via `share_with_followers`
Hoje, adicionamos um novo parâmetro booleano opcional `share_with_followers` em `POST /2/tweets`. Ao postar com um `community_id` e `share_with_followers: true`, o Post da comunidade também é transmitido para as timelines dos seguidores do usuário autenticado — correspondendo à caixa de seleção "Compartilhar também com seguidores" no x.com.
### Lançamento da Community Notes API
Hoje, lançamos a [Community Notes API](https://docs.x.com/x-api/community-notes/introduction) — um novo conjunto de endpoints para que AI Note Writers participem de forma programática do Community Notes:
* `GET /2/notes/search/posts_eligible_for_notes` — pesquisa Posts elegíveis para receber uma Community Note
* `GET /2/notes/search/notes_written` — recupera notas escritas anteriormente pelo AI Note Writer autenticado
* `POST /2/notes` — envia uma Community Note
O acesso requer inscrição no X Developer AI e aprovação como AI Note Writer do Community Notes.
### Alteração no comportamento dos DM Events
Hoje fizemos uma alteração no comportamento de DM Events da X API V2. Com a nova alteração, o array `participant_ids` será incluído apenas para os eventos `ParticipantsJoin` e `ParticipantsLeave` e listará somente os participantes que entraram ou saíram no momento do evento. O evento `MessageCreate` não incluirá mais o array `participant_ids`. Saiba mais [aqui](https://devcommunity.x.com/t/upcoming-change-to-x-api-dm-events-endpoints-behavior/241841).
### Lançamento dos endpoints da Account Activity API
Hoje lançamos novos [endpoints da Account Activity API](/x-api/webhooks/introduction) da X API v2. Saiba mais [aqui](https://devcommunity.x.com/t/account-activity-api-is-now-available-in-v2/242895).
### Melhorias no endpoint de upload de mídia
Fizemos algumas melhorias no endpoint de upload de mídia para aprimorar a experiência do desenvolvedor. Introduzimos endpoints dedicados para Chunked Media Upload nos [endpoints de Media Upload](/x-api/media/introduction). Saiba mais [aqui](https://devcommunity.x.com/t/media-upload-endpoints-update-and-extended-migration-deadline/241818).
### Suporte para recuperação de endereço de e-mail com OAuth 2.0
Hoje adicionamos suporte para recuperação de endereço de e-mail com OAuth 2.0 na X API V2. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-support-for-email-address-retrieval-with-oauth-2-0-in-the-x-api-v2/240555).
### Alterações nos dados de afiliação do usuário
Hoje fizemos alterações nos dados de User Affiliation da X API V2. Com a nova alteração, `affiliation.user_id` retornará um array de `user_ids`. Anteriormente, retornava um único `user_id` como string, mesmo que um usuário tivesse várias afiliações. Saiba mais [aqui](https://devcommunity.x.com/t/change-to-x-api-user-affiliation-data/237164).
### Lançamento dos endpoints de Media Upload
Hoje lançamos os novos [endpoints de Media Upload](/x-api/media/introduction) da X API v2. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-media-upload-endpoints-in-the-x-api-v2/234175/3).
### Lançamento do novo site de documentação
Hoje lançamos nosso novo site de documentação da X Developer Platform, [https://docs.x.com](https://docs.x.com).
### Lançamento da ferramenta xurl
Hoje lançamos o [xurl](https://github.com/xdevplatform/xurl), uma nova ferramenta que simplifica testes de API para desenvolvedores X, que agora oferece suporte ao OAuth 2.0.
### Adição do campo Community ID Tweet
Hoje adicionamos o campo `community_id` ao Tweet na X API v2. Saiba mais [aqui](https://x.com/tapshah21/status/1860061806653317126).
### Adição dos endpoints de bloqueio de DM
Hoje adicionamos os endpoints de bloqueio e desbloqueio de DM na X API v2.
### Suporte para publicações longas
Hoje adicionamos a capacidade de criar publicações longas com até 25k caracteres em vez de 4k.
### Suporte para publicações longas
Hoje adicionamos a capacidade de criar publicações longas usando a X API v2
### Obter afiliação do usuário
Hoje adicionamos a capacidade de obter a afiliação de um usuário de forma programática usando a X API v2
### Obter metadados de Article
Hoje adicionamos a capacidade de obter metadados de Article usando a X API v2
### Obter imagem de perfil e capa
Hoje adicionamos a capacidade de obter a URL da imagem de perfil e da capa via X V2 API
### Adição do campo Connection Status
Hoje adicionamos o campo `connection_status` na X API v2. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-connection-status-field-in-the-user-object-in-the-x-api-v2/212588).
### Adição do endpoint Trends Lookup
Hoje adicionamos o endpoint Trends lookup na X API v2. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567).
### Adição do endpoint Users Search
Hoje adicionamos o endpoint Users Search na X API v2. Saiba mais [aqui](https://devcommunity.x.com/t/announcing-the-users-search-and-trends-lookup-endpoints-in-the-x-api-v2/210567).
### Obter permissões de DM
Hoje adicionamos a capacidade de obter permissões de DM via X API v2. Saiba mais [aqui](https://devcommunity.x.com/t/dm-permissions-available-in-the-x-api-v2/209688).
### Lançamento do campo Subscription Type
Hoje lançamos o campo `subscription_type` no objeto User na X API v2. Saiba mais [aqui](https://devcommunity.x.com/t/new-subscription-type-field-is-available-in-the-twitter-api-v2/209219/2).
### Endpoint Get Posts Usage
Hoje lançamos um endpoint para obter de forma programática o uso de suas publicações na X API v2. Saiba mais [aqui](https://developer.x.com/en/docs/twitter-api/usage/tweets/api-reference/get-usage-tweets).
### Lançamento do endpoint Reposts Lookup
Hoje lançamos um endpoint para buscar os reposts de uma publicação na X API v2. Saiba mais [aqui](https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweets).
### Descontinuação dos endpoints de Search
Hoje estamos descontinuando os endpoints `search/tweets`, `users/search` e `geo/search` na X API v1.1. Saiba mais [aqui](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features).
### Descontinuação do endpoint Replay API
Hoje estamos descontinuando o endpoint Replay API da X API enterprise. Você pode usar os recursos de [recovery](https://developer.x.com/en/docs/twitter-api/enterprise/powertrack-api/guides/powertrack_recovery_and_redundancy_features) em vez disso.
### Descontinuação dos endpoints Historical Powertrack
Hoje estamos descontinuando os endpoints Historical Powertrack e Insights Track da X API enterprise.
### Remoção dos endpoints Follows dos níveis Basic e Pro
Hoje estamos removendo os endpoints Follows e List Follows dos níveis Basic e Pro da X API v2.
### Remoção do endpoint Manage Blocks
Hoje estamos removendo o endpoint Manage Blocks da X API v2.
### Suporte para contagem de Bookmarks e publicações longas
Hoje adicionamos suporte para obter contagem de bookmarks e a capacidade de recuperar publicações com mais de 280 caracteres na X API v2.
### Descontinuação do endpoint Statuses/Filter
Hoje estamos descontinuando o endpoint `statuses/filter` na X API v1.1. Os desenvolvedores podem usar o endpoint filtered stream na X API v2.
### Suporte para View Counts
Hoje estamos adicionando suporte para view counts na X API v2. Um novo campo chamado `impression_count` está disponível em `public_metrics` no payload da publicação.
### Adição do campo Verified Type
Hoje estamos adicionando um campo de usuário `verified_type` à X API v2 que indica o tipo de verificação que uma conta de usuário possui (blue, business, government ou none).
### Remoção do campo Source
Hoje estamos removendo o campo `source` do payload de publicação nas X APIs.
### Adição dos endpoints de Direct Messages
Hoje estamos adicionando seis endpoints v2 de Direct Messages. Esta versão inclui três métodos GET para recuperar eventos de conversa de Direct Message e três métodos POST para criar novos Direct Messages. Esses métodos suportam conversas em grupo pela primeira vez.
Visite nossa [postagem do blog](https://developer.x.com/en/blog/product-news/2022/new-v2-direct-messages-endpoints) para saber mais sobre esta atualização.
### Suporte a metadados de publicações editadas
Hoje estamos adicionando a capacidade de os desenvolvedores recuperarem metadados de publicações editadas usando a X API v2.
Visite nossa [postagem do blog](https://developer.x.com/en/blog/product-news/2022/supporting-edit-tweet-functionality) para saber mais sobre esta atualização.
### Adição de aliases para operadores de filtragem
"Aliases" de operadores de filtragem/consulta foram adicionados aos endpoints search e filtered stream, nas versões enterprise, premium e v2. Em muitos casos, o operador se refere a posts em vez de statuses, por exemplo `in_reply_to_tweet_id` como alias de `in_reply_to_status_id`. Em outros casos, o novo alias de operador adiciona mais clareza à correspondência realizada. Por exemplo, como publicações só podem ter um vídeo anexado, um novo alias `has:video_link` é fornecido para `has:videos`. Confira a [tabela de operadores do v2 filtered stream](https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule#list) para ver mais exemplos.
### Atualizações ao Reverse Chronological Home Timeline
A partir de hoje, o endpoint reverse chronological home timeline v2 pode retornar todas as publicações criadas em uma timeline nos últimos 7 dias e as 800 mais recentes, independentemente da data de criação.
### Novos operadores de filtragem para Filtered Stream
Hoje, 10 novos operadores de filtragem v2 estão disponíveis para todos os desenvolvedores que constroem com os endpoints de filtered stream, e outros 10 estão agora mais amplamente disponíveis.
Visite nossa [postagem do blog](https://developer.x.com/en/blog/product-news/2022/twitter-api-v2-filtered-stream) para saber mais sobre esta atualização.
### Atualizações de latência dos endpoints de Streaming
Hoje estamos fazendo atualizações nos endpoints de streaming na X API v2 para reduzir a latência em 50%.
### Habilitação dos endpoints de mídia v1.1 no Essential Access
Hoje estamos habilitando os endpoints de mídia v1.1 no acesso Essential da X API v2.
Visite nosso [anúncio do fórum](https://devcommunity.x.com/t/v1-1-media-endpoints-available-for-essential-access-in-the-twitter-api-v2/171664) para saber mais sobre esta atualização.
### Lançamento do endpoint Reverse Chronological Home Timeline
Hoje estamos lançando um novo endpoint que permite recuperar uma coleção das publicações e reposts mais recentes publicados pelas pessoas que você segue.
Visite nosso [anúncio do fórum](https://devcommunity.x.com/t/reverse-chronological-home-timeline-in-the-twitter-api-v2/171549) para saber mais sobre este lançamento.
Junto com os novos endpoints, o campo `variants` agora está disponível para o [objeto media](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/media). Isso fornecerá o tipo de conteúdo anexado à URL.
### Lançamento dos endpoints de Bookmarks
Hoje estamos lançando novos endpoints que permitem gerenciar e consultar Bookmarks usando a X API v2. O recurso Bookmarks está disponível há muito tempo no aplicativo X, mas até agora não havia um endpoint que permitisse recuperar, criar ou construir soluções para gerenciar seus Bookmarks via API.
Visite nosso [anúncio do fórum](https://devcommunity.x.com/t/build-with-bookmarks-on-the-twitter-api-v2/168804) para saber mais sobre este lançamento.
### Lançamento do endpoint Quotes Lookup
Hoje estamos lançando o [endpoint quotes lookup](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) que permite obter as citações de um ID de publicação.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/introducing-the-quote-tweets-lookup-endpoint-to-the-twitter-api-v2/168370) para saber mais sobre este lançamento.
### Atualizações na navegação da documentação
Ouvimos seu feedback. Encontrar conteúdo em nossa documentação podia ser difícil, e era confuso quando você clicava em um link e era levado para uma navegação lateral completamente diferente.
Hoje, lançamos uma navegação de documentação atualizada que permite navegar por toda a oferta da X Developer Platform a partir de uma única navegação lateral. Com este lançamento, eliminamos páginas redundantes, removemos ícones confusos e melhoramos como você pode interagir com os diferentes elementos dentro da navegação.
Se tiver algum feedback, informe-nos pelo nosso [canal de feedback](https://twitterdevfeedback.uservoice.com/forums/930250-twitter-api).
### Melhorias nos endpoints Reposts e Likes Lookup
Hoje, estamos lançando melhorias nos endpoints [reposts lookup](https://developer.x.com/en/docs/twitter-api/tweets/retweets/introduction) e [Likes lookup](https://developer.x.com/en/docs/twitter-api/tweets/likes/introduction), permitindo que você obtenha de volta a lista completa de contas que curtiram ou repostaram uma publicação, não apenas as últimas 100 contas a fazerem isso.
Para saber mais sobre este lançamento, visite nosso anúncio do fórum.
### Suporte para autenticação OAuth 2.0
Hoje, todos os desenvolvedores podem autenticar usando OAuth 2.0 selecionando OAuth 2.0 como método de autenticação no Developer Console. Adicionamos suporte para clientes confidenciais e públicos e para todos os endpoints v2 relevantes usarem este método de autenticação como parte desta versão.
OAuth 2.0 é um protocolo de autorização padrão da indústria que oferece aos desenvolvedores mais controle sobre os scopes de uma aplicação e melhora os fluxos de autorização em vários dispositivos. Em outras palavras, os desenvolvedores que constroem aplicações para pessoas no X terão mais controle sobre as informações que seu App solicita aos usuários, de modo que você só precise pedir aos seus usuários finais os dados e informações de que precisa.
Este protocolo de autorização moderno permitirá apresentar aos seus usuários finais um fluxo de consentimento mais simplificado para autorizar seu app, que exibe apenas os scopes específicos que você solicitou deles.
Para saber mais sobre este lançamento, visite nosso anúncio do fórum.
### Principais atualizações da plataforma X API v2
**Principais atualizações da plataforma: X API v2 agora é a versão principal, novos acessos Essential e Elevated e alterações de Política**
Hoje, anunciamos que a X API v2 agora é a versão principal da X API. Lançamos endpoints e funcionalidades suficientes na X API v2 para atender às necessidades de 90% de todos os Apps existentes construídos sobre a X API.
Estamos lançando as seguintes alterações hoje para melhorar ainda mais a experiência do desenvolvedor da X API v2:
* Acesso Essential rápido e gratuito à API e acesso Elevated gratuito para desenvolvedores que tiveram seus casos de uso aprovados. Temos muito mais detalhes sobre esses níveis de acesso disponíveis em nossa página About the X API.
* Estamos removendo a linguagem em nossa Developer Policy que restringia como você constrói com os recursos principais do X e limitava o número de usuários que você pode suportar por meio do seu app.
* Estamos abrindo nossa plataforma para encorajá-lo a construir ferramentas e produtos que tornem o X melhor, mais saudável e ampliem a conversa pública. [Veja uma lista de soluções que adoraríamos ver você construir](https://developer.x.com/en/docs/twitter-api/what-to-build).
* Especificamente, removemos termos que restringiam a replicação da experiência X, incluindo os recursos principais do X, bem como termos que exigiam permissão para ter um alto número de tokens de usuário.
* Sabemos que construir soluções que ajudam as pessoas no X muitas vezes significa que um desenvolvedor precisa construir (ou replicar) algumas das coisas que estão disponíveis no X. Essas alterações à nossa Developer Policy visam trazer clareza ao ecossistema de desenvolvedores e fornecer uma plataforma de API aberta que facilite aos desenvolvedores construir, inovar e ter impacto na conversa pública.
Detalhamos muito mais sobre este lançamento e os lançamentos da X API que levaram a este momento em nossa [publicação do fórum](https://devcommunity.x.com/t/ushering-in-a-new-era-for-the-twitter-developer-platform-with-the-twitter-api-v2/162087).
Além de explorar entradas anteriores do changelog, reunimos alguns recursos-chave que você pode revisar para entender o que foi lançado para a X API v2 até hoje:
* [X API endpoint map](/x-api/migrate/x-api-endpoint-map)
* [About the X API](/x-api/getting-started/about-x-api)
### Lançamento dos endpoints List Lookup
Hoje, estamos lançando os novos endpoints List lookup na X API v2. Esses endpoints permitirão aos usuários recuperar detalhes sobre Listas especificadas, como seguidores, membros, publicações e mais. Os dados recuperados podem ser usados para construir soluções que resolvem casos de uso e necessidades de curadoria, análise e descoberta. Além dos novos endpoints de Lista, um novo operador `list:` foi disponibilizado no nível de acesso Academic Research. Estará disponível para uso em search posts e post counts.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/announcing-list-lookup-endpoints-for-the-twitter-api-v2/161965).
### Adições aos endpoints de Spaces
Estamos adicionando funcionalidade ao endpoint de Spaces para retornar a lista de pessoas que compraram um ingresso para um Space, bem como suporte para Topics.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/adding-new-functionality-to-spaces-endpoints/161959).
### Lançamento dos endpoints Manage Posts
Hoje, estamos lançando novos endpoints manage posts na X API v2. Além da funcionalidade de post e exclusão de post, adicionamos a capacidade de postar enquetes, marcar pessoas em imagens, criar publicações com configurações de resposta e postar para Super Followers.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/announcing-manage-tweets-endpoints-for-the-twitter-api-v2/161501).
### Alterações nos botões incorporados
Hoje, estamos fazendo algumas alterações nos botões incorporados do X. Os botões agora são mais arredondados para combinar com os botões do X.com e atualizamos (muito ligeiramente) nossa paleta de cores.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/embedded-buttons-have-a-new-look/160528).
### Lançamento do grupo de endpoints Lists
Hoje, estamos lançando o novo grupo de endpoints Lists na X API v2. Esses endpoints permitirão que você construa soluções que curam e organizam publicações com base em preferências, interesses, grupos ou tópicos.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-manage-list-endpoints/159980).
### Lançamento do endpoint Mutes Lookup
Hoje, estamos lançando o novo endpoint [mutes lookup](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) na X API v2. Este endpoint permitirá que usuários autenticados recuperem e obtenham informações sobre as contas que silenciaram.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/announcing-new-mutes-lookup-endpoint-for-the-twitter-api-v2/159680).
### Lançamento do beta do OAuth 2.0
Hoje, estamos lançando um beta do OAuth 2.0 e scopes refinados na X API v2. Desenvolvedores interessados em moldar o futuro do OAuth 2.0 na X Developer Platform podem solicitar acesso ao beta do OAuth 2.0.
OAuth 2.0 é o padrão da indústria para autenticação e permitirá uma experiência de autorização mais moderna.
O beta do OAuth 2.0 permite testar essa nova funcionalidade em um Project v2 e App associado e nos dar feedback antes do lançamento de General Availability. No entanto, como esta implementação do OAuth 2.0 está atualmente em desenvolvimento, recomendamos enfaticamente que você evite testar em um ambiente público, de produção ou app.
Para saber mais sobre este lançamento, visite nosso anúncio do fórum.
### Lançamento dos endpoints Batch Compliance
Hoje, estamos lançando os novos [endpoints de batch compliance](https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/introduction) na X API v2 para facilitar aos desenvolvedores que usam a X API manter seus dados X em conformidade com nossa [Developer Agreement and Policy](https://developer.x.com/en/developer-terms/policy). Esses endpoints permitem aos desenvolvedores e pesquisadores fazer upload em lote de grandes quantidades de IDs de publicações ou usuários e entender quais ações são necessárias para garantir que seus conjuntos de dados reflitam a intenção do usuário e o estado atual do conteúdo no X.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/new-batch-compliance-endpoints-available-on-the-twitter-api-v2/158534).
### Lançamento dos endpoints de Spaces
Hoje, estamos lançando os novos [endpoints de Spaces](https://developer.x.com/en/docs/twitter-api/spaces/overview) e um [novo dicionário de dados de Spaces de nível superior](https://developer.x.com/en/docs/twitter-api/data-dictionary/object-model/space) na X API v2. Os endpoints de Spaces permitem buscar Spaces por Space ID ou user ID, ou usando palavras-chave, hashtags ou nomes de usuário de pessoas mencionadas em um título. O novo dicionário de dados contém informações relevantes sobre um Space, como seu título, status de venda de ingressos e métricas de participantes; todos os user IDs podem ser expandidos para objetos completos.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/introducing-new-spaces-endpoints-on-the-twitter-api-v2/158213).
### Novo objeto para limitação de visualizações de vídeo
Anteriormente, quando você solicitava métricas de visualizações de vídeo usando a enterprise \[Engagement API]/x-api/enterprise-gnip-2.0/fundamentals/engagement-api) em publicações com mais de 1800 dias, entregávamos um valor zero sem muito contexto. Hoje, começaremos a entregar um novo objeto nesses casos chamado `unsupported_for_video_views_tweet_ids`, que incluirá uma lista separada por vírgulas de IDs de publicações com mais de 1800 dias. Você ainda receberá todas as outras métricas solicitadas para essas publicações em um objeto separado.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/new-engagement-api-video-views-object-to-clarify-limitation/158163).
### Adição do campo Alt Text
Hoje, estamos disponibilizando o campo `alt_text` no objeto media da X API v2, para permitir que desenvolvedores construam de forma mais consciente em relação à acessibilidade.
Para solicitar este campo, você deve passar o parâmetro `expansions=attachments.media_keys`, bem como o parâmetro `media.fields=alt_text`. Se incluído em sua solicitação, este campo retornará o texto alternativo para qualquer publicação que inclua imagens com texto alternativo.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/media-alt-text-field-now-available-in-twitter-api-v2/157939).
### Lançamento dos endpoints Reposts
Hoje, estamos lançando novos endpoints de [reposts](https://developer.x.com/en/docs/twitter-api/tweets/retweets) na X API v2. Os desenvolvedores agora podem usar esses endpoints para repostar ou desfazer um repost em nome de um usuário autenticado, ou para consultar quem repostou uma determinada publicação.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/announcing-new-twitter-api-v2-retweets-endpoints/156827).
### Lançamento dos endpoints Manage Mutes
Hoje, estamos lançando novos endpoints de [manage mutes](https://developer.x.com/en/docs/twitter-api/users/mutes/introduction) na X API v2. Esses endpoints permitirão que usuários autenticados silenciem ou cancelem o silenciamento de contas.
Para saber mais sobre este lançamento, visite nosso [anúncio do fórum](https://devcommunity.x.com/t/announcing-new-manage-mutes-endpoints-for-the-twitter-api-v2/156261).
Reduzimos o `max_results` que pode ser entregue com o endpoint [full-archive search](/x-api/posts/full-archive-search) quando você está solicitando o campo `context_annotations` com o parâmetro `tweet.fields` para 100, o que significa que você só pode obter até 100 publicações com o campo por página.
### Recursos de confiabilidade para endpoints de Streaming
Hoje, estamos lançando dois recursos de confiabilidade de streaming para filtered stream e sampled stream da X API v2 chamados backfill e redundant connections, agora disponíveis no produto Academic Research.
O recurso de redundant connections permite que você se conecte a um determinado stream duas vezes, o que pode ajudar a garantir que você maximize o tempo de atividade do streaming caso um de seus streams sofra uma desconexão.
Backfill pode ser utilizado adicionando o parâmetro `backfill_minutes` e um número inteiro entre um e cinco à sua solicitação de streaming, e permite solicitar dados perdidos que possam ter resultado de um stream desconectado.