GitHubKit: GitHub SDK for Python

repository·master·Indexed 43 days ago

https://github.com/yanyongyu/githubkit

A modern, fully typed GitHub SDK for Python inspired by Octokit. It provides comprehensive support for REST and GraphQL APIs with sync/async support, pagination, and Pydantic-based data validation. Version 0.16.1 includes built-in HTTP caching via Hishel, automatic retries, and support for GitHub Enterprise Cloud (GHEC) and Server (GHES) via customizable base URLs and specific schema versioning.

Tokens
30.1K
Snippets
102
Records
126
Agent score
57%

What's inside GitHubKit

  1. Overview of githubkit features

    master

    githubkit is a modern, all-batteries-included GitHub SDK for Python that provides:

    • Sync and Async support: Use both synchronous and asynchronous calls.
    • Authentication: Multiple authentication methods and OAuth flow support.
    • API Access: Easy access to both REST and GraphQL APIs.
    • Versioning: Support for REST API versioning, including GitHub Enterprise Cloud (GHEC).
    • Pagination: Built-in support for paginated results.
    • Data Validation: Optional validation for webhook events and REST API responses using Pydantic.
    • Performance & Reliability: Built-in HTTP cache (via Hishel) and automatic retries.
    • Developer Experience: Lazy loading of APIs and models, and fully typed interfaces.
  2. Use GitHubKit-schemas-2026-03-10 for specific GitHub API versions

    master

    The githubkit-schemas-2026-03-10 package provides the specific models and schemas corresponding to the GitHub API version released on 2026-03-10. This allows you to use the GitHubKit SDK with a fixed set of schemas, ensuring that your application's data models remain stable even when the main GitHubKit package updates to newer API versions.

    To ensure consistency in your project, it is recommended to lock the version of this package using a dependency manager like uv.

  3. Quick Start common use cases

    master

    GitHubKit provides several common patterns for interacting with the GitHub API. Depending on your authentication requirements, you can use the following methods:

    • Personal Access Token (PAT): Use a PAT to call the GitHub API directly.
    • GitHub Enterprise: Connect to GitHub Enterprise Cloud or GitHub Enterprise Server.
    • OAuth App (Web Flow): Develop an OAuth App or GitHub App using the web flow to act on behalf of a user.
    • OAuth App (Device Flow): Develop an OAuth App or GitHub App using the device flow to act on behalf of a user.
    • GitHub App: Develop a GitHub App to act on behalf of an installation or a user.

    Note: All APIs in GitHubKit are fully typed. Type hints provided in documentation examples are for reference only.

  4. Use GitHubKit-schemas-ghec-2022-11-28 for GHEC schemas

    master

    This package provides the models and GitHub schemas specifically for GitHub Enterprise Cloud (GHEC) based on the 2022-11-28 schema version. It is used by GitHubKit to ensure type safety and correct data modeling when interacting with GitHub Enterprise Cloud APIs.

    When GitHub updates its schemas, this package is updated accordingly. To ensure stability in your project, you can lock the version of this package using a dependency manager like uv to guarantee your project always uses a specific version of the schemas.

  5. Overview of GitHubKit authentication strategies

    master

    githubkit supports multiple authentication strategies to interact with the GitHub API. All strategies are importable from the top-level githubkit package. Choose a strategy based on your use case (e.g., Personal Access Tokens, GitHub Apps, OAuth, or GitHub Actions).

    # All strategies are importable from the top-level githubkit package
    from githubkit import (
        UnauthAuthStrategy, 
        TokenAuthStrategy, 
        AppAuthStrategy, 
        AppInstallationAuthStrategy, 
        OAuthAppAuthStrategy, 
        OAuthTokenAuthStrategy, 
        OAuthWebAuthStrategy, 
        OAuthDeviceAuthStrategy, 
        ActionAuthStrategy
    )
  6. Switch between GitHub REST API versions

    master

    You can specify a specific version of the GitHub API by calling .rest("VERSION_NAME") on the GitHub instance.

    Supported versions include:

    • 2026-03-10 (latest)
    • ghec-2026-03-10
    • 2022-11-28
    • ghec-2022-11-28

    Note that githubkit.rest is linked to the latest version by default. To use non-default versions, you must install the corresponding extra schema package. Versioned models can be imported from githubkit_schemas.<version>.models.

    # Use a specific API version
    github.rest("2022-11-28").repos.get("owner", "repo")
    
    # Import version-specific models
    from githubkit_schemas.v2022_11_28.models import FullRepository
  7. Access and manipulate response data

    master

    The Response object provides different ways to access data:

    • response.parsed_data: Returns the data validated and parsed into a Pydantic model. This is the recommended way for type safety.
    • response.text: Returns the raw response body as a string.
    • response.json(): Returns the loaded JSON data. This is typed but not validated against the schema.

    Converting Pydantic models to dict or JSON

    If you are using the parsed Pydantic models, you can convert them using standard Pydantic methods:

    Pydantic v2:

    • model.model_dump(): Convert to a dictionary.
    • model.model_dump_json(): Convert to a JSON string.

    Pydantic v1:

    • model.dict(): Convert to a dictionary.
    • model.json(): Convert to a JSON string.
    # Pydantic v2 example
    repo_dict = repo.model_dump(mode="json", by_alias=True, exclude_unset=True)
    repo_json = repo.model_dump_json(by_alias=True, exclude_unset=True)
  8. Use GitHubKit-schemas-2022-11-28 for specific GitHub API versions

    master
    The githubkit-schemas-2022-11-28 package provides the specific models and schemas corresponding to the GitHub API version from November 28, 2022. This is useful when you need to ensure your application uses a stable, fixed set of schemas that do not change when GitHub updates its API. You can lock this package version using dependency managers like uv to maintain consistency in your project.
  9. How to parse webhooks without an event name

    master

    If the X-GitHub-Event header is unavailable, you can use parse_without_name (for Pydantic models) or parse_obj_without_name (for dicts).

    Warning: This approach is not recommended because it is slower, uses more memory, and may incorrectly identify the event type.

    Behavioral differences based on Pydantic version:

    • Pydantic v1: Uses left-to-right mode (returns the first valid model found).
    • Pydantic v2: Uses smart mode (returns the highest scoring valid model).
    from githubkit.webhooks import parse_without_name
    
    event = parse_without_name(request.body)
  10. Exception Hierarchy in GitHubKit

    master

    The following hierarchy represents the exceptions raised by GitHubKit:

    GitHubException
    ├── AuthCredentialError
    ├── AuthExpiredError
    ├── RequestError
    │   ├── RequestTimeout
    │   └── RequestFailed
    │       └── RateLimitExceeded
    │           ├── PrimaryRateLimitExceeded
    │           └── SecondaryRateLimitExceeded
    ├── GraphQLError
    │   ├── GraphQLFailed
    │   └── GraphQLPaginationError
    │       ├── GraphQLMissingPageInfo
    │       └── GraphQLMissingCursorChange
    └── WebhookTypeNotFound
  11. Configure `cache_strategy` for tokens and HTTP responses

    master

    The cache_strategy controls how githubkit caches tokens (e.g., GitHub App installation tokens) and HTTP responses.

    Built-in Cache Strategies

    • MemCacheStrategy (Default): In-memory cache. Each instance maintains its own cache, or you can use the global DEFAULT_CACHE_STRATEGY.
      • Warning: In long-running processes, call cleanup() (sync) or await acleanup() (async) to release memory.
    • RedisCacheStrategy (Sync only): Stores data in Redis. Requires the redis package. Restricts the GitHub instance to sync-only operations.
    • AsyncRedisCacheStrategy (Async only): The async counterpart to RedisCacheStrategy. Requires redis.asyncio. Restricts the GitHub instance to async-only operations.

    Use the prefix parameter in Redis strategies to add a key namespace (e.g., prefix="githubkit").

    from githubkit import GitHub
    from githubkit.cache import DEFAULT_CACHE_STRATEGY, MemCacheStrategy
    
    # Use the global default
    github = GitHub(cache_strategy=DEFAULT_CACHE_STRATEGY)
    
    # Or create an isolated cache instance
    github = GitHub(cache_strategy=MemCacheStrategy())
    
    # Redis (Sync)
    from redis import Redis
    from githubkit.cache import RedisCacheStrategy
    github = GitHub(
        cache_strategy=RedisCacheStrategy(
            client=Redis(host="localhost", port=6379),
            prefix="githubkit",
        )
    )
    
    # Redis (Async)
    from redis.asyncio import Redis
    from githubkit.cache import AsyncRedisCacheStrategy
    github = GitHub(
        cache_strategy=AsyncRedisCacheStrategy(
            client=Redis(host="localhost", port=6379),
            prefix="githubkit",
        )
    )