DEV Community

Mario García
Mario García

Posted on

Python: Posting on X with Tweepy

There are a few libraries for Python that can be used to get access to the X API. I used twitter previously for a project that is documented here and can be found in this GitLab repository.

Due to the recent changes in the X API, and the library not being updated in about a year, I was getting the following error:

details: {'errors': [{'message': 'You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, oauth) only. If you need access to this endpoint, you may need a different access level. You can learn more here:', 'code': 453}]}
Enter fullscreen mode Exit fullscreen mode

The solution was to used Tweepy, a Python library well documented and prepared to be used with the version 2 of the X API.

Through this blog post, you will learn how to use Tweepy for posting updates on X.

Create an app in the X Developer Portal

If you don't have a developer account, you must create one, in order to use the X API. You have to apply for getting access.

Once you're developer account is approved, go to and create a new app, then generate the API Key and Secret, and an Access Token and Secret for your app.


To install the latest version of Tweepy you can use pip:

pip install tweepy
Enter fullscreen mode Exit fullscreen mode

Posting from Python

Let's create a script to post updates on X.

First, import the Tweepy library into your project:

import tweepy
Enter fullscreen mode Exit fullscreen mode

Then, add the following variables:

consumer_key = '' #API Key
consumer_secret = '' #API Key Secret
access_token = ''
access_token_secret = ''
Enter fullscreen mode Exit fullscreen mode

Authenticate with your credentials to be able to use the X API:

client = tweepy.Client(
    consumer_key=consumer_key, consumer_secret=consumer_secret,
    access_token=access_token, access_token_secret=access_token_secret
Enter fullscreen mode Exit fullscreen mode

And finally, create a new post on X:

text = 'Hello, World!'
Enter fullscreen mode Exit fullscreen mode

This is a basic example of Tweepy. Check the documentation for additional information and examples.

Top comments (0)