How To Interact With Github API Using Laravel

How To Interact With Github API Using Laravel

In our last tutorial we thought you how to connect to a twitter stream and listen for a specific keyword. This time we're going to show you, how to open a github issue with the message conent of the tweet that we caught. Ok, how do we open an issue programatically? Luckily, Github has great API access. For the sake of this tutorial, we'll open a new issue on our TNTSearch package eachtime someone mentions TNTSearchBug.

We'll also teach you how to build a miny github library that knows how to talk to and consume the github API.

First, lets create an access token for github. Go to https://github.com/settings/tokens/new and select the scope public_repo

Once we retrieved the token, we'll save it to config\services.php as

'github' => [
    'token' => 'your_github_access_token'
]

Our miny library will be located in App\Lib\Github\Client.php and has only a handful of methods

<?php

namespace App\Lib\Github;

use GuzzleHttp\Client;

class Client
{
    protected $client   = null;
    protected $endpoint = 'https://api.github.com';

    public function __construct()
    {
        $accessToken  = config('services.github.token');
        $this->client = new Client([
            'base_uri' => $this->endpoint,
            'headers'  => [
                'Authorization' => 'Bearer ' . $accessToken,
            ],
        ]);
    }

    public function get($path)
    {
        $ret = $this->client->get($path);
        return json_decode($ret->getBody());
    }

    public function post($path, $payload)
    {
        $ret = $this->client->post($path, [
            'json' => $payload,
        ]);
        return json_decode($ret->getBody());
    }
}

The WatchTwitterStream.php command that we created last time needs to be refactored. We'll extract the twitter functionality to App\Lib\TwitterStream\Client.php



comments powered by Disqus