Getting the follower count from Twitter API v2
Published: 2022-01-20 15:18:23

Version 2 of the Twitter API has been [the primary way to access the developer platform since November](https://blog.twitter.com/developer/en_us/topics/tools/2021/build-whats-next-with-the-new-twitter-developer-platform), but, with around 10 years of blog tutorials about v1.1, there is a lot less information shared by the developer community about the new version. Let's start to change that!

Here's a great question I just answered in [the Twitter tag on Stack Overflow](https://stackoverflow.com/questions/tagged/twitter): 

> "How do I find the number of followers for a Twitter user in API v2?"

You can see the full question (and my answer) embedded below. I thought I'd post here in order to expand on my response a little.

{% stackoverflow 70779246 %}

The answer is quite simple, but not everyone is familiar with the new data formats yet. In v2, we have reduced the number of fields returned by default, and you can opt to select the information that is useful for your application, using the [fields and expansions parameters](https://developer.twitter.com/en/docs/twitter-api/data-dictionary/using-fields-and-expansions).

The follower and following counts for a user are part of the `public_metrics` fields in the User object.

The API endpoint and parameters are in the format

`https://api.twitter.com/2/users/[ID]?user.fields=public_metrics,[any other fields]`

Below is an example of the output, using the [`twurl`](https://github.com/twitter/twurl) command line tool ([I wrote a post about `twurl` here](https://dev.to/twitterdev/how-to-use-twurl-to-quickly-test-the-twitter-api-4n48)). In this case, `twurl` handles the authentication etc, but you could also use the [Twitter API v2 Postman Collection](https://t.co/twitter-api-postman), or the [API Explorer](https://developer.twitter.com/apitools/api?endpoint=%2F2%2Fusers%2F%7Bid%7D&method=get) from the API Tools available on the developer website, or a [library](https://developer.twitter.com/en/docs/twitter-api/tools-and-libraries/v2) of your choice.

```shell
$ twurl -j "/2/users/786491?user.fields=public_metrics,created_at"
{
  "data": {
    "id": "786491",
    "username": "andypiper",
    "created_at": "2007-02-21T15:14:48.000Z",
    "name": "andypiper.xyz",
    "public_metrics": {
      "followers_count": 16570,
      "following_count": 3247,
      "tweet_count": 134651,
      "listed_count": 826
    }
  }
}
```

In this call, we've requested user ID `786491` (which is me! [give me a follow](https://twitter.com/intent/follow?user_id=786491), if you feel like it). By default without any parameters, calls to the [users lookup endpoint](https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-id) only return the `id`, `name` and `username` values. Here, we added the `user.fields` to also ask for the `public_metrics` - followers, following, number of Tweets I've posted, and the number of lists the account has been added to.

So the answer to the original question: **_to get the follower count, ask for the `public_metrics` field in the User object, and access `data.public_metrics.followers_count` in the response._**

---

Let's take it one step further. Expansions and fields are powerful. Using an expansion, we can also ask for my current pinned Tweet and more details about the contents of that Tweet, in a single API call:

```shell
$ twurl -j "/2/users/786491?user.fields=public_metrics,created_at,pinned_tweet_id&expansions=pinned_tweet_id&tweet.fields=created_at,public_metrics,source,context_annotations,entities"
{
  "data": {
    "public_metrics": {
      "followers_count": 16571,
      "following_count": 3247,
      "tweet_count": 134654,
      "listed_count": 826
    },
    "pinned_tweet_id": "1482011997814374406",
    "id": "786491",
    "username": "andypiper",
    "created_at": "2007-02-21T15:14:48.000Z",
    "name": "andypiper.xyz"
  },
  "includes": {
    "tweets": [
      {
        "public_metrics": {
          "retweet_count": 31,
          "reply_count": 5,
          "like_count": 547,
          "quote_count": 1
        },
        "entities": {
          "urls": [
            {
              "start": 113,
              "end": 136,
              "url": "https://t.co/lCaoNcXcyL",
              "expanded_url": "https://dev.to/andypiper/what-resources-help-you-to-learn-a-new-api-2cc9",
              "display_url": "dev.to/andypiper/what…",
              "images": [
                {
                  "url": "https://pbs.twimg.com/news_img/1482011998338654212/0NiDLEms?format=jpg&name=orig",
                  "width": 1000,
                  "height": 500
                },
                {
                  "url": "https://pbs.twimg.com/news_img/1482011998338654212/0NiDLEms?format=jpg&name=150x150",
                  "width": 150,
                  "height": 150
                }
              ],
              "status": 200,
              "title": "What resources help you to learn a new API?",
              "description": "In my day job, when I'm not learning things by reading and sharing here on DEV, I'm a developer...",
              "unwound_url": "https://dev.to/andypiper/what-resources-help-you-to-learn-a-new-api-2cc9"
            }
          ],
          "annotations": [
            {
              "start": 97,
              "end": 103,
              "probability": 0.9056,
              "type": "Product",
              "normalized_text": "Twitter"
            }
          ]
        },
        "text": "I'd love to know more about how you learn to use new APIs, and how I can help you to learn about Twitter API v2. https://t.co/lCaoNcXcyL",
        "id": "1482011997814374406",
        "source": "Twitter Web App",
        "context_annotations": [
          {
            "domain": {
              "id": "46",
              "name": "Brand Category",
              "description": "Categories within Brand Verticals that narrow down the scope of Brands"
            },
            "entity": {
              "id": "781974596752842752",
              "name": "Services"
            }
          },
          {
            "domain": {
              "id": "47",
              "name": "Brand",
              "description": "Brands and Companies"
            },
            "entity": {
              "id": "10045225402",
              "name": "Twitter"
            }
          }
        ],
        "created_at": "2022-01-14T15:29:29.000Z"
      }
    ]
  }
}
```

# 🤯 

OK, that's a lot more information! Let's break it down.

Here, I did the following:

- added the `user.field` to request `pinned_tweet_id`, which returned `"pinned_tweet_id": "1482011997814374406"`
- also, I asked for this to be _expanded_ in the response (`expansions=pinned_tweet_id`). That gets expanded inside of the `includes` array in the response.
- by default, the API only returns the `id` and `text` fields for a Tweet object, so I also specified that I wanted more information. I asked for `tweet.fields` and specified `created_at`, `public_metrics`, `source`, `context_annotations`, and `entities`
 - `created_at`: creation time of the Tweet, the UTC time when I posted it.
 - `public_metrics`: similar to metrics on the User object, we get data about the numbers of retweets, replies, likes and quotes of this Tweet.
 - `source`: the name of the App that was used to post the Tweet (the Twitter website in this case)
 - `context_annotations`: OK, this is _super cool_. We get back an array of information (domain/entity pairs) that cover what Twitter has detected this Tweet to be about. In this case I was posting about the Twitter API, so it pulled out that I'm talking about a brand and company (Twitter) in the Tweet. There are also domains and entities for [things like movies, sports, products, award shows, and so on](https://developer.twitter.com/en/docs/twitter-api/annotations/overview). You can even search for Tweets by entity value using the v2 API - very powerful.  
 - `entities`: this is also an improvement / additional set of data over v1.1. The entities identified in my original Tweet are broken out and expanded. In this case, there was a shortened URL to a [blog post here on DEV](https://dev.to/andypiper/what-resources-help-you-to-learn-a-new-api-2cc9). This is expanded to show the full URL, and what is displayed in the Tweet, as well as the URL to the image that is displayed in the website [summary large image card](https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/summary-card-with-large-image) (and the dimensions of that image), and the description from that card.  

Read more about the [new Twitter data formats and Tweet payloads](https://blog.twitter.com/developer/en_us/topics/tips/2020/understanding-the-new-tweet-payload) on the Developer Blog. Talk to us via the [Twitter Developer Community forums](https://twittercommunity.com).

Share what you learn about Twitter API v2 here on DEV! Use the [`twitter` tag](https://dev.to/t/twitter). It will help others to learn, too.

Finally, if you found this interesting or helpful, I'd love to hear from you in the comments, or [on Twitter](https://twitter.com/andypiper). Happy coding! 💻