Twitter API: How to Post and Get Analytics With the Twitter API
Tags: twitter, api, programming, socialmedia
Published: 2022-12-24 19:00:34


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](https://www.statista.com/statistics/970920/monetizable-daily-active-twitter-users-worldwide/) 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](https://help.twitter.com/en/using-twitter/spaces), curation lists, direct messages, website embeds, and [annotations](https://developer.twitter.com/en/docs/twitter-api/annotations/overview). According to Twitter, over [68% of its users purchase](https://business.twitter.com/en/blog/how-valuable-are-your-followers.html) from a business they follow. Other studies show that [customers prefer to message](https://business.twitter.com/en/blog/how-twitter-has-become-a-key-customer-support-channel.html) rather than call customer support, and those who get good support on Twitter are likely to spend more on the brand.

![alt text](https://www.ayrshare.com/wp-content/uploads/amazon-twitter-1.jpg "Twitter-Account")

Twitter’s user demographics are also compelling. The number of monetizable users in the U.S. has [steadily increased](https://www.statista.com/statistics/970911/monetizable-daily-active-twitter-users-in-the-united-states/) 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](https://developer.twitter.com/en/docs/twitter-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](https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#item2) to figure out the list of the versions you’ll need.

[Top Twitter API tip](https://www.ayrshare.com/top-7-tips-and-tricks-for-twitter-api-posting/): Use Twitter API v2, which is based on [GraphQL](https://graphql.org/), 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](https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#item0) 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](https://developer.twitter.com/en/portal/dashboard), and enter the details of your main app.

### 4. Configure Settings for Your App

![alt text](https://www.ayrshare.com/wp-content/uploads/twitter-api-developer-portal.jpg "Twitter Developer Portal")

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](https://developer.twitter.com/en/docs/twitter-api/tools-and-libraries/v2). Our favorite for Node.js is [twitter-api-v2](https://www.npmjs.com/package/twitter-api-v2) since it supports most features (v1.1 and v2) and is maintained. We also recommend [testing the API calls in Postman](https://developer.twitter.com/en/docs/tutorials/postman-getting-started)…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](https://www.ayrshare.com/wp-content/uploads/twitter-api-authorization.jpg "Twitter OAuth")

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:

```bash
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](https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets).

Generate the other values using this boilerplate:

```javascript
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:

```bash
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`:

```bash
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:

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

The response JSON:

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

```bash
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:

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

```bash
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:

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

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

```javascript
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](https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/introduction) endpoint by specifying the information you want in `tweet.fields`:

```bash
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](https://developer.twitter.com/en/docs/twitter-api/metrics) explains them. Use commas to separate multiple values.
- Header `Authorization: Bearer {access_token}`

An example JSON response:

```json
{
  "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:

```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 as an [alternative to the Twitter API](https://docs.ayrshare.com/).

Posting a tweet using our API’s [Twitter integration](https://docs.ayrshare.com/rest-api/endpoints/post/twitter) and [Social API NPM package](https://www.npmjs.com/package/social-post-api) is as easy as this:

```javascript
// 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);
```

The prerequisites are also simple. Just [sign up for Ayrshare](https://app.ayrshare.com/), get your API key, link to your [users’ Twitter accounts](https://docs.ayrshare.com/gui-dashboard/connect-social-media#twitter-link), and start calling. You don’t have to struggle with OAuth, app settings, credential security, approval, or Twitter’s docs.

![alt text](https://www.ayrshare.com/wp-content/uploads/ayrshare-twitter-api.jpg "Ayrshare API Dashboard")

Try out more examples with Ayrshare’s APIs or see our [other integrations](https://docs.ayrshare.com/packages/overview) 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:

```javascript
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.

```python
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()
```

### 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](https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/overview), keep track of their details, and pass them to the [tweets endpoint](https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets).

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](https://docs.ayrshare.com/rest-api/endpoints/media).

```python
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)
```

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

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

See the [analytics API reference](https://docs.ayrshare.com/rest-api/endpoints/analytics) 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](https://www.ayrshare.com/top-7-tips-and-tricks-for-twitter-api-posting/) posting and [top 10 social media APIs for developers](https://www.ayrshare.com/top-10-social-media-apis-for-developers/).