Upload a gist via the GitHub API

Our OAuthenticator config has passed GitHub information via environment variables. We can use these to publish gists to GitHub.

Get the GitHub username and token from environment variables


In [1]:
import os
gh_user = os.environ['GITHUB_USER']
gh_token = os.environ['GITHUB_TOKEN']

Create a requests.Session for holding our oauth token


In [2]:
import requests
s = requests.session()
s.headers['Authorization'] = 'token ' + gh_token

Verify that we have the scopes we expect:


In [3]:
r = s.get('https://api.github.com/user')
r.raise_for_status()
r.headers['X-OAuth-Scopes']


Out[3]:
'gist, user:email'

Now we can make a gist!


In [4]:
import json
r = s.post('https://api.github.com/gists',
    data=json.dumps({
        'files': {
            'test.md': {
                'content': '# JupyterHub gist\n\nThis file was created from JupyterHub.',
            },
        },
        'description': 'test uploading a gist from JupyterHub',
    }),
)
r.raise_for_status()
print("Created gist: %s" % r.json()['html_url'])


Created gist: https://gist.github.com/6dd52f63aa0860f3018dec36b3c2d7d5