Do you want to implement Twitter Search API on your website? Twitter REST API’s provides a way for developers so they can search tweets or users by writing some piece of code.
Twitter mentioned that Search API is focused on relevance and not completeness. This means that some Tweets and users may be missing from search results. Despite this, you can get a sufficient search result.
How To Search Tweets Using API
Once you installed the TwitterOAuth library, you are able to search tweets through REST APIs. To search a tweets, Twitter provided a endpoint search/tweets. We will use it in seconds. To proceed I assume that, you have set your twitter application and you have your application keys with you.
We need to create an object from the class TwitterOAuth. You need to add below code for it.
require('vendor/autoload.php'); use Abraham\TwitterOAuth\TwitterOAuth; $connection = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', 'YOUR_ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN_SECRET');
Once we instantiate connection object, we are able to use REST API’s endpoint. Below is the code for our endpoint ‘search/tweets’.
$arr_tweets = $connection->get("search/tweets", [ "q" => "@WordPress", "result_type" => "recent", "count" => "15", "lang" => "en"]);
Above method will return recent 15 tweets which are written in English language. To read more about parameters, you can read on twitter developers documentation GET search/tweets.
How To Search Users Using API
You can search users in the same way as you search tweets. Only difference are in some parameters and in endpoint. For user search, we use the endpoint ‘users/search’. You can read more about this on GET users/search
Let’s add some code to it. For example, I want to search users with the name ‘Matt’. So my code would as below.
$arr_tweets = $connection->get("users/search", [ "q" => "Matt", "count" => "15"]);
Above code will return 15 users with the name contains ‘Matt’. You can apply more parameters to search function as provided in twitter developer documentation.
I hope you understand how to use Twitter Search API. For any questions or suggestions please leave a comment below.
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.