Skip to main content

A Python library to supercharge your GitHub organization with bots and webhooks.

Project description

FastGithub written in white with a drawing of a bolt.

A Python library to supercharge your GitHub organization with bots and webhooks.

CI Pipeline Release Codecov
Ruff Pre-commit License
PyPI - Python version PyPI - Version


FastGitHub is a Python package for FastAPI, offering a GitHub webhooks handler and easy Bot creation utilities, streamlined through recipes for easy operations on Github organizations and repositories.

More informations about Github webhooks and payloads: docs.github.com/en/webhooks/webhook-events-and-payloads


Features

  • Seamless experience: GitHub webhook handler and router classes that just works.
  • ⚡️ FastAPI native: Build for FastAPI but can be easily integrate with any WSGI web application framework.
  • 🔌 Battery included: Come with a set of built-in recipes for the most common GitHub operations.
  • ️⛏ Modularity: Recipes can be easily defined for tailor-made needs.

Requirements

Before installing FastGitHub, ensure you have the following prerequisites:

  • Python: Version 3.12 or newer.
  • FastAPI: FastGitHub is built to work with FastAPI, so having FastAPI in your project is essential.

️️Installation

Install the package from the PyPI registry.

pip install fastgithub

Usage

FastGitHub usually involves 3 steps to handle GitHub webhooks:

  1. Define the recipes you want to use.
  2. Attach these recipes to a GithubWebhookHandler.
  3. Include a webhook_router in your FastAPI application.

Recipes

To define a Recipe (or GithubRecipe), simply add events property that returns a dict with the events as keys and their methods to execute. Use * to trigger the recipe on any events. When a recipe is expected to fail, use a raise exception, so that the handler can return an error to the FastAPI application.

To use a GithubRecipe, a Github instance from PyGithub is required when instantiating the class. A GithubHelper exists to help you to work with a GitHub repository.

You can also use raw functions, although this is not the best solution.

from collections.abc import Callable

from fastgithub import Recipe, GithubRecipe
from fastgithub.helpers.github import GithubHelper
from fastgithub.types import Payload


class Hello(Recipe):
    @property
    def events(self) -> dict[str, Callable]:
        return {"*": self.__call__}

    def __call__(self, payload: Payload):
        print(f"Hello from: {payload['repository']}")


class MyGithubRecipe(GithubRecipe):
    @property
    def events(self) -> dict[str, Callable]:
        return {"push": self.__call__, "pull_request": self.__call__}

    def __call__(self, payload: Payload):
        gh = GithubHelper(self.github, repo_fullname=payload["repository"]["full_name"])
        gh.raise_for_rate_excess()

        print(f"Hello from {gh.repo.full_name}!")


def very_simple_recipe(payload: Payload) -> None:
    print(f"Hello from: {payload['repository']}")

Available recipes

  • AutoCreatePullRequest create a PR when a new branch is pushed.
  • LabelsFromCommits add label to a PR using commit messages (a default config is provided).

GitHub recipes can be imported from fastgithub.recipes.github.

Webhook handler

Here's a basic example how to define a GithubWebhookHandler with SHA256 signature verification. Setting signature_verification=None allows you to use the handler without signature verification (which is not at all the recommended way to publish GitHub webhook).

from fastgithub import GithubWebhookHandler, SignatureVerificationSHA256

signature_verification = SignatureVerificationSHA256(secret="mysecret")
webhook_handler = GithubWebhookHandler(signature_verification)

You can use the plan method to set recipes to a handler. The listen handler's method allows you attach recipe functions to specific events. The listen method can also be used as a decorator.

webhook_handler.plan([Hello()])

webhook_handler.listen("pull_request", [very_simple_recipe])


@webhook_handler.listen("pull_request")
def another_simple_recipe(payload: Payload) -> None:
    print(f"Hello from: {payload['repository']}")

Webhook router

The webhook_router function returns a fastapi.APIRouter. You can adopte the inner logic of this function to suit your needs.

import uvicorn
from fastapi import FastAPI

from fastgithub import webhook_router

app = FastAPI()
router = webhook_router(handler=webhook_handler, path="/postreceive")
app.include_router(router)

if __name__ == "__main__":
    uvicorn.run(app)

Development

In order to install all development dependencies, run the following command:

uv sync

To ensure that you follow the development workflow, please setup the pre-commit hooks:

uv run pre-commit install

To test the webhook handler, use the compose.yaml file with the following command:

WEBHOOK_PROXY_URL=https://smee.io/XXX docker compose up

Acknowledgements

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastgithub-0.0.6.tar.gz (153.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastgithub-0.0.6-py3-none-any.whl (14.9 kB view details)

Uploaded Python 3

File details

Details for the file fastgithub-0.0.6.tar.gz.

File metadata

  • Download URL: fastgithub-0.0.6.tar.gz
  • Upload date:
  • Size: 153.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.15

File hashes

Hashes for fastgithub-0.0.6.tar.gz
Algorithm Hash digest
SHA256 d54c449c9da5c1273b6f76da8980e1b4822cd1ba2506f95c6cbdb7c7db555290
MD5 4239c7d7ed19e1a91972c829de6fe2ce
BLAKE2b-256 f74ec825db62f98f4e9f992106b87df886c77c4c50f21df5e521722422b56af3

See more details on using hashes here.

File details

Details for the file fastgithub-0.0.6-py3-none-any.whl.

File metadata

  • Download URL: fastgithub-0.0.6-py3-none-any.whl
  • Upload date:
  • Size: 14.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.15

File hashes

Hashes for fastgithub-0.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 8f1d2caf70a9f9571abaedae64c5be7634cdf3c9ff6d83397b48328f4e7a63ac
MD5 afa815cd20957aaba9ce1f05caf43de9
BLAKE2b-256 87a6efd500b39cfc7f86f5e2039d136a4ad0cc4d728204d96591851e19ba4fd1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page