🦜 Twitter API: From username to userId with JavaScript

If you want to download the tweets for a given Twitter user you first need to get the userId for that account. For this purpose Twitter provides the API GET /2/users/by that can return the userId as well as some other information such as the creation date of the account, the description, the name, the url, etc.

In order to use this endpoint, we need to use a couple of query parameters in the URL:

  • username: the username of the account for which we need the id
  • user.fields: a set of fields identifying the information we want to retrieve (in our case the id)

The query string can be built using the SearchParams object:

const searchParams = new SearchParams({
  usernames: ['marcostlco'],
  'user.fields': ['id', 'created_at', 'description', 'name', 'url']
});

Then we can convert these parameters to a string with the toString() method and append it to the API url provided by Twitter:

const url = `https://api.twitter.com/2/users/by?${searchParams.toString()}`;

Now we need to build the request itself. I’m using the node-fetch package to execute the HTTP requests (to install it as your dependency you can run npm i node-fetch in the terminal).

import fetch from 'node-fetch';

const response = await fetch(url, {
  method: "GET",
  headers: {
    Authorization: BEARER,
  },
});

The fetch method accepts a url and an object with some options such as the method (GET in our case), and the authorization header, needed to authenticate your request. The bearer token is provided by Twitter when you create your application in the Twitter developer portal.

Once the request has been executed we need to parse and read the response:

const { data } = await response.json();

const userId = data.id

The json() method will convert the body of the response into a JavaScript object. This object will contain a field called data with all the information returned by Twitter.

The userId will be the id field of the data object and we’ll be able to use it to execute some other requests to the Twitter API.