Twitter API: How to Post and Get Analytics With the Twitter API

gbourne

Geoffrey Bourne

Posted on December 24, 2022

Twitter API: How to Post and Get Analytics With the Twitter API

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.

alt text

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

alt text

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

alt text

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

The response JSON:

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

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
Enter fullscreen mode Exit fullscreen mode
  • 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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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

https://twitter.com/{user}/status/{ID}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • {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",
  
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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 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-post-api
import SocialPost from 'social-post-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-KEY

const social = new SocialPost(process.env.AYRSHARE_API_KEY);
const post = social.post({
  "post": "Your tweet",
  "platforms": ["twitter"]
})
.then((json) => console.log(json))
.catch(console.error);
Enter fullscreen mode Exit fullscreen mode

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.

alt text

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();
Enter fullscreen mode Exit fullscreen mode

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 os
import requests

params = {
  '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()
Enter fullscreen mode Exit fullscreen mode

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-api
from ayrshare import SocialPost

params = {
  'post': 'Your tweet',
  'platforms': ['twitter'],
  'mediaUrls': ['https://IMAGE–LINK1', 'https://IMAGE-LINK2']
}

social = SocialPost(os.environ["AYRSHARE_API_KEY"])

result = social.post(params)
Enter fullscreen mode Exit fullscreen mode

Get Analytics for Your Social 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
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
gbourne
Geoffrey Bourne

Posted on December 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related