top of page

How to connect to Twitter X API using Python

The Twitter API (aka X API) is a powerful tool that allows developers to interact with Twitter data programmatically. Whether you’re building a bot, analyzing trends, or integrating Twitter into your application, connecting to the Twitter API is a crucial first step. In this guide, we’ll walk you through the process of setting up and connecting to the Twitter API. On this occasion, we will be using a free account, where there are limitations on endpoints, request limits, and creation of projects. This is a good place to start and set up your first connection with X API.


Step 1: Create a Twitter Developer Account

Before you can access the Twitter API, you need to create a Twitter Developer Account and set up a project. Here’s how to do it:


1. Sign up for a Twitter Developer Account:

• Go to the Twitter Developer site.

• Click on “Developer Portal”

• Click on “Sign up for Free Account” and follow the instructions. You will have to write your use case and you are good to go.


2. Set up the project

• Once your developer account is approved, log in to the Developer Dashboard.

• Click on “Projects & Apps” and go to your Default project.

• Go to your User authentication settings and click on "Set up"

Project Overview Page


• Choose "Read and write and Direct message" for the permissions, "Web App, Automated App or Bot" for type of app and fill with the app info. In our case, for testing purposes, you can check the screenshots below.


User Set up



Step 2: Generate API Keys and Tokens

With your project set up, you will be provided with your Client ID and Client Secret for OAuth 2.0. Save them in a secure place.


1. Navigate to Keys and Tokens:

• Within your project, click on “Keys and Tokens"

• Click on "Regenerate"


2. Store Your Credentials Securely:

• Make sure to store these keys and tokens securely. Do not share them publicly, as they can be used to access your Twitter data.



Step 3: Install the Required Libraries

For making request we need to install:

pip install requests
pip install requests_oauthlib

Step 4: Connect to the Twitter API

With this code you will be requested to authenticate with your user and password for the first time, and provide a passcode into the terminal. After that you will see your user info.

import json
import requests
from requests_oauthlib import OAuth1Session


# Define your API keys and tokens
consumer_key = 'your_api_key'
consumer_secret = 'your_api_key_secret'


# User fields
fields = "created_at,description"
params = {"user.fields": fields}

# Get request token
request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)

try:
    fetch_response = oauth.fetch_request_token(request_token_url)
except ValueError:
    print("There may have been an issue with the consumer_key or consumer_secret you entered.")

resource_owner_key = fetch_response.get("oauth_token")
resource_owner_secret = fetch_response.get("oauth_token_secret")
print("Got OAuth token: %s" % resource_owner_key)

# Get authorization
base_authorization_url = "https://api.twitter.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")

# Get the access token
access_token_url = "https://api.twitter.com/oauth/access_token"
oauth = OAuth1Session(
    consumer_key,
    client_secret=consumer_secret,
    resource_owner_key=resource_owner_key,
    resource_owner_secret=resource_owner_secret,
    verifier=verifier,
)
oauth_tokens = oauth.fetch_access_token(access_token_url)

access_token = oauth_tokens["oauth_token"]
access_token_secret = oauth_tokens["oauth_token_secret"]

# Make the request
oauth = OAuth1Session(
    consumer_key,
    client_secret=consumer_secret,
    resource_owner_key=access_token,
    resource_owner_secret=access_token_secret,
)

response = oauth.get("https://api.twitter.com/2/users/me", params=params)


if response.status_code != 200:
    raise Exception("Request returned an error: {} {}".format(response.status_code, response.text))

print("Response code: {}".format(response.status_code))

json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))

# Save the response JSON
def save_user_info_to_json(user_info, filename='user_info.json'):
    with open(filename, 'w') as file:
        json.dump(user_info, file, indent=4)

save_user_info_to_json(json_response)
print(f"User info saved to JSON file: user_info.json")

You should see a json like this:

{

"data": {

"created_at": "2024-06-07T12:51:39.000Z",

"description": "",

"id": "1799061620154585088",

"name": "BRF Test",

"username": "BrfTest10003"

}

}


Conclusion

By following these steps, you will be able to successfully make your first API call to the X API. This is the only endpoint available for retrieving data using Free account access level. If you would like to explore more capabilities, you would need to go have the Basic, Pro or Enterprise account access levels which do have a fee. Feel free to change the script based on your requirements or reach out to us if you need professional assistance. BRF Consulting can help your business continue to grow and be more efficient, feel free to reach us at contact@brfconsulting.com in case of any questions.


About the author: Smilton Roa is a Data Engineer at BRF Consulting, a company specialized on Data Engineering and Business Intelligence.

15 views0 comments

Comments


bottom of page