Twitter API: How to Post and Get Analytics With the Twitter API (2024)

In this tutorial, discover how the Twitter API can enhance your business, and learn how to post and get analytics directly from your platform or app on behalf of your users.

Despite its recent upheaval, Twitter remains one of the most visible social media platforms with about 238 million daily active users worldwide. Some of the biggest businesses, brands, and celebrities engage in public conversations with customers and followers every day on Twitter.


Much of this engagement is done manually using Twitter’s apps, either Twitter built apps or 3rd parties apps. But Twitter also has a robust API (Application Programming interface), which opens up a world of possibilities, e.g. Tweet on behalf of your user right from your platform, present rich analytics such as follower growth, or notify your users when someone comments on their posts.

Here is a quick guide on how to integrate the Twitter API, send a post, and get the analytics.

Why Twitter Is Important for Your Business

Businesses are able to engage with customers by using Twitter’s functionality, including promoted tweets, retweets, ads, Twitter Spaces, curation lists, direct messages, website embeds, and annotations. According to Twitter, over 68% of its users purchase from a business they follow. Other studies show that customers prefer to message rather than call customer support, and those who get good support on Twitter are likely to spend more on the brand.

Twitter API: How to Post and Get Analytics With the Twitter API (1)


Twitter’s user demographics are also compelling. The number of monetizable users in the U.S. has steadily increased every year to 41.5 million in 2022. Given all this, is there a way businesses can utilize Twitter better? That’s where APIs come in.

Introduction To Twitter APIs

The Twitter REST API enable web and mobile applications to use Twitter data and features for their unique business needs and customer experiences.

Here are a few interesting business use cases for a Twitter API:

  • A hiring platform (like Indeed) can post new jobs from a client on that client’s Twitter account.
  • A home real estate platform (like Zillow) can publish videos of new rentals on the landlord’s Twitter account and their ads using the ads API.
  • Whenever a shopping season hashtag like “#blackfridaysale” is trending, an e-commerce platform like Shopify can automatically detect it in real-time and tweet the latest products in its inventory.
  • A customer service platform like Intercom can automatically search tweets using the search endpoint, and open tickets for a customer who receives user complaints on Twitter.

If you’re a developer, we’ll walk you through a step-by-step tutorial to start using the Twitter APIs.

Prepare To Use The Twitter API

First, you have to figure out what your app needs, and then configure its details in Twitter’s developer portal.

1. Select the Features and API Versions You Need

Twitter APIs have multiple versions like Twitter API v2, Standard v1.1, and Enterprise APIs (or Gnip). Use the API resources page to figure out the list of the versions you’ll need.
Top Twitter API tip: Use Twitter API v2, which is based on GraphQL, for all calls except posting images and videos. Currently only v1.1 supports posting media such as images and videos.

2. API Access Level and Approval

Next, decide the API access level you need from Twitter’s access levels page. Each level unlocks more features and higher rate limits. You get essential access by default without needing any approval. But approval is required for elevated and academic research access. In general, essential access is sufficient to start, and you can apply for elevated access when needed. Note that approval can take up to two weeks or more.

3. Register With the Developer Portal

Sign up for a developer account on the Twitter developer portal, and enter the details of your main app.

4. Configure Settings for Your App

Twitter API: How to Post and Get Analytics With the Twitter API (2)

On logging in, you’ll see your main app under “Projects & Apps.” Select the app and click “Set up” under “User authentication settings.” Configure your app as follows:

  • App permissions: Read and write.
  • Type of App: If your app can send secrets like the client secret securely, select “Confidential client.” If not, select “Public client.” Typically, traditional client-server web apps are confidential while mobile apps without any servers are public clients.
  • Callback URI: Register the endpoints of your app that Twitter can call during user authorization.
  • Website URL: A link to your web application or its information page.

5. Store the Client ID and Secret for Your App

After configuration, you’ll get a client ID and client secret for your app. Store them securely in a database, vault, or similar. Either design your application to read them securely, or set up your server to read and inject them into your application’s environment.

6. Decide on Direct Calls or a Client SDK Package

You can either make all the Twitter REST API calls directly or use one of the many Twitter Client SDK packages. Our favorite for Node.js is twitter-api-v2 since it supports most features (v1.1 and v2) and is maintained. We also recommend testing the API calls in Postman…it makes life a lot easier.

For the rest of this article, we’ll stick with direct REST API calls.

Get Consent From Your Users to Tweet on Their Behalf

To tweet or get analytics on behalf of your users, you must first get their consent. This step is called authorization and is implemented using the OAuth 2.0 authorization code flow. Its outcome is an access token per user that enables your application to call Twitter’s APIs.

1. Provide a Link or Button to Let Your Users Authorize

By clicking it, your users can initiate the authorization flow. Call your app’s /authorize endpoint when it’s clicked.

2. Generate the Authorization URL

Twitter API: How to Post and Get Analytics With the Twitter API (3)

In your /authorize endpoint, create an authorization URL and redirect your user there. It’ll open an authorization page owned by Twitter.

Authorization URL format:

https://twitter.com/i/oauth2/authorize?
response_type=code
&scope=tweet.read%20tweet.write%20users.read%20offline.access
&client_id={client-id}
&redirect_uri={registered-url}
&state={state}
&code_challenge={challenge}&code_challenge_method=S256

The important parameters here are:

  • redirect_uri={registered-url}: An endpoint of your web or native app that’s also registered in the developer portal. Twitter sends the authorization code here.
  • client_id={client-id}: Your app’s client ID from the developer portal.
  • scope: The permissions your app needs. Though you just want permission to post, the posting endpoint itself requires the first three.

Generate the other values using this boilerplate:

const state = randomstring.generate(48);const codeVerifier = randomstring.generate(128);const base64Digest = crypto.createHash("sha256").update(codeVerifier).digest("base64");const codeChallenge = base64url.fromBase64(base64Digest);

3. Receive the Authorization Code

Once a user has authorized your app, Twitter sends the authorization code for that user to your app’s redirect_uri endpoint:

GET https://REDIRECT-URL?code={auth-code}&state={state}

4. Exchange the Code for an Access Token

Use that authorization code to obtain an access token from the API v2 endpoint, 2/oauth2/token:

POST https://api.twitter.com/2/oauth2/token

The parameters are:

  • grant_type=authorization_code
  • code={auth-code}: The authorization code you received.
  • redirect_uri={registered-url}: Same redirect URL sent earlier.
  • code_verifier={verifier}: The codeVerifier calculated earlier.
  • Header Authorization: Basic {client-credentials}
  • Header Content-Type: application/x-www-form-urlencoded;charset=UTF-8

Get the {client-credentials} by combining the client ID and secret:

const clientCreds = ${clientId}:${clientSecret};const clientCreds = Buffer.from(clientCreds).toString('base64');

The response JSON:

{ "access_token": "…", "refresh_token": "…", "token_type": "bearer", "expires_in": 7200, "scope": "tweet.read tweet.write users.read offline.access"}

This access token expires in two hours. But using the refresh token, you can request new access tokens from the same endpoint.

You should treat refresh tokens like passwords. Encrypt and store them securely in your database or vault.

Post a Tweet With the Twitter API V2

It’s taken us many steps just to get that access token of your user. Luckily, things get easier now.
Post your first request as your user with these parameters and headers:

POST https://api.twitter.com/2/tweets
  • text={tweet}: The text of your tweet (required)
  • Header Authorization: Bearer {access_token}
  • Header Content-Type: application/json

If the request succeeds, you receive a 200 (success) with this JSON:

{ "data": { "id": "1591766215437361152", "text": "The text of your tweet" }}

The ID returned is the Tweet ID and can be used to directly link to the Tweet:

https://twitter.com/{user}/status/{ID}

But if something’s wrong or missing in the app settings or request headers, it responds with a 403 (forbidden) status:

{ "title": "Forbidden", "type": "about:blank", "status": 403, "detail": "Forbidden"}

A tweet request using Node.js with JavaScript looks like this:

import fetch from 'node-fetch';// Get the access token for the current user.// from your database / vault / keyring, etc.const accessTokenOfUser = getAccessTokenOfLoggedInUser();const params = {'text': 'Your tweet'};const apiResp = await fetch('https://api.twitter.com/2/tweets', { method: 'POST', headers: { 'Authorization': Bearer ${accessTokenOfUser}, 'Content-Type': 'application/json' }, body: JSON.stringify(params)});const tweet = await apiResp.json();

Get Analytics With the Twitter API v2

Get metrics for a tweet from the tweets lookup endpoint by specifying the information you want in tweet.fields:

GET https://api.twitter.com/2/tweets/{ID}?tweet.fields=public_metrics,organic_metrics,non_public_metrics
  • {ID}: A tweet ID
  • tweet.fields: One or more of public_metrics, organic_metrics, non_public_metrics, and promoted_metrics. The metrics doc explains them. Use commas to separate multiple values.
  • Header Authorization: Bearer {access_token}

An example JSON response:

{ "data": { "id": "1591766215437361152", "public_metrics": { "retweet_count": 0, "reply_count": 0, "like_count": 0, "quote_count": 0 }, "non_public_metrics": { "impression_count": 4, "user_profile_clicks": 0 }, "organic_metrics": { "retweet_count": 0, "impression_count": 4, "reply_count": 0, "like_count": 0, "user_profile_clicks": 0 }, "text": "The text of your tweet", … }}

Using Node.js with JavaScript:

import fetch from 'node-fetch';const accessTokenOfUser = getAccessTokenOfLoggedInUser();const tweetId = 'A-TWEET-ID';const tweetUrl = https://api.twitter.com/2/tweets/${tweetId} + '?tweet.fields=public_metrics,organic_metrics,non_public_metrics';const apiResp = await fetch(tweetUrl, { headers: { 'Authorization' : Bearer ${accessTokenOfUser}} });const metrics = await apiResp.json();


An Easier Alternative to the Twitter API

Congratulations if you got through the long list of steps needed to use Twitter’s API. You can drastically cut down on this by using Ayrshare’s social media API instead as an alternative to the Twitter API.

Posting a tweet using our API’s Twitter integration and Social API NPM package is as easy as this:

// Install Ayrshare’s Node package: npm i social-media-apiimport SocialPost from 'social-media-api';// 1. Get your API key from https://app.ayrshare.com/api.// 2. Add it to your application’s environment.// export AYRSHARE_API_KEY=YOUR-AYRSHARE-API-KEYconst social = new SocialMediaAPI(process.env.AYRSHARE_API_KEY);const post = social.post({ "post": "Your tweet", "platforms": ["twitter"]}).then((json) => console.log(json)).catch(console.error);

The prerequisites are also simple. Just sign up for Ayrshare, get your API key, link to your users’ Twitter accounts, and start calling. You don’t have to struggle with OAuth, app settings, credential security, approval, or Twitter’s docs.

Twitter API: How to Post and Get Analytics With the Twitter API (4)

Try out more examples with Ayrshare’s APIs or see our other integrations such as Python, Airtable, and Bubble.

1. Tweet With Ayrshare, Node, and Fetch

You don’t have to use our NPM package or other integrations. Calling our API using your preferred HTTP package is just as simple! Here’s an example using the node-fetch package:

const params = { 'post': 'Your tweet', 'platforms': ['twitter']}const apiResp = await fetch('https://app.ayrshare.com/api/post', { method: 'POST', headers: { 'Authorization' : Bearer ${process.env.AYRSHARE_API_KEY}, 'Content-Type': 'application/json' }, body: JSON.stringify(params)});const tweet = await apiResp.json();

2. Post a Twitter Thread With Ayrshare, Python, and Requests

Posting a numbered thread of tweets requires just two additional options. Ayrshare automatically breaks up your lengthy message into a numbered sequence of tweets. Compare this to the Twitter API where you have to post each tweet with details of its previous tweet.

import osimport requestsparams = { 'post': 'Your lengthy essay…', 'platforms': ['twitter'], 'twitterOptions': { 'thread': True, 'threadNumber': True }}headers = { 'Authorization': f'Bearer {os.environ["AYRSHARE_API_KEY"]}', 'Content-Type': 'application/json'}r = requests.post('https://app.ayrshare.com/api/post', json=params, headers=headers)tweet = r.json()

3. Tweet an Image or Video Using Ayrshare’s Python Package

For images and videos in your user’s tweets, Twitter API expects you to upload them to its /media/upload endpoint, keep track of their details, and pass them to the tweets endpoint.

Using Ayrshare, just set the mediaUrls option to a list of links.

Remember that you need a premium, business, or enterprise plan to tweet videos or more than one image.

If you don’t have a server for your media, you can upload them to our /media API endpoint.

import os# python -m pip install -U social-post-apifrom ayrshare import SocialPostparams = { 'post': 'Your tweet', 'platforms': ['twitter'], 'mediaUrls': ['https://IMAGE–LINK1', 'https://IMAGE-LINK2']}social = SocialPost(os.environ["AYRSHARE_API_KEY"])result = social.post(params)

Get Analytics for Your Posts

How can your users know if their posts and engagements are doing well? You can get detailed metrics for their posts and present the data:

POST https://app.ayrshare.com/api/analytics/post

See the analytics API reference for the full response.

Boost Your Users’ Online Presence With Twitter API Posting

As a powerful social media platform, Twitter can benefit your customers and drive business. Moreover, by learning the basics of both Twitter and Ayrshare APIs, you can further improve engagement.

For more in-depth information about Twitter, check out our top 7 tips and tricks for Twitter API posting and top 10 social media APIs for developers.

Twitter API: How to Post and Get Analytics With the Twitter API (2024)

FAQs

How do I get Twitter Analytics API? ›

First, you have to figure out what your app needs, and then configure its details in Twitter's developer portal.
  1. Select the Features and API Versions You Need. ...
  2. API Access Level and Approval. ...
  3. Register With the Developer Portal. ...
  4. Configure Settings for Your App. ...
  5. Store the Client ID and Secret for Your App.
Dec 6, 2022

How do I get Twitter data from Twitter API? ›

  1. Step 1: Sign up for access. In order to get started with the new Twitter API, you need a developer account. ...
  2. Step 2: Create a Project and connect an App. Next, in the developer portal, create a new Project. ...
  3. Step 3: Make an HTTP request to one of the new endpoints.

How do I get detailed Twitter analytics? ›

If you're already signed in to your account, you can access Analytics through the sidebar menu on the desktop version of Twitter. Click the ellipsis icon at the bottom of the menu and select Analytics. On the Analytics dashboard, you'll find a few different tabs where you can access the various features available.

How to post a tweet with Twitter API? ›

Save this file as twitter.py .
  1. Make a connection with the Twitter API using this set of keys: twitter = Twython( consumer_key, consumer_secret, access_token, access_token_secret )
  2. Start with a basic “Hello world” tweet to test the connection works: message = "Hello world!" twitter.

How do I scrape data from Twitter API? ›

Here is how to use twscrape to scrape Twitter data:
  1. Install twscrape via pip.
  2. Add Twitter accounts to twscrape to work around API usage limits.
  3. Use twscrape's functions to scrape tweets, user profiles, or search results based on your criteria.
  4. Export the scraped data for analysis.
Jun 22, 2024

How to get Twitter data for analysis? ›

Twitter API: Twitter's official API allows for programmatic access to tweet data.
  1. Use Twitter Developer account to access API.
  2. Tailor queries using API parameters.
Apr 12, 2024

What information can I get from Twitter API? ›

  • Data dictionary.
  • Fields.
  • Expansions.
  • Tweet annotations.
  • Metrics.
  • Conversation ID.
  • Pagination.
  • Versioning.

How do I download Twitter analytics data? ›

Export Data

For a more detailed analysis or to share campaign performance with teammates, you can export your campaign data. The 'Export' button - usually found at the top-right of the page - allows you to export data in a CSV format. Select your desired date range and click on 'Export.

How much does Twitter API data cost? ›

X API access levels and versions
FreeBasic
Getting accessGet StartedGet Started
PriceFree$100/month
Access to X API v2✔️ (Only Post creation)✔️
Access to standard v1.1✔️(Only Media Upload, Help, Rate Limit, and Login with X)✔️(Only Media Upload, Help, Rate Limit, and Login with X)
7 more rows

What has happened to Twitter analytics? ›

Users can no longer track their tweet metrics because they cannot access the tool's feature on mobile devices. However, this does not spell the end of Twitter analytics. The tool is still very active and reliable. You can use Twitter analytics on the web to view much more metrics than provided on the mobile app.

Do I need to pay for Twitter analytics? ›

X (Twitter) analytics is a set of key metrics used by the social media platform to track follower count, engagement, impressions, retweets, and more. Twitter analytics are available to view for free through the platform for all users, including personal profiles, professional accounts, and X Premium subscribers.

Why can't i see my Twitter analytics? ›

Twitter Analytics won't work if it's not been more than two weeks since you created your account. The platform requires you to wait at least 14 days before checking this dashboard. Fortunately, the solution is simple if this is the reason you're facing this issue.

Can I still use Twitter API? ›

As announced previously, we have deprecated our legacy Twitter API access tiers. Thus, essential and elevated packages are no longer available. Applications and projects have been placed in the appropriate new Free access tier.

Can I use Twitter API for business? ›

Use Twitter's powerful APIs to help your business listen, act, and discover. Build for people on Twitter, to enhance and improve their experience on the platform. Enhance the Twitter Ads experience with unique innovations and efficiencies for advertisers.

How do you post tweets using Twitter API postman? ›

Send the tweet
  1. Configure the request. After forking it, go to the Postman workspace where you saved it, click on the “Manage Tweets” section and select “Create a Tweet”. ...
  2. Send the Tweet. Finally, go to the “Body” tab and change the value of the “text” key in the JSON body that should be there by default.
Sep 14, 2023

Can I access Twitter API for free? ›

Twitter API rate limits and pricing

In most cases, Twitter API are not used by developers for free. There are certain limits for applying Twitter data in projects. To learn more, read Twitter's reference of rate limiting. There's also some info about the GET endpoints there.

How do I get my Twitter API? ›

When you create your Twitter 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.

How do I download Twitter Analytics data? ›

Export Data

For a more detailed analysis or to share campaign performance with teammates, you can export your campaign data. The 'Export' button - usually found at the top-right of the page - allows you to export data in a CSV format. Select your desired date range and click on 'Export.

How do I get accepted for Twitter API? ›

Step one: Sign up for a developer account

Next you will create a Project and an associated developer App during the onboarding process, which will provide you a set of credentials that you will use to authenticate all requests to the API.

Top Articles
Minnesota hunter walking trails revitalized with $300,000 LCCMR grant ahead of ruffed grouse season
Download Angry Bull City Attack: Wild Bull Simulator Games - Latest Version - APKPanda
Katie Pavlich Bikini Photos
Pet For Sale Craigslist
Garrison Blacksmith Bench
Inducement Small Bribe
Tyrunt
Moviesda Dubbed Tamil Movies
2024 Non-Homestead Millage - Clarkston Community Schools
Pittsburgh Ultra Advanced Stain And Sealant Color Chart
Nba Rotogrinders Starting Lineups
Carolina Aguilar Facebook
Overton Funeral Home Waterloo Iowa
Kürtçe Doğum Günü Sözleri
1v1.LOL - Play Free Online | Spatial
Royal Cuts Kentlands
Drago Funeral Home & Cremation Services Obituaries
Minnick Funeral Home West Point Nebraska
What Are The Symptoms Of A Bad Solenoid Pack E4od?
Devotion Showtimes Near Regency Buenaventura 6
Www Pointclickcare Cna Login
Sofia the baddie dog
Roanoke Skipthegames Com
Urbfsdreamgirl
Paris Immobilier - craigslist
Evil Dead Rise Showtimes Near Sierra Vista Cinemas 16
Effingham Daily News Police Report
Tamil Movies - Ogomovies
Where to eat: the 50 best restaurants in Freiburg im Breisgau
Things to do in Pearl City: Honolulu, HI Travel Guide by 10Best
Albertville Memorial Funeral Home Obituaries
Vlacs Maestro Login
Craigslist/Phx
Craigslist Cars And Trucks Mcallen
Manuel Pihakis Obituary
Teenbeautyfitness
Jay Gould co*ck
Morlan Chevrolet Sikeston
Hermann Memorial Urgent Care Near Me
Ukg Dimensions Urmc
Ludvigsen Mortuary Fremont Nebraska
Deshuesadero El Pulpo
Cranston Sewer Tax
Gfs Ordering Online
Shipping Container Storage Containers 40'HCs - general for sale - by dealer - craigslist
Craigslist/Nashville
Candise Yang Acupuncture
Go Nutrients Intestinal Edge Reviews
Lagrone Funeral Chapel & Crematory Obituaries
Factorio Green Circuit Setup
What Responsibilities Are Listed In Duties 2 3 And 4
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 5842

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.