21

Twitter REST API 1.1 to create Twitter Apps using PHP & Javascript

Share Button

Since twitter has released their new REST API (v1.1), there are some changes which affects quite alot of twitter apps developed based on older API. To prevent malicious use of the Twitter API and gain an understanding of what types of applications are accessing the API, twitter has put some restrictions. Here is the list of changes according to twitter offical blog:

  • required authentication on every API endpoint
  • a new per-endpoint rate-limiting methodology
  • changes to our Developer Rules of the Road, especially around applications that are traditional Twitter clients.

I am going to show you how can you use new twitter API (v1.1) to develop jQuery plugins or any Javascript apps. After having a look at different approaches, I found quite a simple solution which I will explain in this post.

Twitter API PHP

Make sure you have hosting that supports PHP. Next go to twitter-api-php and download the files OR simply click here to download the files.

Next create a folder called twitter or anything you want on your server and upload all the files after unzipping it.

You can delete all files safely and leave TwitterAPIExchange.php & index.php.

Create a twitter APP

Login to twitter and than navigate to the twitter apps site.

Click ‘Create New App’ button provided on the top right hand side.

Enter the name of your application e.g ‘My first app to test v1.1′

Similarly enter description and the website URL where from where you will be accessing the twitter api.

Note: In the website you don’t need to provide full path to twitter folder you created in previous steps. It should look like http://www.mydomain.com.

You can leave Callback URL empty for now.

Click ‘Yes, I agree’ checkbox and finally click ‘Create your twitter application’ button.

twitter-create-app

API Keys & Access Token

Now after create your first Twitter App, you should see something like this:

twitter-app-settings

Next click ‘API Keys’ tab where you will see your API keys:

twtter-api-keys

Scroll down this page and click ‘Create my access token':

twitter-access-token

Twitter will show you a message saying it will take a while. Refresh your page after 5-10 seconds and you will see your access token details.

Copying settings from twitter app to index.php

Next open index.php to edit settings. You should see following code. Just fill the areas labeled as xxxxxxxxxxxxxxxxxx with details from twitter app. Save the file and you are ready to go.

Next load that page in your browser and you will see something like this which you can ignore for now:

Creating your own API for JSON responses

So you can create a page which you can call using Ajax and this page will search anything from twitter and send the response in JSON format.
For JSON response you need to set the PHP header. (I will show the complete code later so need to test this for now). Put the following line as the first line after start PHP tag:

Also you need to limit the calls to your own domain otherwise anyone can use this page to to access your twitter API and steal your bandwidth. Read more about Same-origin policy here.

If you want to access it from multiple websites you can do this:

Also you need to pass the search parameters in the URL which you can access in PHP and append it to the twitter API URL. Here is the complete code, try it:

Make sure you change the relevant bits in above code.

To test simply try following URL:

http://www.mysite.com/twitter/index.php?q=whatsapp&count=10

To see JSON in proper format you can try Chrome’s JSON Formatter extension.

Thats it. You are all done.

Using your Twitter API interface with jQuery

Here is a simple example of how you can use your twitter API with jQuery. [full screen]

Another example where I am displaying tweets on google map on the locations form where they been tweeted. [full screen]

And than a more complex example of creating tweets cloud using tagcanvas.
[full screen]

You can use all sorts of different options mentioned on twitter official docs.

Update

You can try pure Javascript based approch but it doesn’t give you full control over different twitter API options. I have tried something (full screen) which you can check.

Share Button
  • Ammar Wasif

    Very nice my brother :)
    Masha Allah

  • Adam

    Thanks for this – I’m trying to test this locally (127.0.0.1) but I’m getting a blank page with no errors when I load index.php in the browser.

    Any ideas?

    • http://www.aamirafridi.com/ Aamir Afridi

      I’ve not tried it on localhost. Some people have had success, but it appears some couldn’t get it to work. Ideally you should try it on a web host. Please google for follow keywords and you might find something…
      twitter api 1.1 localhost

      • Adam

        I’ve googled and tried various different solutions with no luck. I’ve got as far as displaying the raw json code with one so will try and parse that and see how I get on. Thanks anyway.

        • jc

          I also get no response or error codes. Tested locally and also on public facing web server.

  • Brian S

    Aamir, Thanks man. This was super helpful.

    • http://www.aamirafridi.com/ Aamir Afridi

      I am glad it helped you :)

    • Shekhar Suman

      i am working on localhost and i am getting a blank page.
      please send me your code so it would be easy for me.
      thankyou.

  • expy movies

    Aamir Bro, Thanks for this , im trying to test this but its return blank page no error… so please send me this file ..
    please ….

    expymovies@gmail.com

    • http://www.aamirafridi.com/ Aamir Afridi

      If follow the steps correctly till end, than you should have app working. Please explain your issue in more detail. Do you have a demo which I can check?
      Also paste some code as in comment so I might detect the issue.

      • Guest

        please give me your email address , then i send apps secret code.

        “xxxxxxxxxxxxxxxxxxxxx”,
        ‘oauth_access_token_secret’ => “xxxxxxxxxxxxxxxxxxxxxx”,
        ‘consumer_key’ => “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”,
        ‘consumer_secret’ => “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
        );

        /** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
        $url = ‘https://api.twitter.com/1.1/blocks/create.json';
        $requestMethod = ‘POST';

        /** POST fields required by the URL above. See relevant docs as above **/
        $postfields = array(
        ‘screen_name’ => ‘mukhtarezamana’,
        ‘skip_status’ => ‘1’
        );

        /** Perform a POST request and echo the response **/
        $twitter = new TwitterAPIExchange($settings);
        echo $twitter->buildOauth($url, $requestMethod)
        ->setPostfields($postfields)
        ->performRequest();

        /** Perform a GET request and echo the response **/
        /** Note: Set the GET field BEFORE calling buildOauth(); **/
        $url = ‘https://api.twitter.com/1.1/followers/ids.json';
        $getfield = ‘?screen_name=mukhtarezamana';
        $requestMethod = ‘GET';
        $twitter = new TwitterAPIExchange($settings);
        echo $twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)
        ->performRequest();

        • http://www.aamirafridi.com/ Aamir Afridi

          I am sorry but its really hard to look at the code without testing. I don’t have enough time to configure the environment locally to test your code. All I can suggest is follow tutorial from the start and add code bit by bit and progress. When you see an error at that point you will understand what is causing the issue.

      • expy movies

        Please Aamir Bro give me your email address for sending apps secret code.. thnkss for interest..

        “xxxxxxxxxxxxxxxxxxxxx”,
        ‘oauth_access_token_secret’ => “xxxxxxxxxxxxxxxxxxxxxx”,
        ‘consumer_key’ => “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”,
        ‘consumer_secret’ => “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
        );

        /** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
        $url = ‘https://api.twitter.com/1.1/blocks/create.json';
        $requestMethod = ‘POST';

        /** POST fields required by the URL above. See relevant docs as above **/
        $postfields = array(
        ‘screen_name’ => ‘mukhtarezamana’,
        ‘skip_status’ => ‘1’
        );

        /** Perform a POST request and echo the response **/
        $twitter = new TwitterAPIExchange($settings);
        echo $twitter->buildOauth($url, $requestMethod)
        ->setPostfields($postfields)
        ->performRequest();

        /** Perform a GET request and echo the response **/
        /** Note: Set the GET field BEFORE calling buildOauth(); **/
        $url = ‘https://api.twitter.com/1.1/followers/ids.json';
        $getfield = ‘?screen_name=mukhtarezamana';
        $requestMethod = ‘GET';
        $twitter = new TwitterAPIExchange($settings);
        echo $twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)
        ->performRequest();
        ?>

  • expy movies

    Please define Aamir Bro..

  • Himanshu Mishra

    : ) thank you. It is working.

    • http://www.aamirafridi.com/ Aamir Afridi

      :)

  • WPSkier

    Hello. I am still getting Could not authenticate you error message. I cannot get past that even after following your directions regarding javascript. Ideas?

  • HPrakash

    Instead of FreeKashmir, why don’t you put ReturnPaktoIndiaAndGoBackToDesert in the tutorial?

  • VijaySoni_Open

    how can we use twitter search api with js ?

  • http://www.hire-php-developers.co.uk/ PHP Developers

    All the internet websites and the social media channels are affected by the hacking. During the development phase, sometimes outdated plugins are used for app development and as a result the apps are easily hacked.

    For developing a secure app you can hire expert and reliable developers of DL solutions to create a secure, responsive and flexible application with high sense of professionalism.

Copyright © 2017 — musings of Aamir Afridi