|

|  How to Use GitHub Packages API to Manage Package Registries in Python

How to Use GitHub Packages API to Manage Package Registries in Python

October 31, 2024

Unlock the power of GitHub Packages API in Python. Learn to manage package registries effectively with this comprehensive guide.

How to Use GitHub Packages API to Manage Package Registries in Python

 

Understanding GitHub Packages API

 

  • GitHub Packages offers a versatile platform for hosting and managing various packages, supporting formats like npm, Maven, and Docker.
  •  

  • The GitHub Packages API provides endpoints for interacting with these packages, allowing for tasks like publishing, consuming, and deleting packages programmatically.

 

 

Setting Up Authentication

 

  • To use the GitHub Packages API, you need to authenticate using a GitHub token. Ensure that your token has the required scopes: read:packages, write:packages, and delete:packages.
  •  

  • Store this token securely, often in environment variables or a secure vault. In Python, retrieve it using os.environ.

 

import os

GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")

 

 

Interacting with Package Registries

 

  • Use popular HTTP clients like requests in Python to make API calls. Start by setting up a session and preparing headers with authentication.

 

import requests

session = requests.Session()
session.headers.update({
    'Authorization': f'token {GITHUB_TOKEN}',
    'Accept': 'application/vnd.github.v3+json'
})

 

 

Listing Packages

 

  • Fetch a list of packages using the API endpoint /user/packages or /orgs/{org}/packages for organizational packages. Handle API pagination if needed to retrieve all entries.

 

def list_packages():
    response = session.get("https://api.github.com/user/packages")
    response.raise_for_status()  
    return response.json()

packages = list_packages()
for package in packages:
    print(package['name'], package['package_type'])

 

 

Uploading and Publishing Packages

 

  • For uploading packages, use format-specific endpoints and tooling. Many ecosystems like npm and Maven have CLI tools to handle package uploads that internally communicate with GitHub Packages API.
  •  

  • For Python packages, this often involves configuring your .pypirc and using twine.

 

twine upload --repository-url https://upload.pypi.org/legacy/ dist/*

 

 

Deleting Packages

 

  • Use the API to delete entire packages or just specific package versions. Note the endpoints /user/packages/{package_type}/{package_name}/versions/{version\_id} for specific versions.

 

def delete_package_version(package_type, package_name, version_id):
    url = f"https://api.github.com/user/packages/{package_type}/{package_name}/versions/{version_id}"
    response = session.delete(url)
    response.raise_for_status()

delete_package_version('npm', 'example-package', '1')

 

 

Handling Rate Limits

 

  • GitHub's API has rate limits that apply to all requests, including those made to GitHub Packages. Monitor API responses for the headers X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset.

 

def check_rate_limit():
    response = session.get("https://api.github.com/rate_limit")
    response.raise_for_status()
    return response.json()['rate']

rate_limit = check_rate_limit()
print(f"Remaining: {rate_limit['remaining']} out of {rate_limit['limit']}")

 

 

Conclusion and Best Practices

 

  • Integrate Github Packages API into CI/CD pipelines to streamline package management.
  •  

  • Regularly audit package permissions and cleanup outdated versions to optimize storage and security.