How does the Twitter API work

Twitter API v1.1 tutorial - read my tweets

By Lars Ebert on 07/01/2013, 11:00 a.m.
Categories: PHP, Programming and Tutorials

Since the week before last, users of the Twitter API v1 have noticed that the interface has suddenly stopped working. Why? Twitter no longer supports the API and urges all developers to use API v1.1 now. This will make reading out the tweets a little more complicated in the future. In this article, I'll show you how to use the API v1.1 so that you can continue to display your tweets on your website in the future.

Step 1: create the Twitter app

In order to be able to access the new API, you have to authorize yourself as a Twitter app. Twitter is now doing exactly the same as Facebook is doing here. So now we have to create a Twitter app first.

To do this, we go to the Twitter Developer Center and log in with our Twitter account. Then we will find an overview of our apps on the My applications page, in the upper right corner we will find a button for creating a new app.

We will need the consumer key and consumer secret during implementation.

Step 2: get BearerToken

Now we can request a BearerToken in the name of our app. For every request that we send to the API, we have to request a BearerToken beforehand.

We have to send this request to Twitter in order to receive a BearerToken. With PHP we can send this request as follows:

First we combine the key and secret to form our AuthKey. To do this, we connect the two with a colon and encode the result with base64. This is done here in line 10.

Next we send a request to the tokenUrl with Curl, insert the generated AuthKey in the header (line 15) and request a BearerToken from Twitter (line 16).

We now execute the prepared curl request, as the return value we get a JSON object that contains the BearerToken. We extract this in lines 19 and 20 and then terminate the connection with line 21.

Now we have a BearerToken and can send the actual call to the Twitter API.

Step 3: Use the Twitter API

In order to get all of my own tweets, I used Curl to send another request to the Twitter API.

This time, however, we transfer the BearerToken (line 26) as authorization and receive the tweeds as the return value. We could now output these as follows, for example: