X API v2
Look up X users and posts, search the last 7 days, sign users in with PKCE, publish posts and manage bookmarks.
SocialGuided#twitter#x#social#oauth2#pkce#search#posts
Fork copies the collection into your workspace, without the publisher's secrets, so you can add your own key and send requests. Star saves it to your starred APIs (Account › Marketplace) and helps others find it.
Overview
The X API v2 (formerly the Twitter API) lets your app read public posts and profiles, search recent conversation, and, with a user's permission, publish and delete posts and manage that user's bookmarks. This guided collection covers the requests most apps need first, in the order to run them.
Get credentials
- Sign in at the X Developer Console with an X account and accept the Developer Agreement and Policy.
- Buy credits: the API is billed pay-per-use, and calls fail without a credit balance (see pricing).
- Create a New App. The console shows the credentials once, so store them safely:
- Bearer Token for app-only requests (public data).
- Client ID and Client Secret for OAuth 2.0 user sign-in.
- In the app's user authentication settings, add a callback URL (for example
http://127.0.0.1:8080/callback) and give the app read and write permission if you will post.
Authentication
All calls go to https://api.x.com/2 with an Authorization: Bearer ... header. There are two kinds of token:
- App-only bearer token (folder 1): the Bearer Token from the console. It reads public data such as users, posts and recent search. It cannot act for a user, so
/users/me, posting, bookmarks, likes and follows refuse it. - OAuth 2.0 user context with PKCE (folders 2-5): the user signs in at
https://x.com/i/oauth2/authorizeand approves scopes (tweet.read,users.read,tweet.write,bookmark.read,bookmark.write,offline.access...). You exchange the returned code and your PKCE verifier athttps://api.x.com/2/oauth2/tokenfor an access token (about two hours) and, withoffline.access, a refresh token. The authorization code expires about 30 seconds after approval, so exchange it immediately.
Using this collection
- Paste your Bearer Token into
bearerTokenand run folder 1. Get a user by username fillsuserId, and Get a user's posts fillspostIdfor the lookups after it. - For user actions, follow the steps in folder 2 (fill
clientId,clientSecret,redirectUri,codeVerifier, thenauthCode) and run the exchange. It storesuserTokenandrefreshToken. - Run Get the signed-in user (fills
myUserId), then folders 3-5. Create a post stores the new post's id so you can delete it afterwards.
Fields and expansions
Responses are lean by default: a post comes back with id and text, a user with id, name and username. Ask for more with tweet.fields and user.fields (comma-separated lists such as created_at,public_metrics). Expansions such as author_id or referenced_tweets.id pull related objects into a separate includes block instead of making you call again.
Limits and pricing
Every endpoint has its own rate-limit window. Each response carries x-rate-limit-limit, x-rate-limit-remaining and x-rate-limit-reset (Unix time when the window resets); past the limit you get 429 until then. Rate limits are separate from billing: reads are charged per resource returned (re-reading the same resource within a UTC day is deduplicated) and writes per request. Since April 2026 following, likes and quote posts are no longer available on self-serve access, and programmatic replies are only allowed where the original author mentioned or quoted your account; folder 5 is kept for Enterprise customers. Current prices and limits: pricing and rate limits.
Common errors
| Status | Meaning | What to do |
|---|---|---|
| 400 | Invalid parameter or body | Check field names, IDs (digits only) and the query syntax. |
| 401 | Missing, wrong or expired token | Re-check bearerToken, or refresh userToken. |
| 402 | No credits left | Add credits in the Developer Console. |
| 403 | Not allowed | Wrong token type (app-only on a user endpoint), missing scope, app lacks write permission, or the action is not on your access level. |
| 404 / errors[] | Not found | The user or post does not exist or is protected; partial failures come back in an errors array with status 200. |
| 429 | Rate limited | Wait until x-rate-limit-reset, then back off. |
Docs: X API introduction, fields, expansions, building search queries, OAuth 2.0 PKCE, changelog.
Endpoints 20
1. Start here: public data (app-only token)
- GETGet a user by username
/users/by/username/{{username}}Looks up one account by its handle (without the @). When: the usual starting point, because most other endpoints take the numeric user ID, not the handle.… - GETGet a user by ID
/users/{{userId}}Returns the same user object as the username lookup, addressed by numeric ID. When: you stored IDs (they never change, handles can) or got an author_id from a… - GETGet a user's posts (timeline)
/users/{{userId}}/tweetsLists the most recent posts written by one user, newest first. When: showing someone's feed or collecting their posts. What comes back: data (array of posts)… - GETLook up a post (fields and expansions)
/tweets/{{postId}}Fetches one post by ID and shows how fields and expansions work together. When: you have a post ID (from a link, a timeline or search) and need its details,… - GETLook up several posts at once
/tweetsFetches up to 100 posts in one call by passing their IDs comma-separated in ids. When: refreshing metrics for a batch of stored posts, which is cheaper on… - GETSearch recent posts
/tweets/search/recentSearches posts from the last 7 days with X's query language. Query operators (combine with spaces = AND, OR, parentheses and - to negate): Example: (api OR…
2. User sign-in (OAuth 2.0 with PKCE)
- POSTExchange the code for a user token
/oauth2/tokenTrades the authorization code and your PKCE verifier for a user access token. How it authenticates: this collection's app is treated as a confidential client,… - POSTRefresh the user token
/oauth2/tokenGets a new access token without asking the user again. When: a user-context call returns 401 after the token's two hours are up. Requires that offline.access… - POSTRevoke a token
/oauth2/revokeInvalidates an access or refresh token, for example when the user signs out of your app. Body: token (the token to revoke) and client_id; confidential clients…
3. The signed-in user and posting
- GETGet the signed-in user (me)
/users/meReturns the account that authorised userToken. When: right after sign-in, to learn the user's ID and handle. Only works with a user token; the app-only bearer… - POSTCreate a post
/tweetsPublishes a post as the signed-in user. Needs the tweet.write scope and an app with write permission. What comes back: 201 with data.id and data.text. The… - DELETEDelete a post
/tweets/{{createdPostId}}Deletes a post the signed-in user wrote. Uses {{createdPostId}} from Create a post. When: cleaning up, or letting users remove posts from your app. You can… - GETRate-limit check (read the headers)
/users/meAny request returns rate-limit headers; this one repeats the cheap /users/me call so you can look at them. Limits are per endpoint, and per user for user…
4. Bookmarks
- GETList bookmarks
/users/{{myUserId}}/bookmarksLists the posts the signed-in user has bookmarked, newest first. Key parameters: max_results (1-100), pagination_token from meta.next_token, plus the usual… - POSTBookmark a post
/users/{{myUserId}}/bookmarksAdds a post to the signed-in user's bookmarks. Body: {"tweet_id": "..."}. Uses {{postId}} from folder 1. What comes back: data.bookmarked: true. Common… - DELETERemove a bookmark
/users/{{myUserId}}/bookmarks/{{postId}}Removes a post from the signed-in user's bookmarks. What comes back: data.bookmarked: false.
5. Likes and follows (Enterprise access only)
- POSTLike a post
/users/{{myUserId}}/likesLikes a post as the signed-in user. Body: {"tweet_id": "..."} (uses {{postId}}). What comes back: data.liked: true. Common errors: 403 on self-serve access… - DELETEUnlike a post
/users/{{myUserId}}/likes/{{postId}}Removes the signed-in user's like from a post. What comes back: data.liked: false. Same access rules as Like a post. - POSTFollow a user
/users/{{myUserId}}/followingFollows another account as the signed-in user. Body: {"target_user_id": "..."} (uses {{userId}} from folder 1). What comes back: data.following and… - DELETEUnfollow a user
/users/{{myUserId}}/following/{{userId}}Stops the signed-in user (source_user_id) following target_user_id. What comes back: data.following: false. Same access rules as Follow a user.
API details
- Base URL
https://api.x.com/2- Authentication
- A bearer token in the Authorization header
OAuth 2.0 (authorization code flow) - Operations
- 20 operations on 20 pathsGET 9POST 7DELETE 4
- Main resources
- 1. Start here: public data (app-only token) 62. User sign-in (OAuth 2.0 with PKCE) 33. The signed-in user and posting 44. Bookmarks 35. Likes and follows (Enterprise access only) 4
- Description format
- Swastik Codes guided collection, API version
checked against the docs on 2026-11-17 - Links
- Documentation
How to test the X API v2 in Swastik Codes
- Open the APISelect “Fork & run in Swastik Codes” on this page. Sign in or create a free account if asked.
- Fork it into your workspaceChoose a workspace. You get your own copy of the X API v2 collection, without the publisher's secrets.
- Add your credentialsThis API uses A bearer token in the Authorization header. Add yours in the collection's variables or an environment; the requests already reference it.
- Send a requestPick an endpoint, for example “Get a user by username” (GET /users/by/username/{{username}}), and press Send. Check the response, add tests and run the whole collection with the runner.
Frequently asked questions
What is the X API v2?
Look up X users and posts, search the last 7 days, sign users in with PKCE, publish posts and manage bookmarks. It is listed under Social and has 20 endpoints.
Who publishes the X API v2?
It is listed from X (Twitter)'s public API description (an OpenAPI document), not published by X (Twitter) on Swastik Codes. Anyone who controls twitter.com can claim the profile by adding a DNS TXT record.
What is the base URL of the X API v2?
Requests go to https://api.x.com/2. Endpoint paths are added to this base URL.
How do I authenticate with the X API v2?
It accepts 2 methods: A bearer token in the Authorization header; OAuth 2.0 (authorization code flow).
How many endpoints does the X API v2 have?
20 operations on 20 paths (9 GET, 7 POST, 4 DELETE). The largest groups are 1. Start here: public data (app-only token), 2. User sign-in (OAuth 2.0 with PKCE), 3. The signed-in user and posting, 4. Bookmarks.
Is forking the X API v2 free?
Yes. Forking copies the collection into your workspace for free. It has been starred 0 times and forked 0 times.