Use Guzzle for OAuth2 API Integration

I wanted to fetch my delicious bookmarks for display on this website, I started by creating a command in Laravel (it’s my favourite way of testing things like this work!) that would run my delicious class and fetch bookmarks.

First things first, create an app on delicious and get your client ID and client secret.

Guzzle is a fantastic library for consuming APIs but out of the box doesn’t support OAuth2, so I pulled in the Guzzle OAuth2 plugin via composer and set about adding it to my delicious class to fetch tweets.

We’re going to start with a bit of a fudge, I’m going to be the only user of my app.

So I’ll visit (in my browser):

https://delicious.com/auth/authorize?client_id<client_id>&redirect_uri=http://www.domain.com/redirect

This will redirect us to:

http://www.domain.com/redirect?code=<code>

Grab the code on the end of the URL, we’ll need this in a moment.

We now need to make a POST to:

https://avosapi.delicious.com/api/v1/oauth/token?client_id=<client_id>&client_secret=<client_secret>&grant_type=code&code=<code from redirect earlier>

I find the easiest way to make a POST like this that I won’t use again is Postman in Chrome, so long as you’re quick enough between requesting the access token and making the POST with the code you should get a JSON back with an access token in it.

We should now be able to use this access token to make requests in Laravel.

Let’s use the fetch command we created earlier to fetch recent bookmarks

<?php 
namespace App\Console\Commands; 
use GuzzleHttp\Client; 
use CommerceGuys\Guzzle\Oauth2\Oauth2Subscriber; 

class Delicious { 
   protected $base_url = 'https://api.del.icio.us/v1/'; 
   protected $access_token = 'MYACCESSTOKEN'; 
   public function fetch() { 
     // Create a subscriber and add our retrieved access token 
     $subscriber = new Oauth2Subscriber(); 
     $subscriber->setAccessToken($this->access_token);

        // Create a new Guzzle client
        $oauth2Client = new Client(
            [
                'base_url' => $this->base_url,
                'defaults' => [
                    'subscribers' => [$subscriber],
                    'auth' => 'oauth2',
                    'exceptions' => false,
                ]

            ]);


        // Fetch recent posts
        $response = $oauth2Client->get('posts/recent');
        $body = $response->xml();

        print_r($body);;
    }

}

You can check out all the Delicious API functions here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.