Twitter (X) REST API in Python

Exhibit 25.6 demonstrates the Python implementation of the Twitter REST API to retrieve tweets containing the keywords BMW, Mercedes and/or Audi. The process involves the following steps:

  1. Import the Required Libraries: Begin by importing all necessary libraries. We include the json library to easily parse the outputs of the Twitter API, as it returns data in JSON format. JSON, or JavaScript Object Notation, is a lightweight data format that is easy to read and write. It is widely used for storing and transporting data across web applications. We also use the requests module, which allows us to send HTTP requests using Python.
  2. Define the Endpoint URL: Next, store the endpoint URL in a variable. In the context of web APIs, an endpoint refers to a specific URL or address that a client can use to access a particular resource or service provided by the server.
  3. Set Up the Connection Parameters: Now, define the parameters needed to establish a connection with the Twitter API. This includes setting up an OAuth client to handle authentication. OAuth is a protocol that allows you to grant limited access to your resources without exposing your credentials.
  4. Encode and Execute the Query: Encode the query parameters. In this example, we are searching for tweets related to three car brands: BMW, Mercedes, and Audi. After encoding the query, execute a search request using the OAuth client.
  5. Process and Display the Results: The API returns a list of tweets along with their metadata. Convert this data to JSON format and print the content of each tweet by accessing the text field. If the text field exists, decode it to UTF-8 to manage encoding issues before printing it.

Twitter API Tutorial
# Twitter (X) REST API
'''
Note: Twitter (X) ceased providing v2 access for free apps from June 2023 onwards. 
'''

# 1 Import the Required Libraries
import requests
import json

# 2 Define the Endpoint URL (REST API)
url_rest="https://api.twitter.com/2/tweets/search/recent"

# 3 Set Up the Connection Parameters
# Bearer token required to establish connections (authorization)
auth_params = {
'bearer':
    'ENTER_BEARER_TOKEN'
}

# Headers
'''
Headers are additional pieces of information that are sent along with the request to the server. 
They provide metadata about the request or response, such as the content type of the request body, 
the authentication token, or the software client making the request.
'''
headers = {'Authorization': 'Bearer ' + auth_params['bearer']}

# 4 Encode and Execute the Query
query_params = {'query': '(BMW OR Mercedes OR Audi) lang:en','max_results':'30'}

# Execute a search request using query and headers (OAuth client)
results = requests.get(url_rest, params=query_params, headers=headers)

# 5 Process and Display the Results
'''
- Parse the JSON content from the response body 
- Convert it into a Python list 
- Print the ID, text and retweet fields.
'''
for tweet in results.json()['data']:
    print("ID: ", tweet['id'])
    print(tweet['text'])
    if 'retweet_count' in tweet:
        print("Retweets: ", tweet['retweet_count'])
    else:
        print("Retweets: 0")

ID:  1752681723933188464
RT @FastestPitStop: F1 Rumor:

Mercedes title sponsor, Petronas is looking to bring back the Sepang International Circuit back on the F1 ca…
Retweets: 0
ID:  1752681706337767503
@KateFantom @The_PlugSeeker @Tesla @elonmusk @ecocars1 @She_sElectric @PoletoPoleEV @106Euan @jtchivers @RZOC @FoxGeorgiou @EVRevShow Until you drive an Audi or BMW.
Retweets: 0
ID:  1752681680744464671
@Joylou1209 @BTW0205 If you miss a rich Audi, don't miss a PGID. PGID after 20 days of development, the holding address has exceeded 4000+, the ground studio has exceeded 40+, the dark horse PGID of the inscription track, owning it is your wealth! https://t.co/g33jsJLsex
Retweets: 0
ID:  1752681644857626840
Your South Salt Lake, Utah Audi repair quest ends here. At Wofford's European Car, our well-versed technicians combine expertise with cutting-edge technology to deliver unmatched service, repair, and care. Act now to improve your Audi experience with us!

https://t.co/6AJtYUgMHw https://t.co/uDzq0WI3fA
Retweets: 0
ID:  1752681628692857045
RT @drrosemaryreyn1: Lucky to be alive tonight after a lorry swerved into us on M3. Terrifying being spun on motorway and hitting concrete…
Retweets: 0
ID:  1752681621516333526
RT @WrestlingWCC: Saraya shares throwback picture with Mercedes Mone and AJ Lee 💯 https://t.co/8N0H4T7uHs
Retweets: 0
ID:  1752681621243957256
@BTW0205 If you miss a rich Audi, don't miss a PGID. PGID after 20 days of development, the holding address has exceeded 4000+, the ground studio has exceeded 40+, the dark horse PGID of the inscription track, owning it is your wealth! https://t.co/hxnOR9y2wm
Retweets: 0
ID:  1752681606542737656
RT @ShiloteW: 2018 BMW X1 xDrive20d M Sport Auto
Mileage: 103 200

Price: R370 000
Interest rate: 11.75%
Repayment period: 72 months
Instal…
Retweets: 0
ID:  1752681599249068201
RT @BisKota_: TOP

Mercedes Benz OF 1623 Air Suspension https://t.co/cNYcsfc2Ty
Retweets: 0
ID:  1752681566122418368
@CCCCLTDofficial @Chengdu_China If you miss a rich Audi, don't miss a PGID. PGID after 20 days of development, the holding address has exceeded 4000+, the ground studio has exceeded 40+, the dark horse PGID of the inscription track, owning it is your wealth! https://t.co/MARlPOqwr6
Retweets: 0
ID:  1752681555141550465
RT @chainbear: Red Bull: The competition will be fiercer than ever this year
Stake F1: STAKE
Mercedes: Challenging for the title is the onl…
Retweets: 0
ID:  1752681552335765732
@CarsGuide who really in aus is gonna choose a mazda over a bmw or merc . mazda has about as much prestige as $500 suit off the rack from myer sure it will look ok but and it will function but merc and bmw is about prestige and heritage mazda is about so much less.
Retweets: 0
ID:  1752681549953380444
RT @BisKota_: TOP



Exhibit 25.6 Twitter (X) REST API demonstration of Python implementation to retrieve tweets containing the keywords BMW, Mercedes and/or Audi.


Previous     Next

Use the Search Bar to find content on MarketingMind.