Sam  Son

Sam Son

1572837121

How to Get Tweets using IDs with Tweepy, Twitter API and Python

In this post, I am going to explain how to fetch tweets using their IDs using Tweepy. I am going to explain why we are doing such thing? Why we store Tweet IDs instead of directly themselves, after that I am going to explain what is Tweepy and how to use that. And lastly we will see an example with Python.

First of all, the question is why we are using Tweet IDs? This is the result of hardware actually. We don’t want to use lots of memory all the time. We don’t have enough space!

After identification of tweets, we store their IDs, it means that we can fetch them later. But is it really necessary? How much space can we save with this method? Here is one example, since I am working on natural disasters in our world, I am searching for datasets all the time. And if you are data scientist, you need a large amount of data to find out correlation. Here is the example; https://crisisnlp.qcri.org is the website which stores and shares some datasets with data scientists to help them. In that website there is a resource number 5, which is about tweets published during seven major natural disasters.

If you want to download tweets of this datasets you need to download a data which is approximately 1.8GB. But if you want to download only their IDs, you need to download only 79MB. So Tweets are 22 times larger than their IDs. Now think about you are collecting data all the time and you have that kind of datasets for every topic. You need to buy lots of hard drive I guess which is of course not preferred. Because of this reason, we prefer to store tweet IDs after we choose and analyze them. That means we can fetch them later when we need it.

Tweepy and Twitter API

After this brief information, let’s assume that we found a good dataset on the internet that we think it will be useful for our work but it only consist of Tweet IDs. How we can fetch them? Tweepy is my answer. What is Tweepy?

Tweepy explain itself as a “An easy-to-use Python library for accessing the Twitter API.” It is actually a library which uses Twitter API. Twitter has it’s own API to access features of itself. In short with Tweepy, it will be much easier to use Twitter API. I am not going to dive in to Twitter API here, but please check this link to learn more: https://developer.twitter.com/en.html

Let’s continue with how to use Tweepy. To use Tweepy first we need to sign up as a Twitter developer. Please see the above link to sign up as a developer and take your credentials. Otherwise you can’t use the Twitter API which results you can’t use Tweepy as well.

Here are the steps for being a Twitter Developer;

Visit this link; https://developer.twitter.com/en/apply-for-access

Via above link you will apply twitter for a developer account.

This is image title

Click the button “Apply for a developer account”.

This is image title

And please login with your account.

So here is the page that welcomes you.

This is image title

Please choose your reason why you want to use Twitter API. And click “Next”. After that there will be some pages to fill details. Twitter want to know more about your aim. You need to describe your project or idea to Twitter specifically. For example I wanted to fetch tweets for my thesis and I have explained details of my thesis to Twitter. After some detailed explanations. And then click “Next” until you submit your application.

Then you can wait for the answer from Twitter. If you receive an email like that, yey! Now you can start to use Twitter API.

This is image title

Being able to send a request to Twitter API, you need to have authentication credentials. You need to create an app in order to have credentials. So please create an app under the section “Apps”.

This is image title

Click the button “Create an app”, and you need to fill some details about your application. Also on the left side of the screen you can see answers of FAQs.

This is image title

After completion of app creation, you have now your credentials under the section “Keys and tokens”.

This is image title

Now it is time for coding! You have everything for your application. Install Tweepy, and use it to invoke the Twitter API.

#This code creates the dataset from Corpus.csv which is downloadable from the
#internet well known dataset which is labeled manually by hand. But for the text
#of tweets you need to fetch them with their IDs.
import tweepy

# Twitter Developer keys here
# It is CENSORED
consumer_key = 'XX'
consumer_key_secret = 'XX'
access_token = 'XX-XX'
access_token_secret = 'XX'

auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# This method creates the training set
def createTrainingSet(corpusFile, targetResultFile):
    import csv
    import time

    counter = 0
    corpus = []

    with open(corpusFile, 'r') as csvfile:
        lineReader = csv.reader(csvfile, delimiter=',', quotechar="\"")
        for row in lineReader:
            corpus.append({"tweet_id": row[2], "label": row[1], "topic": row[0]})

    sleepTime = 2
    trainingDataSet = []

    for tweet in corpus:
        try:
            tweetFetched = api.get_status(tweet["tweet_id"])
            print("Tweet fetched" + tweetFetched.text)
            tweet["text"] = tweetFetched.text
            trainingDataSet.append(tweet)
            time.sleep(sleepTime)

        except:
            print("Inside the exception - no:2")
            continue

    with open(targetResultFile, 'w') as csvfile:
        linewriter = csv.writer(csvfile, delimiter=',', quotechar="\"")
        for tweet in trainingDataSet:
            try:
                linewriter.writerow([tweet["tweet_id"], tweet["text"], tweet["label"], tweet["topic"]])
            except Exception as e:
                print(e)
    return trainingDataSet

# Code starts here
# This is corpus dataset
corpusFile = "datasets/corpus.csv"
# This is my target file
targetResultFile = "datasets/targetResultFile.csv"
# Call the method
resultFile = createTrainingSet(corpusFile, targetResultFile)

Here is the code that I used for fetching tweets. Please fill your tokens and keys here, I have left them as “XX”. I have used the well-known corpus for that. But you can use same code for any other dataset of course. My corpus file looks like;

This is image title

This is corpus which is about some tweets about big companies and labeled as positive, negative or neutral. As you can see, last column is tweet ID.

With the above code, we will take this IDs from corpus file, fetch the tweets one by one and write it to new file named “targetResultFile.csv”. Result will looks like that;

This is image title

There are some key points when running the code. I wanted to explain everything with comments but let’s underline one important point. Twitter has some strict limits. You can’t fetch everything once.

This is image title

Because of this limitations, you need to add some delays to your code or different business logic. Tweepy has it’s unique exceptions for that. I didn’t add this to my example code for now but, you can add the specific code blocks for specific exceptions for example RateLimitError. You can add some delay if you caught that exception. You may need to up t one hour to be able to fetch new tweets if you caught that exception. You can find more information here.

This is image title

After you have successfully fetched you tweets, you may now need to preprocess your tweets. You can continue to read following story about preprocessing tweets to continue learn more about this topic.

We have successfully fetched tweets from Twitter and we are ready to continue! Thank you for your time! Please share if you liked it!

#Python #Twitter #Data Science #Machine Learning #Tweepy

What is GEEK

Buddha Community

How to Get Tweets using IDs with Tweepy, Twitter API and Python
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Sam  Son

Sam Son

1572837121

How to Get Tweets using IDs with Tweepy, Twitter API and Python

In this post, I am going to explain how to fetch tweets using their IDs using Tweepy. I am going to explain why we are doing such thing? Why we store Tweet IDs instead of directly themselves, after that I am going to explain what is Tweepy and how to use that. And lastly we will see an example with Python.

First of all, the question is why we are using Tweet IDs? This is the result of hardware actually. We don’t want to use lots of memory all the time. We don’t have enough space!

After identification of tweets, we store their IDs, it means that we can fetch them later. But is it really necessary? How much space can we save with this method? Here is one example, since I am working on natural disasters in our world, I am searching for datasets all the time. And if you are data scientist, you need a large amount of data to find out correlation. Here is the example; https://crisisnlp.qcri.org is the website which stores and shares some datasets with data scientists to help them. In that website there is a resource number 5, which is about tweets published during seven major natural disasters.

If you want to download tweets of this datasets you need to download a data which is approximately 1.8GB. But if you want to download only their IDs, you need to download only 79MB. So Tweets are 22 times larger than their IDs. Now think about you are collecting data all the time and you have that kind of datasets for every topic. You need to buy lots of hard drive I guess which is of course not preferred. Because of this reason, we prefer to store tweet IDs after we choose and analyze them. That means we can fetch them later when we need it.

Tweepy and Twitter API

After this brief information, let’s assume that we found a good dataset on the internet that we think it will be useful for our work but it only consist of Tweet IDs. How we can fetch them? Tweepy is my answer. What is Tweepy?

Tweepy explain itself as a “An easy-to-use Python library for accessing the Twitter API.” It is actually a library which uses Twitter API. Twitter has it’s own API to access features of itself. In short with Tweepy, it will be much easier to use Twitter API. I am not going to dive in to Twitter API here, but please check this link to learn more: https://developer.twitter.com/en.html

Let’s continue with how to use Tweepy. To use Tweepy first we need to sign up as a Twitter developer. Please see the above link to sign up as a developer and take your credentials. Otherwise you can’t use the Twitter API which results you can’t use Tweepy as well.

Here are the steps for being a Twitter Developer;

Visit this link; https://developer.twitter.com/en/apply-for-access

Via above link you will apply twitter for a developer account.

This is image title

Click the button “Apply for a developer account”.

This is image title

And please login with your account.

So here is the page that welcomes you.

This is image title

Please choose your reason why you want to use Twitter API. And click “Next”. After that there will be some pages to fill details. Twitter want to know more about your aim. You need to describe your project or idea to Twitter specifically. For example I wanted to fetch tweets for my thesis and I have explained details of my thesis to Twitter. After some detailed explanations. And then click “Next” until you submit your application.

Then you can wait for the answer from Twitter. If you receive an email like that, yey! Now you can start to use Twitter API.

This is image title

Being able to send a request to Twitter API, you need to have authentication credentials. You need to create an app in order to have credentials. So please create an app under the section “Apps”.

This is image title

Click the button “Create an app”, and you need to fill some details about your application. Also on the left side of the screen you can see answers of FAQs.

This is image title

After completion of app creation, you have now your credentials under the section “Keys and tokens”.

This is image title

Now it is time for coding! You have everything for your application. Install Tweepy, and use it to invoke the Twitter API.

#This code creates the dataset from Corpus.csv which is downloadable from the
#internet well known dataset which is labeled manually by hand. But for the text
#of tweets you need to fetch them with their IDs.
import tweepy

# Twitter Developer keys here
# It is CENSORED
consumer_key = 'XX'
consumer_key_secret = 'XX'
access_token = 'XX-XX'
access_token_secret = 'XX'

auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# This method creates the training set
def createTrainingSet(corpusFile, targetResultFile):
    import csv
    import time

    counter = 0
    corpus = []

    with open(corpusFile, 'r') as csvfile:
        lineReader = csv.reader(csvfile, delimiter=',', quotechar="\"")
        for row in lineReader:
            corpus.append({"tweet_id": row[2], "label": row[1], "topic": row[0]})

    sleepTime = 2
    trainingDataSet = []

    for tweet in corpus:
        try:
            tweetFetched = api.get_status(tweet["tweet_id"])
            print("Tweet fetched" + tweetFetched.text)
            tweet["text"] = tweetFetched.text
            trainingDataSet.append(tweet)
            time.sleep(sleepTime)

        except:
            print("Inside the exception - no:2")
            continue

    with open(targetResultFile, 'w') as csvfile:
        linewriter = csv.writer(csvfile, delimiter=',', quotechar="\"")
        for tweet in trainingDataSet:
            try:
                linewriter.writerow([tweet["tweet_id"], tweet["text"], tweet["label"], tweet["topic"]])
            except Exception as e:
                print(e)
    return trainingDataSet

# Code starts here
# This is corpus dataset
corpusFile = "datasets/corpus.csv"
# This is my target file
targetResultFile = "datasets/targetResultFile.csv"
# Call the method
resultFile = createTrainingSet(corpusFile, targetResultFile)

Here is the code that I used for fetching tweets. Please fill your tokens and keys here, I have left them as “XX”. I have used the well-known corpus for that. But you can use same code for any other dataset of course. My corpus file looks like;

This is image title

This is corpus which is about some tweets about big companies and labeled as positive, negative or neutral. As you can see, last column is tweet ID.

With the above code, we will take this IDs from corpus file, fetch the tweets one by one and write it to new file named “targetResultFile.csv”. Result will looks like that;

This is image title

There are some key points when running the code. I wanted to explain everything with comments but let’s underline one important point. Twitter has some strict limits. You can’t fetch everything once.

This is image title

Because of this limitations, you need to add some delays to your code or different business logic. Tweepy has it’s unique exceptions for that. I didn’t add this to my example code for now but, you can add the specific code blocks for specific exceptions for example RateLimitError. You can add some delay if you caught that exception. You may need to up t one hour to be able to fetch new tweets if you caught that exception. You can find more information here.

This is image title

After you have successfully fetched you tweets, you may now need to preprocess your tweets. You can continue to read following story about preprocessing tweets to continue learn more about this topic.

We have successfully fetched tweets from Twitter and we are ready to continue! Thank you for your time! Please share if you liked it!

#Python #Twitter #Data Science #Machine Learning #Tweepy

Sival Alethea

Sival Alethea

1624302000

APIs for Beginners - How to use an API (Full Course / Tutorial)

What is an API? Learn all about APIs (Application Programming Interfaces) in this full tutorial for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you’ll have no problem following along.
⭐️ Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:03:57)
⌨️ Video 3 - Defining API (0:07:51)
⌨️ Video 4 - Remote APIs (0:12:55)
⌨️ Video 5 - How the web works (0:17:04)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:22:00)

⭐️ Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:27:36)
⌨️ Video 2 - Using an API from the command line (0:44:30)
⌨️ Video 3 - Using Postman to explore APIs (0:53:56)
⌨️ Video 4 - Please please Mr. Postman (1:03:33)
⌨️ Video 5 - Using Helper Libraries (JavaScript) (1:14:41)
⌨️ Video 6 - Using Helper Libraries (Python) (1:24:40)

⭐️ Unit 3 - Using APIs
⌨️ Video 1 - Introducing the project (1:34:18)
⌨️ Video 2 - Flask app (1:36:07)
⌨️ Video 3 - Dealing with API Limits (1:50:00)
⌨️ Video 4 - JavaScript Single Page Application (1:54:27)
⌨️ Video 5 - Moar JavaScript and Recap (2:07:53)
⌨️ Video 6 - Review (2:18:03)
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=GZvSYJDk-us&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=5
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#apis #apis for beginners #how to use an api #apis for beginners - how to use an api #application programming interfaces #learn all about apis

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys