21

In the past, using Twitter API version 1, I used the following URL to get a JSON feed of all tweets with the hashtag "baseball":

http://search.twitter.com/search.json?q=%23baseball&result_type=recent

How do you achieve a similar result using API version 1.1? I'm using PHP as my server-side code, so not sure if I need to use it to authenticate and such?

Sample code would be extremely helpful. Thanks.

freginold
  • 3,946
  • 3
  • 13
  • 28
John
  • 32,403
  • 80
  • 251
  • 422

3 Answers3

38

As you know, authenticated requests are now required, so there's a few things that you may need to take a look at first. The new 1.1 search, how to use hashtags, and authentication.

Twitter Search for 1.1

The new twitter search api docs can be found here. According to these docs:

https://api.twitter.com/1.1/search/tweets.json is the new resource URL to use for search.

Hashtag searches

You've got that part right! %23 decodes to a # character.

Authentication

OAuth is a lot more complex. It would help if you just used a library that just worked.

Here's a post a lot of people found useful to help you make authenticated requests to the 1.1 API. This includes a one-file include library to make requests like those you require.

Example

This example assumes you're using the above library and set up your keys etc. To make your request:

// Your specific requirements
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=#baseball&result_type=recent';

// Perform the request
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();

Yes, that's it. Apart from the little setting up you need to do (as my post explains), for your dev keys, that's everything you need to perform authenticated requests.

Response

The response is returned to you in JSON. From the overview:

API v1.1 will support JSON only. We've been hinting at this for some time now, first dropping XML support on the Streaming API and more recently on the trends API. We've chosen to throw our support behind the JSON format shared across the platform.

Jimbo
  • 25,790
  • 15
  • 86
  • 131
  • @Jimbo : Thanks for great answer(+1).I have one problem I am making one web-app which based on ur solution But I got error "Rate limit exceeded " error message How can I resolve it I want to know I have to follow other authentication method ?? Can I use twiter account of user who are using my web-app. please help thanks.. – mcacorner Jul 04 '13 at 09:57
  • Great that I am searching for #tag serch! "You've got that part right! %23 decodes to a # character" – Kiren S Aug 12 '13 at 11:59
  • 1
    @KirenSiva Using the above library, you shouldn't need to type in any encoded characters into `$getfield` as the library does this automatically for you. – Jimbo Aug 12 '13 at 12:31
  • what if I don't want to search based on hash tag. I want to fetch all the statuses that are updated in last 1 day.? – keen Jan 23 '14 at 09:24
  • @BSThakrar The docs for every endpoint are [**here**](https://dev.twitter.com/docs/api/1.1). You can use [**GET search/tweets**](https://dev.twitter.com/docs/api/1.1/get/search/tweets) to search for all tweets using the query paremeter (`?q=...`). [Here](https://dev.twitter.com/docs/using-search) is how you can build that query parameter, and the `since` keyword is what you are after. Do some bloody googling! – Jimbo Jan 23 '14 at 09:44
  • Thanks for ur quick resposne. But I already saw this and i couldn't find anything to keep it blank and get all tweets. – keen Jan 23 '14 at 10:00
  • Sir, You are just great – Raghav Satyadev Feb 02 '17 at 09:08
  • Are you sure the has should be in the query ? Because the hash make the response empty. – Dimitri Kopriwa May 01 '21 at 15:12
  • @DimitriKopriwa This depends on the library you're using and whether or not it encodes the values properly for you before sending the request. The one I shoved on Github so people could check it out easily works with the above but doesn't do some other things so well. – Jimbo May 04 '21 at 12:10
4

If you just want to test, you can do the follow:

Access the twitter dev console: https://dev.twitter.com/console

In Authentication put: OAuth 1, that will ask you to give permission from your twitter account.

Request URL put GET

In url: https://api.twitter.com/1.1/search/tweets.json?q=%23yourhashtag

After Send, in Request window, copy the Authorization value.

Now put it in your request header.

Go example:

func main() {
    client := &http.Client{}
    req, _ := http.NewRequest("GET", "https://api.twitter.com/1.1/search/tweets.json?q=%23golang", nil)
    req.Header.Add("Authorization", `OAuth oauth_consumer_key=...`)

    resp, _ := client.Do(req)
    io.Copy(os.Stdout, resp.Body)
}
1

Here's a simple example in python using application-only auth using the requests API. Get keys by creating an app at https://apps.twitter.com/app/new.

api_key = ...
api_secret = ...

# https://dev.twitter.com/oauth/application-only
# The base64 stuff described there is the normal Basic Auth dance.
import requests
r = requests.post('https://api.twitter.com/oauth2/token',
                  auth=(api_key, api_secret),
                  headers={'Content-Type':
                      'application/x-www-form-urlencoded;charset=UTF-8'},
                  data='grant_type=client_credentials')
assert r.json()['token_type'] == 'bearer'
bearer = r.json()['access_token']

url = 'https://api.twitter.com/1.1/search/tweets.json?q=%23yourhashtag'
r = requests.get(url, headers={'Authorization': 'Bearer ' + bearer})
print r.json()
thakis
  • 5,405
  • 1
  • 33
  • 33