Social Media

How to Get an X (Twitter) API Key: Setup, Keys and What It Costs

Matt
· Updated 8 min read

TL;DR - Quick Answer

18 min read

Comprehensive 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:

  1. Visit developer.x.com
  2. Sign in with your X account
  3. Accept the developer agreement
  4. 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:

  1. Check email for verification link
  2. Click verification link
  3. Return to developer portal

Phone Verification:

  1. Add phone number if not already added
  2. 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:

  1. Go to the X Developer Portal dashboard
  2. Click "Create App"
  3. 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:

  1. Go to your app dashboard
  2. Click "Keys and Tokens" tab
  3. 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.

OperationPrice
Read a post$0.005 per resource
Read a user$0.010 per resource
Read likes, mutes or blocks$0.001 per resource
Read your own data (posts, bookmarks, followers)$0.001 per resource
Create a post$0.015
Create a post containing a URL$0.200
Create a post when summoned$0.010

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:

  1. Enable read and write permissions
  2. Generate user access tokens
  3. Implement OAuth flow for user authorization
  4. Store tokens securely

Analytics and Research

Required Permissions:

  • Read tweets and user data
  • Access tweet metrics
  • Search historical tweets
  • User lookup capabilities

Setup Steps:

  1. Apply for Academic Research access if applicable
  2. Use bearer token for app only authentication
  3. Implement rate limiting handling
  4. Set up data storage compliance

Automation Bots

Required Permissions:

  • Read tweets
  • Post tweets
  • Like and retweet content
  • Follow/unfollow users

Setup Steps:

  1. Create app with automation use case
  2. Set up user context authentication
  3. Implement proper rate limiting
  4. 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:

  1. Verify keys are correct and complete
  2. Check authentication format
  3. Test with simple API call
  4. Review account status in dashboard

Rate Limit Exceeded

Solutions:

  • Read the x-rate-limit-reset header 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:

  1. Raise your spending limit in the developer console when volume grows
  2. 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
  3. Push reads towards owned data where you can, at $0.001 instead of $0.005
  4. 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?
It is pay-per-usage with no subscription and no minimum spend. X's pricing documentation lists $0.005 per post read, $0.010 per user read, $0.001 for likes, mutes and blocks, $0.015 to create a post and $0.200 to create a post containing a URL. Reads of your own data are $0.001. Pay-per-usage accounts are capped at 2 million post reads per billing cycle.
Is there still a free X API tier?
No. Essential and Elevated Access, the free tiers older guides describe, were retired when Twitter ended free API access in February 2023, and the academic research product went with them. The subscription tiers that replaced them have also been wound down, with legacy Basic subscribers migrated to pay-per-use after 1 June 2026.
Why does posting a link cost so much more?
X prices a post containing a URL at $0.200 against $0.015 for a post without one, more than thirteen times as much. Nothing warns you at call time. If your integration shares links at volume, that single line will dominate your bill, so model it before you build.
Do I still need to apply for a developer account?
No. The application form, the use-case questionnaire and the manual review that took days to weeks are all gone. You sign in at developer.x.com, accept the developer agreement, create a project and app, and set up billing. Guides describing an approval wait are pre-2023.
What is the difference between an API key and a Bearer token?
The API key and secret, also called the consumer key and secret, identify your app and are used with an access token and secret for OAuth calls that act on behalf of a user. The Bearer token is app-only authentication for reading public data with no user context. If you need to post as someone, you need the OAuth pair; if you only need to read, the Bearer token is simpler.
My app authenticates but every write fails. Why?
Almost always app permissions. An app created read-only will authenticate happily and refuse every write, and changing the permission does not update tokens that already exist. Set the app to read and write, then regenerate the access token and secret.
Can I get historical X data through the API?
Recent search covers roughly the last 7 days. Full-archive search is not part of pay-per-usage and the academic tier that used to provide it no longer exists, so deep historical access now means an enterprise agreement. Budget for that before designing around it.
Do the old tweepy and twitter code snippets still work?
Mostly not. tweepy.API with api.update_status and the npm `twitter` package both target v1.1 endpoints that a new project cannot call, which is why those snippets fail with a 403 rather than an authentication error. Use tweepy.Client with create_tweet in Python, and twitter-api-v2 in Node.
How do I stop the API from running up a bill?
Set a spending limit in the developer console before writing any code, cap your retries, cache anything you read twice, and log resources returned rather than calls made, because resources are the billing unit. An uncapped exponential backoff against a failing endpoint is a spending bug.
How do I secure my X API keys?
Environment variables rather than source, never in client-side code or a public repository, never in URLs or logs, rotate them periodically, and watch usage for anomalies. Under pay-per-use a leaked key is a financial exposure as well as a security one.

Was this article helpful?

Let us know what you think!

#SocialMedia#ContentStrategy#DigitalMarketing

📚 Continue Learning

More articles to boost your social media expertise