Create a team using PyGithub

PyGithub is a terrific Python library that simplifies interacting with Github’s API. In this blog post I will discuss using PyGithub to create a Github Team. I am assuming that you already have a Github account (free or paid).

Pygithub works best with Python 3.7.


1. Install Pygithub

Open your bash terminal and type the following:  

pip3 install pygithub

2. Create a Github Personal Access Token

You can either use your username/password combination or create a Personal Access Token for your Github account. I normally prefer a token as it gives you a bit more granular level controls on what you can allow it to do. For creating teams, we need to give it admin:org scope:

  1. Login to Github.com
  2. Go to the top right of the page, click on your profile image and choose Settings.
  3. Click on Developer Settings.
  4. Click on Personal access tokens.
  5. Click on Generate new token.
  6. Enter the required details and select “admin:org” in the scope

Make a copy of the token as you will not be able to view it afterwards. If you lose the code, you can always regenerate a new code.


3. Create the team

The following code will authenticate to Github using your token and create a new team.

from github import Github, GithubException

github_org   = "Your account name"
github_token = "Your Personal access token"
github_team  = "team1"

g   = Github(github_token)
org = g.get_organization(github_org)

print ("Creating team - %s" % github_team)
try:
  org.create_team(
    github_team, 
    privacy="closed", 
    permission="admin")
except GithubException as e:
  print (e.args[1]['message'])

And it’s that easy. No need to create JSON requests or messing around with authentication headers.

For a full reference on Pygithub,visit the docs.

Leave a Comment

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.