Creating GitHub issues using a Personal Access Token through their API cover image

Creating GitHub issues using a Personal Access Token through their API

May 9, 2020

programming

Using PHP's most popular GitHub API package knpLabs/php-github-api, I was trying to automatically generate issues on my own repositories using my GitHub account, but I kept receiving Bad Credentials and Not Found errors.

The trick using the above PHP API package is the parameter placement of the Personal Access Token, and the authorization method to use.

Let's walk through this step-by-step.

Creating the Personal Access Token

First, we must create a Personal Access Token:

  1. Login to GitHub
  2. Click Settings under the profile menu:
  3. Click Developer Settings at the very bottom of the left menu:
  4. Click Personal Access Tokens:
  5. Click Generate new token:
  6. Enter a name for your token:
  7. Give the token only public_repo permissions, nothing else:
  8. Then, click Generate Token:

Using the PHP API

Now we have our token, we can begin using it. Install the knpLabs/php-github-api package using composer in your project:

composer require knpLabs/php-github-api

Then, import Github\Client into where you want to start creating issues:

use Github\Client;

$client = new Client();

$client->authenticate('my-personal-access-token', null, Client::AUTH_HTTP_TOKEN);

$issueDetails = [
    'title' => 'My Issue Title',
    'body' => 'The body of the issue' // This supports markdown.
];

$issue = $client->api('issue')->create(
    $userOrCompany = 'laravel',
    $repository = 'framework',
    $issueDetails
);

Notice how we set the second parameter of the authenticate() method null and the last parameter to Client::AUTH_HTTP_TOKEN. This wasn't immediately clear to me in the GitHub or package docs.

You can also visit the GitHub documentation to see all issue parameters.

Hope this helps! ❤️