Get the contents of a single file on Github using Guzzle and PHP

Recently I found myself needing to get most recent content of a single file from a private Github repo.

It took me a while to figure out how to make it work using Guzzle, but once I got it, it was pretty simple to use.

One of the caveats is that, regardless of the type of error you might encounter when requesting a file from a private repo, the Github API always throws a 404 error. That can make it tricky to troubleshoot other kinds of errors (e.g., authentication, etc.)

Anyway, here’s a gist with the working code. You’ll need to modify this to suit your own situation, naturally. If you find this useful, let me know!

<?php
use \GuzzleHttp\Client;
use \GuzzleHttp\Psr7;
use \GuzzleHttp\Exception\RequestException;
/**
* Use guzzle to get a single file from github and return it as a string.
*
* @param string $url The path of the file to fetch
* @return string
* @throws \Exception
*/
public function fetchFileFromGithub(string $url):string
{
try {
$response = $this->guzzle->request('GET', $url, [
'auth' => [
$this->githubUser, //<-- replace with your username
$this->githubToken, //<-- replace with your Github Personal Access Token
],
'headers' => [
'Accept' => 'application/vnd.github.v3.raw', //<-- This gets you the raw contents of the file.
'User-Agent' => 'Your-Application', //<-- Github wants a user agent.
]
]);
} catch (ClientException $e) {
throw new \Exception('Guzzle problem: ', Psr7\Message::toString($e->getRequest()), Psr7\Message::toString($e->getResponse()));
}
if ($response->getStatusCode() == '200') {
return (string) $response->getBody();
} else {
throw new \Exception('Guzzle bad response code');
}
}