How to Get an X (Twitter) API Key: Setup, Keys and What It Costs
TL;DR - Quick Answer
18 min readComprehensive guide with practical insights you can apply today.
Getting X API credentials is how you read X data, automate posting, and build integrations. Two things have changed since most guides on this topic were written, and both change the plan you should be making.
The application gate is gone. There is no longer a use-case questionnaire, no manual review measured in weeks, and no approval to wait for. You sign up in the developer portal at developer.x.com and create an app.
The free tiers are gone too. Essential and Elevated, the free tiers every older guide describes, went with the February 2023 API shutdown, and the academic research tier went with them. X now bills per call. From X's own pricing documentation: $0.005 per post read, $0.015 to create a post, and $0.200 to create a post containing a URL. That last one is the number to plan around: a link post costs more than thirteen times a plain one, which matters a great deal if you are building anything that shares links.
Quick Setup Overview
What You'll Need
- An X account with a verified phone number
- A payment method, because usage is billed
- A rough estimate of your monthly read and write volume
What You'll Get
- API Key (Consumer Key)
- API Secret Key (Consumer Secret)
- Bearer Token
- Access Token and Secret
Step by Step Setup Process
Step 1: Create Twitter Developer Account
Create content, post everywhere
Create captions, images, and videos with AI. Schedule to 9 platforms in seconds.
Start your free trial
Go to the X Developer Portal:
- Visit developer.x.com
- Sign in with your X account
- Accept the developer agreement
- Create your first project and app
Older guides send you to developer.x.com and tell you to click "Apply for a developer account". The domain redirects and the application no longer exists.
Step 2: Set Up Billing and a Spending Limit
This is the step that replaced the application, and it is the one worth doing carefully. Usage is billed against a credit balance, and the console lets you:
- Set a spending limit per billing cycle, which is the only thing standing between a retry loop and a surprise invoice
- Turn on auto-recharge if you would rather not have calls start failing, with a built-in limit of one charge per five-minute window
- Watch the credit balance in the developer console while you are developing, not after
Set the spending limit before you write any code. A bug that reads a timeline in a loop is cheap to write and not cheap to run.
Step 3: Verify Your Account
Email Verification:
- Check email for verification link
- Click verification link
- Return to developer portal
Phone Verification:
- Add phone number if not already added
- Enter verification code received via SMS
Step 4: Set App Permissions
There is no review to wait for, but there is a permission choice that catches people out. An app created with read-only permissions will authenticate fine and then fail on every write, and changing the permission does not update tokens you already generated. If you switch an app from read to read-and-write, regenerate the access token and secret afterwards or you will spend an afternoon debugging a permission you already fixed.
Step 5: Create Your App
Once your project exists:
- Go to the X Developer Portal dashboard
- Click "Create App"
- Fill out app details
App Information Required:
- App name (must be unique)
- App description
- Website URL (can be placeholder)
- Callback URLs (for authentication)
Step 6: Get Your API Keys
Navigate to Keys and Tokens:
- Go to your app dashboard
- Click "Keys and Tokens" tab
- Find your credentials
Your API Credentials:
API Key (Consumer Key): [25 character string]
API Secret Key (Consumer Secret): [50 character string]
Bearer Token: [Long encoded string]
Access Token: [50 character string]
Access Token Secret: [45 character string]
What the X API Costs
X bills per call. Its pricing documentation is explicit that there are "no contracts, subscriptions, or minimum spend", which also means there is no free allowance to fall back on.
Pay-per-usage accounts are capped at 2 million post reads per monthly billing cycle. X also offers up to 20% back in xAI API credits once cumulative spend passes its thresholds.
The two numbers that decide your architecture
A post with a link costs $0.200 against $0.015 without one. That is more than thirteen times the price for adding a URL, and it is the single biggest cost lever in most integrations. If you are building anything that shares links at volume, model that line specifically. Nothing in the API surfaces the difference at call time; it turns up on the bill.
Reading your own data costs $0.001 instead of $0.005. A 90% discount applies to your own posts, bookmarks and followers, so an analytics dashboard for your own account is five times cheaper to run than one that reads other people's. Route owned-data reads through the owned endpoints rather than through generic lookups.
What happened to the free tiers
Essential Access, Elevated Access and the academic research product are all gone. They were retired when Twitter ended free API access in February 2023, and the subscription tiers that replaced them have themselves been wound down: legacy Basic subscribers were automatically migrated to pay-per-use after 1 June 2026. Any guide that offers you "500,000 free tweet reads a month", including an earlier version of this page, is describing 2022.
Setting Up Authentication
Bearer Token Authentication
For Read Only Access:
const headers = {
'Authorization': `Bearer ${BEARER_TOKEN}`,
'Content-Type': 'application/json'
}OAuth 1.0a Authentication
For User Context:
const auth = {
consumer_key: API_KEY,
consumer_secret: API_SECRET,
access_token_key: ACCESS_TOKEN,
access_token_secret: ACCESS_TOKEN_SECRET
}Common Use Cases and Setup
Social Media Management Tools
Required Permissions:
- Read tweets and user data
- Post tweets
- Manage direct messages
- Access user followers
Setup Steps:
- Enable read and write permissions
- Generate user access tokens
- Implement OAuth flow for user authorization
- Store tokens securely
Analytics and Research
Required Permissions:
- Read tweets and user data
- Access tweet metrics
- Search historical tweets
- User lookup capabilities
Setup Steps:
- Apply for Academic Research access if applicable
- Use bearer token for app only authentication
- Implement rate limiting handling
- Set up data storage compliance
Automation Bots
Required Permissions:
- Read tweets
- Post tweets
- Like and retweet content
- Follow/unfollow users
Setup Steps:
- Create app with automation use case
- Set up user context authentication
- Implement proper rate limiting
- Follow Twitter automation rules
API Testing and Validation
Test Your Setup
Basic API Call Test:
curl -X GET "https://api.x.com/2/tweets/search/recent?query=hello&max_results=10" \
-H "Authorization: Bearer YOUR_BEARER_TOKEN"Expected Response:
{
"data": [
{
"id": "1234567890123456789",
"text": "Hello world tweet example"
}
]
}Common Testing Endpoints
Get Tweet by ID:
GET /2/tweets/{id}
Search Recent Tweets:
GET /2/tweets/search/recent?query={query}
Get User by Username:
GET /2/users/by/username/{username}
Rate Limiting and Best Practices
Understanding Rate Limits
Rate limits are per endpoint and per 15-minute window, and they are published against each endpoint in the X API reference rather than as a single figure per plan. Do not budget against a number from a blog post, this one included: check the endpoint you are actually calling.
Under pay-per-use there is a second limit that matters more than the rate limit, and that is your own spending cap. Hitting a rate limit costs you time. Not hitting one, because your retry loop is happily paying for every call, costs money.
Handling Rate Limits
Best Practices:
- Implement exponential backoff, and cap the number of retries. Under pay-per-use every retry is billable, so an uncapped backoff loop is a spending bug, not just a politeness bug
- Cache responses. A cached read costs nothing
- Batch requests: asking for 100 posts in one call beats 100 calls
- Watch the credit balance and the spending limit in the developer console, not just the rate limit headers
Rate Limit Headers:
x-rate-limit-limit: 75
x-rate-limit-remaining: 74
x-rate-limit-reset: 1635724800
Security Best Practices
Protecting Your Keys
Never Do:
- Commit API keys to public repositories
- Share keys in client side code
- Use keys in URLs or logs
- Store keys in plain text
Always Do:
- Use environment variables
- Implement proper access controls
- Rotate keys regularly
- Monitor usage for anomalies
Environment Variable Setup
For Development:
export TWITTER_API_KEY="your_api_key"
export TWITTER_API_SECRET="your_api_secret"
export TWITTER_ACCESS_TOKEN="your_access_token"
export TWITTER_ACCESS_SECRET="your_access_secret"Troubleshooting Common Issues
Unexpected Charges
Common Causes:
- A retry loop with no cap, paying for every attempt
- Posting links without realising they are billed at $0.200 rather than $0.015
- Reading your own account through generic lookup endpoints at $0.005 instead of the owned-data rate of $0.001
- Pagination fetching more resources than you use
Solutions:
- Set a spending limit first, then debug
- Log the number of resources returned per call, not just the number of calls
- Cache anything you read more than once
API Key Not Working
Potential Issues:
- Keys not properly copied
- Wrong authentication method
- Expired or revoked keys
- Account suspension
Debugging Steps:
- Verify keys are correct and complete
- Check authentication format
- Test with simple API call
- Review account status in dashboard
Rate Limit Exceeded
Solutions:
- Read the
x-rate-limit-resetheader and wait rather than retrying immediately - Batch: request the maximum resources per call your endpoint allows
- Cache aggressively
- Reduce polling frequency. Most integrations poll far more often than their data changes
API Integration Examples
Python Integration
import tweepy
# v2 client. tweepy.API / api.update_status target v1.1 endpoints that a new
# project cannot call, which is why older snippets fail with a 403.
client = tweepy.Client(
consumer_key=API_KEY,
consumer_secret=API_SECRET,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_TOKEN_SECRET,
)
response = client.create_tweet(text="Hello X API!")
print(response.data["id"])Node.js Integration
// twitter-api-v2. The older `twitter` package is unmaintained and calls v1.1
// endpoints such as search/tweets that are no longer generally available.
const client = new TwitterApi({
appKey: process.env.X_API_KEY,
appSecret: process.env.X_API_SECRET,
accessToken: process.env.X_ACCESS_TOKEN,
accessSecret: process.env.X_ACCESS_SECRET,
});
// Each result here is a billable read, so keep max_results tight.
const search = await client.v2.search('social media', { max_results: 10 });
console.log(search.data);Managing Your Developer Account
Dashboard Navigation
Key Sections:
- Apps overview and management
- Usage metrics and analytics
- Account settings and limits
- Billing, credit balance and spending limits
Monitoring Usage
Track These Metrics:
- Credit balance and spend against your limit
- Resources returned per call, which is what you are billed on, not calls made
- Rate limit hit frequency
- Error rates and types, since failed calls still cost time and sometimes money
Account Maintenance
Regular Tasks:
- Review API usage patterns
- Update app information as needed
- Monitor for policy updates
- Rotate keys for security
Scaling Up
There are no access levels to upgrade between any more, so "requesting additional access" is not a step that exists. What you do instead:
- Raise your spending limit in the developer console when volume grows
- Check the 2 million post reads per billing cycle cap. Pay-per-usage accounts stop there. Genuinely higher volume means an enterprise agreement, negotiated rather than self-served
- Push reads towards owned data where you can, at $0.001 instead of $0.005
- Audit link posts at $0.200 each. This is usually where an unexpected bill comes from
Successfully setting up your Twitter API access opens up possibilities for automation, analytics, and integration with your social media workflows.
Frequently Asked Questions
How much does the X (Twitter) API cost?
Is there still a free X API tier?
Why does posting a link cost so much more?
Do I still need to apply for a developer account?
What is the difference between an API key and a Bearer token?
My app authenticates but every write fails. Why?
Can I get historical X data through the API?
Do the old tweepy and twitter code snippets still work?
How do I stop the API from running up a bill?
How do I secure my X API keys?
Related Resources
Was this article helpful?
Let us know what you think!