Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Twitter OpenAPI
https://github.com/fa0311/twitter-openapi
Admin
This project provides the Twitter OpenAPI (Swagger) specification.
Tokens:
63,140
Snippets:
336
Trust Score:
9.8
License:
MIT
Update:
3 weeks ago
Context
Chat
Benchmark
65.67
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Example usage of Config.main() Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/build-config.md Shows how to instantiate Config, call main(), and inspect the request hooks for both profiles. The example prints the class names of the last hook for 'tweet' and 'post' requests, demonstrating the difference between the profiles. ```python from tools.build_config import Config from tools.hooks import AddParametersOnBody, SetResponsesHeader config = Config() # Docs profile: JSON-in-query for GraphQL GETs profiles = config.main() docs_request = profiles["docs"]["request"] print(type(docs_request["tweet"][-1]).__name__) # AddParametersOnContent # Compatible profile: plain strings compat_request = profiles["compatible"]["request"] print(type(compat_request["tweet"][-1]).__name__) # AddParametersOnParameters # POST hooks carry the JSON body hook print(type(docs_request["post"][-1]).__name__) # AddParametersOnBody ``` -------------------------------- ### Python example — bookmarks pagination Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-bookmarks-follow.md Python script that paginates through bookmarks using the getBookmarks endpoint. It loops up to 5 pages, sends a GET request with variables and features, handles errors, and extracts the bottom cursor from TimelineAddEntries instructions. Requires a valid Bearer token and CSRF token. ```python import json import requests cursor = None for page in range(5): variables = {"count": 20, "includePromotedContent": True} if cursor: variables["cursor"] = cursor resp = requests.get( "https://x.com/i/api/graphql/XD0ViOeSOW4YoeNTGjVaYw/Bookmarks", headers={"authorization": "Bearer <token>", "x-csrf-token": "<ct0>"}, params={ "variables": json.dumps(variables), "features": json.dumps({"rweb_video_screen_enabled": False, "rweb_cashtags_enabled": True}), }, ) body = resp.json() if body.get("errors"): raise RuntimeError(body["errors"]) timeline = body["data"]["bookmark_timeline_v2"]["timeline"] for instr in timeline["instructions"]: if instr["type"] == "TimelineAddEntries": for entry in instr["entries"]: content = entry["content"] if content.get("cursorType") == "Bottom": cursor = content["value"] if not cursor: break ``` -------------------------------- ### Python example — follow list with defensive union handling Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-bookmarks-follow.md Python script that fetches followers using the getFollowers endpoint and handles the UserUnion type defensively. It sends a GET request with userId and empty features, then iterates over timeline entries, checking for TimelineUser items and printing screen names only when the union resolves to a User. ```python resp = requests.get( "https://x.com/i/api/graphql/_orfRBQae57vylFPH0Huhg/Followers", params={ "variables": json.dumps({"userId": "44196397"}), "features": json.dumps({}), }, ) data = resp.json().get("data", {}) if data: result = data["user"]["result"] for instr in result["timeline"]["timeline"]["instructions"]: for entry in instr.get("entries", []): item = entry["content"].get("itemContent", {}) if item.get("__typename") == "TimelineUser": user = item["user_results"]["result"] # UserUnion if user["__typename"] == "User": print(user["legacy"]["screen_name"]) ``` -------------------------------- ### Generated client flow (Python) Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-timeline.md Commented-out example of using the generated client (Python generator) after running openapi-generator-cli. Shows the equivalent flow to the raw request: instantiate client, get tweet API, call get_search_timeline, and iterate over instructions. ```python # Equivalent generated-client flow (Python generator, dist/compatible): # client = TwitterOpenApi(...); api = client.get_tweet_api() # response = api.get_search_timeline(path_query_id, variables=..., features=...) # for entry in response.data.search_by_raw_query.search_timeline.timeline.instructions: # ... ``` -------------------------------- ### GET /other Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md This is not an actual endpoint. It models the `window.__INITIAL_STATE__` session object of the web app. ```APIDOC ## GET /other ### Description This is not an actual endpoint. It models the `window.__INITIAL_STATE__` session object of the web app. ### Method GET ### Endpoint /other ### Response #### Success Response (200) Returns the `OtherObjectAll` schema. #### Response Example ```json { "country": "US", "communitiesActions": { "create": true }, "isActiveCreator": true, "isRestrictedSession": false, "guestId": "1234567890", "hasCommunityMemberships": true, "language": "en", "oneFactorLoginEligibility": { "fetchStatus": "success" }, "SsoInitTokens": {}, "superFollowersCount": 10, "superFollowsApplicationStatus": "NotStarted", "user_id": "1234567890", "userFeatures": { "mediatool_studio_library": true }, "isSuperFollowSubscriber": false } ``` ``` -------------------------------- ### GET SearchTimeline Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-timeline.md Example of calling the SearchTimeline endpoint directly using Python requests, including request parameters and response handling. ```APIDOC ## GET /i/api/graphql/Yw6L66Pw54NHKuq4Dp7b4Q/SearchTimeline ### Description Performs a search on Twitter using the SearchTimeline GraphQL endpoint. The variables and features are passed as JSON-encoded query parameters. ### Method GET ### Endpoint https://x.com/i/api/graphql/Yw6L66Pw54NHKuq4Dp7b4Q/SearchTimeline ### Parameters #### Query Parameters - **variables** (string) - Required - JSON-encoded object containing search parameters (e.g., rawQuery, count, querySource, product). - **features** (string) - Required - JSON-encoded object containing feature flags (e.g., rweb_video_screen_enabled, rweb_cashtags_enabled). ### Request Example ```python import json import requests resp = requests.get( "https://x.com/i/api/graphql/Yw6L66Pw54NHKuq4Dp7b4Q/SearchTimeline", headers={"authorization": "Bearer <public-web-token>", "x-csrf-token": "<ct0 cookie>", "user-agent": "<browser UA>"}, params={ "variables": json.dumps({"rawQuery": "elonmusk", "count": 20, "querySource": "typed_query", "product": "Top"}), "features": json.dumps({"rweb_video_screen_enabled": False, "rweb_cashtags_enabled": True}), }, ) ``` ### Response #### Success Response (200) - **data** (object) - Contains the search results. - **data.search_by_raw_query.search_timeline.timeline** (object) - The timeline object with instructions. - **data.search_by_raw_query.search_timeline.timeline.instructions** (array) - List of instruction objects (InstructionUnion[]). #### Response Example ```python body = resp.json() if body.get("errors"): for err in body["errors"]: print(err["extensions"]["code"], err["message"]) else: timeline = body["data"]["search_by_raw_query"]["search_timeline"]["timeline"] print(timeline["instructions"]) ``` ### Error Handling - **errors** (array) - If present, contains error objects with `extensions.code` and `message` fields. ``` -------------------------------- ### Custom hook example: PrettyQueryId Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/hooks.md Custom hook extending RequestHookBase to rewrite the path and mutate the operation value. The hook accesses the placeholder dictionary to retrieve the queryId and path, then sets the description. The example shows the expected output comment. ```python import json from tools.hooks import RequestHookBase class PrettyQueryId(RequestHookBase): """Demonstrates the hook contract: rewrite path + mutate operation.""" def hook(self, path, value): path, value = super().hook(path, value) qid = self.PLACEHOLDER[self.path_name]["queryId"] value["description"] = f"queryId {qid} captured on {self.PLACEHOLDER[self.path_name]['@path']}" return path, value h = PrettyQueryId(split=-1) path, op = h.hook("/graphql/{pathQueryId}/UserByScreenName", {"responses": {"200": {}}}) print(op["description"]) # queryId IGgvgiOx4QZndDHuD3x9TQ captured on /i/api/graphql/IGgvgiOx4QZndDHuD3x9TQ/UserByScreenName ``` -------------------------------- ### GET /other — other Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md Defines the GET /other operation with operationId other. The description explicitly states 'This is not an actual endpoint'; it models the window.__INITIAL_STATE__ session object of the web app. The other tag has an empty hook chain, so no parameters or headers are added. ```yaml get: operationId: other description: This is not an actual endpoint responses: "200": description: Successful operation content: application/json: schema: $ref: "#/components/schemas/OtherObjectAll" tags: - "other" ``` -------------------------------- ### GET UsersByRestIds Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-user.md Example of batch resolving users by rest IDs using the UsersByRestIds GraphQL endpoint. ```APIDOC ## [GET] https://x.com/i/api/graphql/_8egOzcbgeLIhP0TbTStGw/UsersByRestIds ### Description Batch resolve users by their rest IDs, returning a typed union of user or unavailable user results. ### Method GET ### Endpoint https://x.com/i/api/graphql/_8egOzcbgeLIhP0TbTStGw/UsersByRestIds ### Parameters #### Query Parameters - **variables** (string) - Required - JSON-encoded object containing `userIds` array of user rest IDs. - **features** (string) - Required - JSON-encoded object with feature flags (e.g., `payments_enabled`). ### Request Example ```python resp = requests.get( "https://x.com/i/api/graphql/_8egOzcbgeLIhP0TbTStGw/UsersByRestIds", params={ "variables": json.dumps({"userIds": ["44196397"]}), "features": json.dumps({"payments_enabled": False}), }, ) ``` ### Response #### Success Response (200) - **data.users** (array) - List of user result objects. - **result.__typename** (string) - Discriminator: `"User"` or `"UserUnavailable"`. - **result.rest_id** (string) - User rest ID (when `__typename` is `"User"`). - **result.is_blue_verified** (boolean) - Blue verification status (when `__typename` is `"User"`). - **result.message** (string) - Error message (when `__typename` is `"UserUnavailable"`). #### Response Example ```json { "data": { "users": [ { "result": { "__typename": "User", "rest_id": "44196397", "is_blue_verified": true } } ] } } ``` ``` -------------------------------- ### Build project with Python tools Source: https://github.com/fa0311/twitter-openapi/blob/main/README.md Builds the project locally. Requires Python 3.10.8 and installing dependencies from requirements.txt before running the build script. ```shell python -V # Python 3.10.8 pip install -r requirements.txt python tools/build.py ``` -------------------------------- ### GET friends/following/list.json with requests Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md Performs a GET request to the v1.1 friends/following/list endpoint. Requires a Bearer token and CSRF token in headers. The response schema is not declared in the spec, so the raw JSON is printed. ```python resp = requests.get( "https://x.com/i/api/1.1/friends/following/list.json", headers={"authorization": "Bearer <token>", "x-csrf-token": "<ct0>"}, params={ "include_profile_interstitial_type": 1, "include_blocking": 1, "include_blocked_by": 1, "include_followed_by": 1, "include_want_retweets": 1, "include_mute_edge": 1, "include_can_dm": 1, "include_can_media_tag": 1, "include_ext_has_nft_avatar": 1, "include_ext_is_blue_verified": 1, "include_ext_verified_type": 1, "include_ext_profile_image_shape": 1, "skip_status": 1, "cursor": -1, "user_id": "44196397", "count": 3, "with_total_count": True, }, ) print(resp.json()) # response schema not declared in the spec ``` -------------------------------- ### GET /2/search/adaptive.json — getSearchAdaptive Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md Defines the GET /2/search/adaptive.json operation with operationId getSearchAdaptive. The v2.0-get tag uses the same hook chain as v1.1-get, adding ~35 query parameters from placeholder.json. ```yaml get: operationId: getSearchAdaptive description: get search adaptive responses: "200": description: Successful operation tags: - "v2.0-get" ``` -------------------------------- ### GET /1.1/friends/following/list.json — getFriendsFollowingList Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md Defines the GET /1.1/friends/following/list.json operation with operationId getFriendsFollowingList. The v1.1-get tag triggers SetResponsesHeader() and AddParametersOnParameters(split=2, schemaType=None), which adds required query parameters from placeholder.json. ```yaml get: operationId: getFriendsFollowingList description: get friends following list responses: "200": description: Successful operation tags: - "v1.1-get" ``` -------------------------------- ### Generate parameters with AddParametersOnContent hook Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/configuration.md Uses the AddParametersOnContent hook to generate parameters for a GraphQL operation by injecting placeholder-driven content. The hook is configured with split=-1, contentType="application/json", and ignoreKeys=["queryId", "@path", "@method"]. The example prints the generated parameter name and schema, showing a screen_name property with example and default values. ```python from tools.hooks import AddParametersOnContent hook = AddParametersOnContent(split=-1, contentType="application/json", ignoreKeys=["queryId", "@path", "@method"]) path, op = hook.hook( "/graphql/{pathQueryId}/UserByScreenName", {"responses": {"200": {}}}, ) print(op["parameters"][1]["name"]) # variables print(op["parameters"][1]["content"]["application/json"]["schema"]) # {'type': 'object', 'properties': {'screen_name': {'type': 'string', # 'example': 'elonmusk', 'default': 'elonmusk'}}, 'required': ['screen_name']} ``` -------------------------------- ### GET /graphql/{pathQueryId}/UserMedia Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-usertweets.md Retrieves user media using the UserMedia GraphQL query. ```APIDOC ## GET /graphql/{pathQueryId}/UserMedia ### Description Get user media. ### Method GET ### Endpoint /graphql/{pathQueryId}/UserMedia ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The query ID for the GraphQL operation. #### Query Parameters - **variables** (object) - Optional - Defaults include `includePromotedContent: False`, `withClientEventToken: False`. - **features** (object) - Optional - Present in the request. - **fieldToggles** (object) - Optional - Present in the request. ### Response #### Success Response (200) - **UserTweetsResponse** - Successful operation. #### Response Example ```json { "data": { "user": { "result": { "__typename": "User", "timeline": {} } } } } ``` ``` -------------------------------- ### Minimal authenticated GET to UserByScreenName Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/endpoints.md Minimal authenticated GET request to the Twitter/X internal GraphQL endpoint. Requires a valid `ct0` CSRF token and `auth_token` cookie; the bearer token is the public default. Prints the rate-limit remaining header and the JSON response. ```python import json, requests base = "https://x.com/i/api" resp = requests.get( f"{base}/graphql/IGgvgiOx4QZndDHuD3x9TQ/UserByScreenName", headers={ "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA", "x-csrf-token": "<ct0>", "user-agent": "Mozilla/5.0 ... Chrome/130.0.0.0 Safari/537.36", }, cookies={"auth_token": "...", "ct0": "..."}, params={ "variables": json.dumps({"screen_name": "elonmusk"}), "features": json.dumps({}), }, ) print(resp.headers.get("x-rate-limit-remaining"), resp.json()) ``` -------------------------------- ### GET /graphql/{pathQueryId}/HomeLatestTimeline Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/endpoints.md Retrieves the latest home timeline for the authenticated user. ```APIDOC ## GET /graphql/{pathQueryId}/HomeLatestTimeline ### Description Fetches the latest home timeline for the authenticated user. ### Method GET ### Endpoint /graphql/{pathQueryId}/HomeLatestTimeline ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The query ID for the HomeLatestTimeline operation. Default: `0dateTVgvXjpkf7kyBZy0g`. #### Query Parameters - **variables** (object) - Required - Contains: `count` (integer), `includePromotedContent` (boolean), `latestControlAvailable` (boolean), `requestContext` (string), `seenTweetIds` (array of strings). - **features** (object) - Required - Feature flags for the request. ### Response #### Success Response (200) - **data.home.home_timeline_urt** (Timeline) - The home timeline data. #### Response Example ```json { "data": { "home": { "home_timeline_urt": {} } } } ``` ``` -------------------------------- ### GET /2/search/adaptive.json Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md Performs an adaptive search. This is a legacy v2.0 REST endpoint. ```APIDOC ## GET /2/search/adaptive.json ### Description Performs an adaptive search. This is a legacy v2.0 REST endpoint. ### Method GET ### Endpoint /2/search/adaptive.json ### Parameters #### Query Parameters - **q** (string) - Required - Default: "elon musk" - **query_source** (string) - Required - Default: "trend_click" - **count** (integer) - Required - Default: 20 - **tweet_mode** (string) - Required - Default: "extended" - **cards_platform** (string) - Required - Default: "Web-12" - **ext** (string) - Required - A long CSV of requested extensions - **include_*** (various) - Required - Standard include flags (multiple parameters) ### Response #### Success Response (200) Successful operation ``` -------------------------------- ### GET /graphql/{pathQueryId}/ProfileSpotlightsQuery — getProfileSpotlightsQuery Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-user.md Retrieves profile spotlights for a user by screen name. This operation requires the screen_name variable and returns a ProfileResponse. ```APIDOC ## GET /graphql/{pathQueryId}/ProfileSpotlightsQuery ### Description Get user by screen name (profile spotlights). ### Method GET ### Endpoint /graphql/{pathQueryId}/ProfileSpotlightsQuery ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The query ID for this operation. For this operation, the query ID is `mzoqrVGwk-YTSGME1dRfXQ`. #### Query Parameters - **variables** (object) - Required - Default: `{screen_name: "elonmusk"}`. Must include `screen_name`. - **features** (object) - Required - Present in the request (empty dict `{}` in placeholder). ### Response #### Success Response (200) - **ProfileResponse** - Contains `data.user_result_by_screen_name` of type `UserResultByScreenName` (base64 `id`, `result`) and optional `errors`. #### Response Example ```json { "data": { "user_result_by_screen_name": { "id": "", "result": {} } }, "errors": [] } ``` ``` -------------------------------- ### GET /graphql/{pathQueryId}/Following — getFollowing YAML definition Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-bookmarks-follow.md YAML operation definition for the getFollowing endpoint. Specifies operationId, description, 200 response with FollowResponse schema, and tag 'user-list'. Located at src/openapi/paths/follow.yaml:8. ```yaml get: operationId: getFollowing description: get user list of following responses: "200": description: Successful operation content: application/json: schema: $ref: "#/components/schemas/FollowResponse" tags: - "user-list" ``` -------------------------------- ### GET /graphql/{pathQueryId}/Bookmarks Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-bookmarks-follow.md Retrieves the bookmarks timeline for the authenticated user. Supports pagination via a cursor. ```APIDOC ## GET /graphql/{pathQueryId}/Bookmarks ### Description Get bookmarks for the authenticated user. ### Method GET ### Endpoint /graphql/{pathQueryId}/Bookmarks ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The GraphQL query ID (e.g., `XD0ViOeSOW4YoeNTGjVaYw`). #### Query Parameters - **variables** (object) - Required - JSON-encoded object with `count` (default 20) and `includePromotedContent` (default true). Optional `cursor` for pagination. - **features** (object) - Required - JSON-encoded object with feature flags. ### Request Example ```json { "variables": {"count": 20, "includePromotedContent": true, "cursor": "..."}, "features": {"rweb_video_screen_enabled": false, "rweb_cashtags_enabled": true} } ``` ### Response #### Success Response (200) - **data** (object) - Contains `bookmark_timeline_v2`. - **errors** (array) - Optional error list. #### Response Example ```json { "data": { "bookmark_timeline_v2": { "timeline": { "instructions": [] } } } } ``` ``` -------------------------------- ### GET /graphql/{pathQueryId}/Following Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-bookmarks-follow.md Retrieves the list of users that a given user is following. The response contains a timeline with user entries. ```APIDOC ## GET /graphql/{pathQueryId}/Following ### Description Get the list of users that the specified user is following. ### Method GET ### Endpoint /graphql/{pathQueryId}/Following ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The GraphQL query ID (e.g., `F42cDX8PDFxkbjjq6JrM2w`). #### Query Parameters - **variables** (object) - Required - JSON-encoded object with `userId`. - **features** (object) - Required - JSON-encoded object with feature flags. ### Request Example ```json { "variables": {"userId": "44196397"}, "features": {} } ``` ### Response #### Success Response (200) - **data** (object) - Contains `user.result.timeline.timeline`. - **errors** (array) - Optional error list. #### Response Example ```json { "data": { "user": { "result": { "timeline": { "timeline": { "instructions": [] } } } } } } ``` ``` -------------------------------- ### GET UserByScreenName Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/dev-tools.md Reference implementation of a real GraphQL call to retrieve a user by screen name. Demonstrates the required headers, cookies, and query parameters. ```APIDOC ## GET https://twitter.com/i/api/graphql/BQ6xjFU6Mgm-WhEP3OiT9w/UserByScreenName ### Description Retrieves a Twitter user's information by their screen name using the GraphQL endpoint. This is a reference implementation of a real GraphQL call against the spec's contract. ### Method GET ### Endpoint https://twitter.com/i/api/graphql/BQ6xjFU6Mgm-WhEP3OiT9w/UserByScreenName ### Parameters #### Query Parameters - **variables** (string) - Required - JSON-encoded string containing the `screen_name` parameter. - **features** (string) - Required - JSON-encoded string containing feature flags. - **fieldToggles** (string) - Required - JSON-encoded string containing field toggles. ### Request Example ```python import json import requests data = requests.get( "https://twitter.com/i/api/graphql/BQ6xjFU6Mgm-WhEP3OiT9w/UserByScreenName", cookies={k["name"]: k["value"] for k in json.load(open("cookie.json"))}, params={ "variables": json.dumps({"screen_name": "5unsetpowerln"}), "features": json.dumps({ "hidden_profile_subscriptions_enabled": True, "rweb_tipjar_consumption_enabled": True, "responsive_web_graphql_exclude_directive_enabled": True, }), "fieldToggles": json.dumps({"withAuxiliaryUserLabels": False}), }, headers={ "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA", "x-csrf-token": json.load(open("cookie.json")).get("ct0"), "x-twitter-active-user": "yes", "x-twitter-auth-type": "OAuth2Session", "x-twitter-client-language": "en", }, ) print(data.json()) ``` ### Response #### Success Response (200) - **data** (object) - The response data containing user information. #### Response Example ```json { "data": {} } ``` ``` -------------------------------- ### POST friendships/create.json with requests Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md Sends a POST request to create a friendship using form-encoded data. The response includes x-rate-limit-remaining header, which is declared on the 200 response. The example prints the status code and that header. ```python resp = requests.post( "https://x.com/i/api/1.1/friendships/create.json", headers={"authorization": "Bearer <token>", "x-csrf-token": "<ct0>"}, data={ "include_profile_interstitial_type": 1, "include_blocking": 1, "include_blocked_by": 1, "include_followed_by": 1, "include_want_retweets": 1, "include_mute_edge": 1, "include_can_dm": 1, "include_can_media_tag": 1, "include_ext_has_nft_avatar": 1, "include_ext_is_blue_verified": 1, "include_ext_verified_type": 1, "include_ext_profile_image_shape": 1, "skip_status": 1, "user_id": "44196397", }, ) print(resp.status_code, resp.headers.get("x-rate-limit-remaining")) # 200, "xx" — x-rate-limit-* headers are declared on the 200 response ``` -------------------------------- ### GET /graphql/{pathQueryId}/CommunityMediaTimeline — getCommunityMediaTimeline Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-timeline.md Retrieves the media timeline of a community. Uses query ID `ZniZ7AAK_VVu1xtSx1V-gQ` and returns a `CommunityMediaTimelineResponse`. ```APIDOC ## GET /graphql/{pathQueryId}/CommunityMediaTimeline ### Description Retrieves the media timeline of a community. ### Method GET ### Endpoint /graphql/{pathQueryId}/CommunityMediaTimeline ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The per-endpoint query ID injected at build time. Default is the query ID `ZniZ7AAK_VVu1xtSx1V-gQ`. #### Query Parameters - **variables** (object) - Required - JSON-serialized string or application/json content schema typed from `placeholder.json`. - **features** (object) - Required - JSON-serialized string or application/json content schema typed from `placeholder.json`. - **fieldToggles** (object) - Optional - Only if the placeholder defines it; not defined for this operation. ### Response #### Success Response (200) - **CommunityMediaTimelineResponse** - The response schema. Contains `data.communityResults.result.community_media_timeline` → `TimelineResult`. #### Response Example (No explicit response example provided in source.) ``` -------------------------------- ### Python: Manually reproduce a single profile's assembly Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/build-pipeline.md Loads the root OpenAPI document and a path module, then uses replace_ref from tools.build to merge the module's paths into the document. Prints the operationId for the HomeTimeline GET endpoint, which outputs 'getHomeTimeline'. ```python # Reproduce a single profile's assembly manually import yaml from tools.build_config import Config from tools.build import replace_ref config = Config() with open("src/openapi/openapi-3.0.yaml") as f: doc = yaml.safe_load(f) with open("src/openapi/paths/timeline.yaml") as f: module = yaml.safe_load(f) doc["paths"] = replace_ref(module["paths"]) print(doc["paths"]["/graphql/{pathQueryId}/HomeTimeline"]["get"]["operationId"]) # getHomeTimeline ``` -------------------------------- ### Run the build pipeline Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/build-pipeline.md Executes the build pipeline from the command line. Reads all *.yaml files under src/openapi, runs configured hooks, and writes OpenAPI 3.0 documents to dist/. ```shell python tools/build.py ``` -------------------------------- ### Config.main() method definition Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/build-config.md Defines the main() method of the Config class, returning a dictionary with two profiles: 'docs' and 'compatible', each generated by hooks_generator with different queryParameterJson settings. ```python def main(self): return { "docs": self.hooks_generator(), "compatible": self.hooks_generator( queryParameterJson=False, ), } ``` -------------------------------- ### Generate client with openapi-generator-cli Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/README.md Command to generate a client from the OpenAPI spec hosted on GitHub. Use the dist/docs version for strict OpenAPI compliance; dist/compatible drops JSON-in-query-parameter syntax for generators that do not support it. ```shell openapi-generator-cli generate -g <language> \ -i https://raw.githubusercontent.com/fa0311/twitter-openapi/main/dist/docs/openapi-3.0.yaml \ -o ./generated ``` -------------------------------- ### End-to-end update flow: login, generate, build, and smoke-test Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/dev-tools.md Sequential shell commands that capture auth cookies with tools/login.py, paste DevTools fetch dumps into tools/input.js and run tools/generater.py to update src/config/placeholder.json, rebuild both dist/ variants with tools/build.py, and smoke-test against the live API using the captured session via the TWITTER_SESSION environment variable. ```bash # 1. Capture auth cookies (logs in as the given account) python tools/login.py # writes cookie.json, prints base64 bundle # 2. Paste DevTools fetch dumps into tools/input.js, then: python tools/generater.py # updates src/config/placeholder.json # 3. Rebuild both dist/ variants python tools/build.py # 4. Smoke-test against the live API with the captured session TWITTER_SESSION=$(python - <<'EOF' import json, base64 print(base64.b64encode(open("cookie.json","rb").read()).decode()) EOF ) python test/python/test_serialize.py ``` -------------------------------- ### GenericError JSON example for missing status Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/errors.md Example error response captured from TweetDetail for a missing status. Shows the full error object with duplicated fields at top level and in extensions, including code 144 and kind NonFatal. ```json { "errors": [ { "message": "_Missing: No status found with that ID.", "locations": [{"line": 2, "column": 3}], "path": ["threaded_conversation_with_injections_v2"], "extensions": { "name": "GenericError", "source": "Server", "code": 144, "kind": "NonFatal", "tracing": {"trace_id": "e6de8b2b694ae128"} }, "code": 144, "kind": "NonFatal", "name": "GenericError", "source": "Server", "tracing": {"trace_id": "e6de8b2b694ae128"} } ], "data": {} } ``` -------------------------------- ### AddParametersOnParameters hook class Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/hooks.md Appends one required query parameter per non-ignored placeholder key. With schemaType="string" the value is JSON-serialized into default/example (the compatible profile); with schemaType=None each value is expanded into a fully typed schema (placeholder_to_yaml). Throws KeyError if self.path_name has no placeholder entry. ```python class AddParametersOnParameters(RequestHookBase): schemaType: str | None ignoreKeys: list[str] def __init__( self, split: str = 1, schemaType: str | None = None, ignoreKeys: list[str] | None = None, ): super().__init__(split=split) self.schemaType = schemaType self.ignoreKeys = ignoreKeys or [] def hook(self, path: str, value: dict): path, value = super().hook(path, value) data = self.PLACEHOLDER[self.path_name] data = {key: data[key] for key in data.keys() if key not in self.ignoreKeys} for key in data.keys(): if self.schemaType == "string": example = ( data[key] if isinstance(data[key], str) else json.dumps(data[key]) ) schema = { "type": "string", "default": example, "example": example, } elif self.schemaType == "object": example = ( data[key] if isinstance(data[key], str) else json.dumps(data[key]) ) schema = { "type": "object", "default": example, "example": example, } else: schema = self.placeholder_to_yaml(data[key]) value["parameters"].append( { "name": key, "in": "query", "required": True, "schema": schema, } ) return path, value ``` -------------------------------- ### main() function in tools/generater.py Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/dev-tools.md Entry point for the placeholder generator script. Prompts the user to paste Chrome DevTools 'copy as fetch' output into ./tools/input.js. Uses rich for console output and runs under the module-level main() guard. ```python #!/usr/bin/env python3 # Usage: poetry run python -m misc.TwitterAPIQueryGenerator import json import re import urllib.parse from rich import print from rich.rule import Rule def main(): print(Rule(characters="=")) print( "Chrome DevTools の Network タブで検索窓に「graphql」と入力し「表示されているものをすべてfetch としてコピー」したコードを`input.js`に貼り付けてください。" ) print("Enter を押すと続行します。") print(Rule(characters="=")) input() ``` -------------------------------- ### AddParametersOnContent hook class Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/hooks.md Appends one required query parameter per non-ignored placeholder key, each carrying a content: application/json wrapper around a fully typed schema (the docs profile). Throws KeyError if the placeholder has no entry for self.path_name. ```python class AddParametersOnContent(RequestHookBase): contentType: str ignoreKeys: list[str] def __init__( self, split: str = 1, contentType: str = "application/json", ignoreKeys: list[str] | None = None, ): super().__init__(split=split) self.contentType = contentType self.ignoreKeys = ignoreKeys or [] def hook(self, path: str, value: dict): path, value = super().hook(path, value) data = self.PLACEHOLDER[self.path_name] data = {key: data[key] for key in data.keys() if key not in self.ignoreKeys} for key in data.keys(): value["parameters"].append( { "name": key, "in": "query", "required": True, "content": { self.contentType: { "schema": self.placeholder_to_yaml(data[key]), } }, } ) return path, value ``` -------------------------------- ### GET /graphql/{pathQueryId}/Bookmarks Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/endpoints.md Retrieves the bookmarked tweets for the authenticated user. ```APIDOC ## GET /graphql/{pathQueryId}/Bookmarks ### Description Retrieves the bookmarked tweets for the authenticated user. ### Method GET ### Endpoint /graphql/{pathQueryId}/Bookmarks ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The query ID for the Bookmarks operation. #### Query Parameters - **variables** (object) - Required - Contains `count` (integer) and `includePromotedContent` (boolean). - **features** (object) - Required - Feature flags for the request. ### Response #### Success Response (200) - **data.bookmark_timeline_v2.timeline** (Timeline) - The timeline of bookmarked tweets. #### Response Example ```json { "data": { "bookmark_timeline_v2": { "timeline": {} } } } ``` ``` -------------------------------- ### GET /graphql/{pathQueryId}/HomeTimeline Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/endpoints.md Retrieves the home timeline for the authenticated user. ```APIDOC ## GET /graphql/{pathQueryId}/HomeTimeline ### Description Fetches the home timeline for the authenticated user. ### Method GET ### Endpoint /graphql/{pathQueryId}/HomeTimeline ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The query ID for the HomeTimeline operation. Default: `7zlnp2TxC044W4C1ZUJMHw`. #### Query Parameters - **variables** (object) - Required - Contains: `count` (integer), `includePromotedContent` (boolean), `latestControlAvailable` (boolean), `requestContext` (string), `seenTweetIds` (array of strings). - **features** (object) - Required - Feature flags for the request. ### Response #### Success Response (200) - **data.home.home_timeline_urt** (Timeline) - The home timeline data. #### Response Example ```json { "data": { "home": { "home_timeline_urt": {} } } } ``` ``` -------------------------------- ### HookBase class initialization Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/hooks.md Defines the HookBase class with a PLACEHOLDER attribute loaded from src/config/placeholder.json on construction. ```python class HookBase: PLACEHOLDER: dict def __init__(self): with open("src/config/placeholder.json", mode="r", encoding="utf-8") as f: self.PLACEHOLDER = json.load(f) ``` -------------------------------- ### Config class definition with OUTPUT_DIR and INPUT_DIR Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/build-config.md Defines the Config class with class attributes OUTPUT_DIR (format string for output directory) and INPUT_DIR (directory for source YAML modules). ```python class Config: OUTPUT_DIR = "dist/{0}" INPUT_DIR = "src/openapi" ``` -------------------------------- ### GET /1.1/search/typeahead.json Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-legacy-other.md Performs a typeahead search. This is a legacy v1.1 REST endpoint. ```APIDOC ## GET /1.1/search/typeahead.json ### Description Performs a typeahead search. This is a legacy v1.1 REST endpoint. ### Method GET ### Endpoint /1.1/search/typeahead.json ### Parameters #### Query Parameters - **include_ext_is_blue_verified** (string) - Required - Placeholder parameter - **include_ext_verified_type** (string) - Required - Placeholder parameter - **include_ext_profile_image_shape** (string) - Required - Placeholder parameter - **q** (string) - Required - Search query - **src** (string) - Required - Source of the search - **result_type** (string) - Required - Type of results to return ### Response #### Success Response (200) Successful operation ``` -------------------------------- ### HookBase.load_component method Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/hooks.md Loads a component YAML file from src/config/component/{name}.yaml. Throws FileNotFoundError if the file does not exist. ```python def load_component(self, name: str) -> dict: with open(f"src/config/component/{name}.yaml", mode="r", encoding="utf-8") as f: return yaml.safe_load(f) ``` -------------------------------- ### getProfileSpotlightsQuery OpenAPI operation Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-user.md Defines the GET /graphql/{pathQueryId}/ProfileSpotlightsQuery operation with operationId getProfileSpotlightsQuery. The response schema references ProfileResponse. Query ID mzoqrVGwk-YTSGME1dRfXQ; variables default to {screen_name: "elonmusk"} and features is an empty dict in the placeholder. No tags declared, so the build assigns the default tag. ```yaml get: operationId: getProfileSpotlightsQuery description: "get user by screen name" responses: "200": description: Successful operation content: application/json: schema: $ref: "#/components/schemas/ProfileResponse" ``` -------------------------------- ### GET /graphql/{pathQueryId}/Retweeters Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-tweet.md Retrieves the list of users who retweeted a tweet. ```APIDOC ## GET /graphql/{pathQueryId}/Retweeters ### Description Retrieves the list of users who retweeted a tweet. ### Method GET ### Endpoint /graphql/{pathQueryId}/Retweeters ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The query ID for the operation. Default is `TZsWuSj7vGmncVnq7KWDUQ`. #### Query Parameters - **variables** (object) - Required - Contains the following defaults: `tweetId` (string, default `1349129669258448897`), `count` (integer, default `20`), `includePromotedContent` (boolean, default `true`). - **features** (object) - Required - Contains feature flags. ### Response #### Success Response (200) - **data** (object) - Contains `retweeters_timeline` of type `TimelineResult`. - **errors** (array) - Optional - Array of `ErrorResponse` objects. #### Response Example ```json { "data": { "retweeters_timeline": {} }, "errors": [] } ``` ``` -------------------------------- ### GET /graphql/{pathQueryId}/Favoriters Source: https://github.com/fa0311/twitter-openapi/blob/main/_autodocs/api-reference/endpoints-tweet.md Retrieves the list of users who favorited a tweet. ```APIDOC ## GET /graphql/{pathQueryId}/Favoriters ### Description Retrieves the list of users who favorited a tweet. ### Method GET ### Endpoint /graphql/{pathQueryId}/Favoriters ### Parameters #### Path Parameters - **pathQueryId** (string) - Required - The query ID for the operation. Default is `SPOr3rvo2j1E8bFd-qGczQ`. #### Query Parameters - **variables** (object) - Required - Contains the following defaults: `tweetId` (string, default `1349129669258448897`), `count` (integer, default `20`), `includePromotedContent` (boolean, default `true`). - **features** (object) - Required - Contains feature flags. ### Response #### Success Response (200) - **data** (object) - Contains `favoriters_timeline` of type `TimelineResult`. - **errors** (array) - Optional - Array of `ErrorResponse` objects. #### Response Example ```json { "data": { "favoriters_timeline": {} }, "errors": [] } ``` ```