To interact with the GitHub API in Python, you can use the requests library. Below is an example script that demonstrates how to create a new repository using the GitHub API. Note that you'll need a personal access token (PAT) with the required scopes for these operations [1][2].
```python
from github import Github
# Replace with your GitHub personal access token
token = "YOUR_PERSONAL_ACCESS_TOKEN"
# Create a GitHub API client
g = Github(token)
# Repository information
repo_name = "example-repo"
repo_description = "Example repository created via the GitHub API"
org_name = "your-organization" # Replace with your organization name (if applicable)
collaborators = ["collaborator1", "collaborator2"] # List of collaborators
try:
# Create a new repository
user = g.get_user()
if org_name:
org = g.get_organization(org_name)
repo = org.create_repo(repo_name, description=repo_description)
else:
repo = user.create_repo(repo_name, description=repo_description)
print(f"Repository '{repo_name}' created successfully.")
# Add collaborators to the repository
for collaborator in collaborators:
try:
user = g.get_user(collaborator)
repo.add_to_collaborators(user)
print(f"{collaborator} added as a collaborator.")
except Exception as e:
print(f"Failed to add {collaborator} as a collaborator: {str(e)}")
# Perform other repository-related tasks here
# For example, you can add code to create files, manage issues, etc.
except Exception as e:
print(f"Failed to create the repository: {str(e)}")
```
In this script:
* Replace `YOUR_PERSONAL_ACCESS_TOKEN` with your GitHub personal access token. Make sure it has the necessary permissions for creating repositories and adding collaborators.
* You can customize the repository information, such as repo_name, repo_description, org_name, and the list of collaborators you want to add to the repository.
* The script creates a new repository using the GitHub API, either within your user account or within an organization if org_name is specified.
* It adds the specified collaborators to the repository.
* You can add more tasks or API operations based on your requirements. The PyGithub library provides methods for a wide range of GitHub API operations.
Please note that handling exceptions and adding error checks is important for robust script development, especially when working with APIs. Be sure to handle exceptions and errors appropriately in your code.