### Act on Behalf of an Installation (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/github-app.md Find the installation ID for a specific repository and create a new client authenticated as that installation. Use this installation client to perform actions. ```python from githubkit import GitHub, AppAuthStrategy from githubkit.versions.latest.models import Installation, IssueComment app_github = GitHub( AppAuthStrategy( app_id="your_app_id", private_key="your_private_key", client_id="your_client_id", client_secret="your_client_secret", ) ) # 2. Find the installation ID for a specific repository resp = app_github.rest.apps.get_repo_installation("owner", "repo") repo_installation: Installation = resp.parsed_data # 3. Create a new client authenticated as that installation installation_github = app_github.with_auth( app_github.auth.as_installation(repo_installation.id) ) # 4. Use the installation client to perform actions resp = installation_github.rest.issues.create_comment("owner", "repo", 1, body="Hello") išt: IssueComment = resp.parsed_data ``` -------------------------------- ### Basic Installation with UV Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Use this command to install the basic githubkit package with UV. ```bash uv add githubkit ``` -------------------------------- ### Act on Behalf of an Installation (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/github-app.md Asynchronously find the installation ID for a specific repository and create a new client authenticated as that installation. Use this installation client to perform actions. ```python from githubkit import GitHub, AppAuthStrategy from githubkit.versions.latest.models import Installation, IssueComment app_github = GitHub( AppAuthStrategy( app_id="your_app_id", private_key="your_private_key", client_id="your_client_id", client_secret="your_client_secret", ) ) # 2. Find the installation ID for a specific repository resp = await app_github.rest.apps.async_get_repo_installation("owner", "repo") repo_installation: Installation = resp.parsed_data # 3. Create a new client authenticated as that installation installation_github = app_github.with_auth( app_github.auth.as_installation(repo_installation.id) ) # 4. Use the installation client to perform actions resp = await installation_github.rest.issues.async_create_comment( "owner", "repo", 1, body="Hello" ) išt: IssueComment = resp.parsed_data ``` -------------------------------- ### Basic Installation with PDM Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Use this command to install the basic githubkit package with PDM. ```bash pdm add githubkit ``` -------------------------------- ### Basic Installation with Pip Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Use this command to install the basic githubkit package with Pip. ```bash pip install githubkit ``` -------------------------------- ### Basic Installation with Poetry Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Use this command to install the basic githubkit package with Poetry. ```bash poetry add githubkit ``` -------------------------------- ### Full Installation with All Dependencies using UV Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with all extra dependencies using UV for a fully featured experience. ```bash uv add githubkit[all] ``` -------------------------------- ### Full Installation with All Dependencies using PDM Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with all extra dependencies using PDM for a fully featured experience. ```bash pdm add githubkit[all] ``` -------------------------------- ### Full Installation with All Dependencies using Pip Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with all extra dependencies using Pip for a fully featured experience. ```bash pip install githubkit[all] ``` -------------------------------- ### Install Dependencies and Pre-commit Hooks Source: https://github.com/yanyongyu/githubkit/blob/master/docs/contributing.md Installs all project dependencies, including extras, and sets up pre-commit hooks for local development. ```bash uv sync --all-extras && uv run pre-commit install ``` -------------------------------- ### Full Installation with All Dependencies using Poetry Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with all extra dependencies using Poetry for a fully featured experience. ```bash poetry add githubkit[all] ``` -------------------------------- ### Install githubkit with Auth App Dependencies using UV Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with 'auth-app' extra dependencies using UV for GitHub App authentication. ```bash uv add githubkit[auth-app] ``` -------------------------------- ### Switch Authentication Strategy for GitHub App to Installation Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/authentication.md Create a new GitHub client instance authenticated as a specific installation using the `with_auth` method. This shares the same configuration as the original client. ```python from githubkit import GitHub, AppAuthStrategy github = GitHub(AppAuthStrategy("", "")) # Create a new client authenticated as a specific installation installation_github = github.with_auth( github.auth.as_installation(installation_id) ) ``` -------------------------------- ### Install githubkit with Auth App Dependencies using PDM Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with 'auth-app' extra dependencies using PDM for GitHub App authentication. ```bash pdm add githubkit[auth-app] ``` -------------------------------- ### Install githubkit with Auth App Dependencies using Poetry Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with 'auth-app' extra dependencies using Poetry for GitHub App authentication. ```bash poetry add githubkit[auth-app] ``` -------------------------------- ### Fetch repository information Source: https://github.com/yanyongyu/githubkit/blob/master/README.md Use the initialized GitHub SDK instance to fetch repository details. This example retrieves repository information and prints its full name. ```python from githubkit import Response from githubkit.versions.latest.models import FullRepository resp: Response[FullRepository] = github.rest.repos.get("owner", "repo") repo: FullRepository = resp.parsed_data print(repo.full_name) ``` -------------------------------- ### Authenticate as a GitHub App Installation Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/authentication.md Authenticate as a specific installation of your GitHub App to access repositories and permissions approved for that installation. API requests are attributed to the app. You can use either the app ID or client ID. ```python from githubkit import GitHub, AppInstallationAuthStrategy # Using app ID github = GitHub( AppInstallationAuthStrategy( "", "", installation_id, "", "", ) ) # Using client ID instead of app ID github = GitHub( AppInstallationAuthStrategy( None, "", installation_id, "", "" ) ) ``` -------------------------------- ### Install githubkit with Auth App Dependencies using Pip Source: https://github.com/yanyongyu/githubkit/blob/master/docs/installation.md Install githubkit with 'auth-app' extra dependencies using Pip for GitHub App authentication. ```bash pip install githubkit[auth-app] ``` -------------------------------- ### Get Repository (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to fetch repository details synchronously. Ensure you have a valid token and the correct owner and repository names. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import FullRepository github = GitHub("") resp: Response[FullRepository] = github.rest.repos.get("owner", "repo") repo: FullRepository = resp.parsed_data ``` -------------------------------- ### Paginate with Initial Cursor (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Start GraphQL pagination from a specific point by providing an initial cursor value synchronously. This allows resuming pagination or starting from a known position. ```python for result in github.graphql.paginate( query, variables={"owner": "owner", "repo": "repo", "cursor": "initial_cursor"} ): print(result) ``` -------------------------------- ### Paginate with Initial Cursor (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Start GraphQL pagination from a specific point by providing an initial cursor value asynchronously. This allows resuming pagination or starting from a known position within an async context. ```python async for result in github.graphql.paginate( query, variables={"owner": "owner", "repo": "repo", "cursor": "initial_cursor"} ): print(result) ``` -------------------------------- ### Initialize GitHub Client and Make Sync API Calls Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/calling-api-with-pat.md Initialize the GitHub client with your Personal Access Token for synchronous REST and GraphQL API calls. Ensure you have the 'githubkit' library installed. ```python from githubkit import GitHub from githubkit.versions.latest.models import PublicUser, PrivateUser # Initialize the client with your Personal Access Token github = GitHub("") # Call GitHub rest api resp = github.rest.users.get_authenticated() user: PublicUser | PrivateUser = resp.parsed_data # Call GitHub graphql api data: dict = github.graphql("{ viewer { login } }") ``` -------------------------------- ### Get Repository (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to fetch repository details asynchronously. Ensure you have a valid token and the correct owner and repository names. ```python from githubkit import Response from githubkit.versions.latest.models import FullRepository github = GitHub("") resp: Response[FullRepository] = await github.rest.repos.async_get("owner", "repo") repo: FullRepository = resp.parsed_data ``` -------------------------------- ### Define GraphQL Query Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Define your GraphQL query as a string. This example fetches the login of the current viewer. ```python query = """ { viewer { login } } """ ``` -------------------------------- ### Client Instance Reference Warning Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md This example demonstrates a common pitfall: not holding a strong reference to the githubkit client instance, which can lead to errors. Always ensure the client instance persists for the duration of its use. ```python from githubkit import GitHub def get_client() -> GitHub: return GitHub() # This will cause error get_client().rest.repos.get("owner", "repo") # This is ok client = get_client() client.rest.repos.get("owner", "repo") ``` -------------------------------- ### Define GraphQL Query with Variables (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Define a GraphQL query that accepts variables. This example fetches a repository's name based on owner and repo name. ```python query = """ query ($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { name } } """ data: dict[str, Any] = github.graphql(query, variables={"owner": "owner", "repo": "repo"}) repo_name: str = data["repository"]["name"] ``` -------------------------------- ### GitHub Actions Workflow for Python Script Source: https://context7.com/yanyongyu/githubkit/llms.txt This workflow demonstrates how to set up a Python environment in GitHub Actions, install the githubkit library, and run a Python script that uses the library. Ensure your script is named 'my_script.py' and that the GITHUB_TOKEN secret is available. ```yaml name: Example Workflow on: [pull_request] jobs: comment: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.11' - run: pip install githubkit - run: python my_script.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Asynchronous API Request on Behalf of a User Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/github-app.md This asynchronous code snippet demonstrates how to find a user's installation ID and create an issue comment using async operations. It requires app credentials and the target username. ```python from githubkit import GitHub, AppAuthStrategy from githubkit.versions.latest.models import Installation, IssueComment app_github = GitHub( AppAuthStrategy( app_id="your_app_id", private_key="your_private_key", client_id="your_client_id", client_secret="your_client_secret", ) ) # 2. Find the installation ID for a specific user resp = await app_github.rest.apps.async_get_user_installation("username") user_installation: Installation = resp.parsed_data # 3. Create a new client authenticated as that user user_github = app_github.with_auth( app_github.auth.as_installation(user_installation.id) ) # 4. Use the user client to perform actions on a repository resp = await user_github.rest.issues.async_create_comment( "owner", "repo", 1, body="Hello" ) issue: IssueComment = resp.parsed_data ``` -------------------------------- ### Define GraphQL Query with Variables (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Define a GraphQL query that accepts variables for asynchronous execution. This example fetches a repository's name. ```python query = """ query ($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { name } } """ data: dict[str, Any] = await github.async_graphql(query, variables={"owner": "owner", "repo": "repo"}) repo_name: str = data["repository"]["name"] ``` -------------------------------- ### GraphQL Query for Pagination Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Example GraphQL query structure required for pagination. It must include `nodes` and `pageInfo` with `hasNextPage` and `endCursor` for forward pagination. ```graphql query ($owner: String!, $repo: String!, $cursor: String) { repository(owner: $owner, name: $repo) { issues(first: 10, after: $cursor) { nodes { number } pageInfo { hasNextPage endCursor } } } } ``` -------------------------------- ### Synchronous API Request on Behalf of a User Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/github-app.md Use this synchronous code to find a user's installation ID and then create an issue comment on their behalf. Ensure you have the necessary app credentials and the target username. ```python from githubkit import GitHub, AppAuthStrategy from githubkit.versions.latest.models import Installation, IssueComment app_github = GitHub( AppAuthStrategy( app_id="your_app_id", private_key="your_private_key", client_id="your_client_id", client_secret="your_client_secret", ) ) # 2. Find the installation ID for a specific user resp = app_github.rest.apps.get_user_installation("username") user_installation: Installation = resp.parsed_data # 3. Create a new client authenticated as that user user_github = app_github.with_auth( app_github.auth.as_installation(user_installation.id) ) # 4. Use the user client to perform actions on a repository resp = user_github.rest.issues.create_comment("owner", "repo", 1, body="Hello") issue: IssueComment = resp.parsed_data ``` -------------------------------- ### Pass Custom Headers in API Request (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use the `headers` parameter to pass additional headers to the API request. This example sets the `Accept` header for raw JSON. ```python from githubkit import GitHub github = GitHub("") resp = github.rest.repos.get_content( "owner", "repo", "/path/to/file", headers={\"Accept\": \"application/vnd.github.raw+json\"}, ) content = resp.text ``` -------------------------------- ### Mock GitHub API Calls (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/unit-test.md Use this method for asynchronous GitHub API calls. It involves patching the `GitHub.arequest` method. This example uses `pytest.mark.anyio` for async testing. Ensure `fake_response.json` is available. ```python import json from pathlib import Path from typing import Any, Type, Union import httpx import pytest from githubkit import GitHub from githubkit.utils import UNSET from githubkit.response import Response from githubkit.typing import URLTypes, UnsetType from githubkit.versions.latest.models import FullRepository FAKE_RESPONSE = json.loads(Path("fake_response.json").read_text()) async def target_async_func() -> FullRepository: # (1)! async with GitHub("xxxxx") as github: resp = await github.rest.repos.get("owner", "repo") return resp.parsed_data async def mock_arequest( g: GitHub, method: str, url: URLTypes, *, response_model: Union[Type[Any], UnsetType] = UNSET, **kwargs: Any, # (2)! ) -> Response[Any]: if method == "GET" and url == "/repos/owner/repo": # (3)! return Response( httpx.Response(status_code=200, json=FAKE_RESPONSE), Any if response_model is UNSET else response_model, ) raise RuntimeError(f"Unexpected request: {method} {url}") # Test the target function @pytest.mark.anyio async def test_async_mock(): with pytest.MonkeyPatch.context() as m: # Patch the request method with the mock m.setattr(GitHub, "arequest", mock_arequest) repo = await target_async_func() assert isinstance(repo, FullRepository) ``` -------------------------------- ### Initialize GitHub SDK instance Source: https://github.com/yanyongyu/githubkit/blob/master/README.md Create an instance of the GitHub SDK using a Personal Access Token (PAT). Ensure you replace '' with your actual token. ```python from githubkit import GitHub github = GitHub("") ``` -------------------------------- ### Initialize GitHub with Keyword Arguments Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Pass keyword arguments directly to the GitHub constructor for custom configuration. This is suitable for single instance configurations. ```python from githubkit import GitHub github = GitHub( base_url="https://api.github.com/", accept_format=None, previews=None, user_agent="GitHubKit/Python", follow_redirects=True, timeout=None, ssl_verify=True, trust_env=True, proxy=None, transport=None, async_transport=None, event_hooks=None, async_event_hooks=None, cache_strategy=None, http_cache=True, throttler=None, auto_retry=True, rest_api_validate_body=True, ) ``` -------------------------------- ### Configure Accept Header with Previews Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Use the 'previews' parameter to enable API preview features by providing a list of feature names. The '-preview' suffix is added automatically. ```python # Enable an API preview feature github = GitHub(previews=["starfox"]) ``` -------------------------------- ### Get Latest API Version Name and Version Mapping Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Retrieve the latest API version name and the mapping of all supported versions. ```python from githubkit.versions import LATEST_VERSION, VERSIONS ``` -------------------------------- ### Initialize GitHub Client and Make Async API Calls Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/calling-api-with-pat.md Initialize the GitHub client with your Personal Access Token for asynchronous REST and GraphQL API calls. This requires an async context and the 'githubkit' library. ```python from githubkit import GitHub from githubkit.versions.latest.models import PublicUser, PrivateUser # Initialize the client with your Personal Access Token github = GitHub("") # Call GitHub rest api resp = await github.rest.users.async_get_authenticated() user: PublicUser | PrivateUser = resp.parsed_data # Call GitHub graphql api data: dict = await github.async_graphql("{ viewer { login } }") ``` -------------------------------- ### Initialize GitHub with a Config Object Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Build a Config object and pass it to the GitHub constructor using the 'config' parameter. This is useful for sharing the same configuration across multiple GitHub instances. ```python import httpx from githubkit import GitHub, Config from githubkit.retry import RETRY_DEFAULT from githubkit.cache import DEFAULT_CACHE_STRATEGY config = Config( base_url="https://api.github.com/", accept="application/vnd.github+json", user_agent="GitHubKit/Python", follow_redirects=True, timeout=httpx.Timeout(None), ssl_verify=True, trust_env=True, proxy=None, transport=None, async_transport=None, event_hooks=None, async_event_hooks=None, cache_strategy=DEFAULT_CACHE_STRATEGY, http_cache=True, throttler=None, auto_retry=RETRY_DEFAULT, rest_api_validate_body=True, ) github = GitHub(config=config) ``` -------------------------------- ### Create GitHub Client with Token Authentication Source: https://context7.com/yanyongyu/githubkit/llms.txt Initialize a GitHub client using a Personal Access Token (PAT). Recommended to use a context manager for efficient connection reuse. Supports both synchronous and asynchronous operations. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import FullRepository # Simple token authentication - pass token string directly github = GitHub("") # Using context manager for efficient connection reuse (recommended) with GitHub("") as github: resp: Response[FullRepository] = github.rest.repos.get("owner", "repo") repo: FullRepository = resp.parsed_data print(f"Repository: {repo.full_name}") print(f"Stars: {repo.stargazers_count}") print(f"Language: {repo.language}") # Async context manager async with GitHub("") as github: resp = await github.rest.repos.async_get("owner", "repo") print(resp.parsed_data.full_name) ``` -------------------------------- ### Initialize GitHub App Client Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/github-app.md Initialize the client using your app's credentials with the AppAuthStrategy. This initial client can only access app-level APIs. ```python from githubkit import GitHub, AppAuthStrategy # 1. Authenticate as the GitHub App # This client is used to get information about your app's installations. app_github = GitHub( AppAuthStrategy( app_id="your_app_id", private_key="your_private_key", client_id="your_client_id", client_secret="your_client_secret", ) ) ``` -------------------------------- ### Configure GitHubKit with LocalThrottler Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Use LocalThrottler to limit concurrent requests within the current process or event loop. This example allows at most 100 concurrent requests. ```python from githubkit import GitHub from githubkit.throttling import LocalThrottler # Allow at most 100 concurrent requests github = GitHub(throttler=LocalThrottler(100)) ``` -------------------------------- ### Get Raw API Response Data Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Access the raw data from an API response using `response.text` or `response.json()`. The loaded JSON data is typed but not validated. ```python from typing import Any from githubkit import Response from githubkit.versions.latest.models import FullRepository from githubkit.versions.latest.types import FullRepositoryType resp: Response[FullRepository, FullRepositoryType] = github.rest.repos.get("owner", "repo") repo: FullRepositoryType = resp.json() ``` -------------------------------- ### GitHub Actions Authentication with GITHUB_TOKEN Source: https://context7.com/yanyongyu/githubkit/llms.txt Authenticate GitHubKit within GitHub Actions workflows using the automatically provided GITHUB_TOKEN. This example demonstrates creating a comment on a pull request. ```python from githubkit import GitHub, ActionAuthStrategy import os import json # Automatically uses GITHUB_TOKEN from environment github = GitHub(ActionAuthStrategy()) # Example: Comment on the triggering PR in a workflow event_name = os.environ.get("GITHUB_EVENT_NAME") if event_name == "pull_request": # Read event payload with open(os.environ["GITHUB_EVENT_PATH"]) as f: event = json.load(f) pr_number = event["pull_request"]["number"] repo = os.environ["GITHUB_REPOSITORY"] owner, repo_name = repo.split("/") github.rest.issues.create_comment( owner, repo_name, pr_number, body="Thanks for your contribution! :tada:" ) ``` -------------------------------- ### Configure GitHubKit Client Directly Source: https://context7.com/yanyongyu/githubkit/llms.txt Instantiate the GitHub client with various configuration options directly in the constructor. Supports base URL for GitHub Enterprise, timeouts, redirects, caching, and request body validation. ```python import httpx from githubkit import GitHub github = GitHub( "", base_url="https://github.example.com/api/v3/", # GitHub Enterprise timeout=30.0, # 30 second timeout follow_redirects=True, http_cache=True, # Enable HTTP caching auto_retry=True, rest_api_validate_body=True, # Validate request bodies ) ``` -------------------------------- ### Custom Retry Function for GitHubKit Source: https://context7.com/yanyongyu/githubkit/llms.txt Define a custom retry strategy for GitHubKit exceptions. This example returns a RetryOption to retry RateLimitExceeded exceptions up to 3 times with a 60-second delay. ```python from githubkit.exceptions import GitHubException, RateLimitExceeded from githubkit.retry import RetryOption from datetime import timedelta def custom_retry(exc: GitHubException, retry_count: int) -> RetryOption: if isinstance(exc, RateLimitExceeded) and retry_count < 3: return RetryOption(do_retry=True, retry_after=timedelta(seconds=60)) return RetryOption(do_retry=False) github = GitHub("", auto_retry=custom_retry) ``` -------------------------------- ### Async Test Client with Mock Transport Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/unit-test.md This snippet shows how to set up an asynchronous test client using a mock transport. The mock handler should be designed to return appropriate asynchronous responses. ```python import json from pathlib import Path import httpx import pytest from githubkit import GitHub from githubkit.versions.latest.models import FullRepository FAKE_RESPONSE = json.loads(Path("fake_response.json").read_text()) async def target_async_func(github: GitHub): resp = await github.rest.repos.async_get("owner", "repo") return resp.parsed_data def mock_transport_handler(request: httpx.Request) -> httpx.Response: if request.method == "GET" and request.url.path == "/repos/owner/repo": return httpx.Response(status_code=200, json=FAKE_RESPONSE) raise RuntimeError(f"Unexpected request: {request.method} {request.url.path}") @pytest.mark.anyio async def test_async_mock(): g = GitHub("xxxxx", async_transport=httpx.MockTransport(mock_transport_handler)) repo = await target_async_func(g) assert isinstance(repo, FullRepository) ``` -------------------------------- ### Configure GitHubKit Client with Proxy Source: https://context7.com/yanyongyu/githubkit/llms.txt Set up the GitHub client to use a proxy server for network requests by providing the proxy URL during instantiation. ```python from githubkit import GitHub github = GitHub("", proxy="http://proxy.example.com:8080") ``` -------------------------------- ### Pass Custom Headers in API Request (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use the `headers` parameter to pass additional headers to the API request in an asynchronous context. This example sets the `Accept` header for raw JSON. ```python from githubkit import GitHub github = GitHub("") resp = await github.rest.repos.async_get_content( "owner", "repo", "/path/to/file", headers={\"Accept\": \"application/vnd.github.raw+json\"}, ) content = resp.text ``` -------------------------------- ### Configure Accept Header with accept_format Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Set the 'accept_format' parameter to customize the 'Accept' header for specific media type suffixes like 'raw+json'. The leading dot is added automatically. ```python # Request raw markdown content as JSON github = GitHub(accept_format="raw+json") ``` -------------------------------- ### Exchange Authorization Code for User Token Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/authentication.md Exchange an authorization code obtained from the web flow to get a user access token. Persist the resulting token and refresh token for future use. ```python from githubkit import GitHub, OAuthWebAuthStrategy, OAuthTokenAuthStrategy github = GitHub( OAuthWebAuthStrategy("", "", "") ) # sync auth: OAuthTokenAuthStrategy = github.auth.exchange_token(github) # async auth: OAuthTokenAuthStrategy = await github.auth.async_exchange_token(github) # Persist these values to your database access_token = auth.token refresh_token = auth.refresh_token ``` -------------------------------- ### Use Sync Context Manager for GitHub Client Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/reusing-client.md Wrap your GitHub instance in a `with` block to create a shared HTTP client that is automatically closed on exit. This is recommended for workloads making multiple API calls. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import FullRepository with GitHub("") as github: resp: Response[FullRepository] = github.rest.repos.get(owner="owner", repo="repo") repo: FullRepository = resp.parsed_data ``` -------------------------------- ### Exchange and Refresh Token (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/oauth-web-flow.md This asynchronous code demonstrates how to exchange an authorization code for a user token, manage the refresh token by storing and restoring it, and refresh the access token. Use this for non-blocking operations. ```python from githubkit.versions.latest.models import PublicUser, PrivateUser from githubkit import GitHub, OAuthAppAuthStrategy, OAuthTokenAuthStrategy github = GitHub(OAuthAppAuthStrategy("", "")) # redirect user to github oauth page and get the code from callback auth: OAuthTokenAuthStrategy = await github.auth.as_web_user( "" ).async_exchange_token(github) # (1)! refresh_token = auth.refresh_token auth = OAuthTokenAuthStrategy( "", "", refresh_token=refresh_token ) # (2)! await auth.async_refresh(github) # (3)! refresh_token = auth.refresh_token user_github = github.with_auth(auth) # now you can act as the user resp = await user_github.rest.users.async_get_authenticated() user: PublicUser | PrivateUser = resp.parsed_data # you can get the user name and id now username = user.login user_id = user.id ``` -------------------------------- ### Configure Proxy with String URL Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Set a proxy URL for all requests by passing a string to the 'proxy' parameter. If 'trust_env' is True and no 'proxy' is set, environment variables like HTTP_PROXY are respected. ```python github = GitHub(proxy="http://proxy.example.com:8080") ``` -------------------------------- ### Configure GitHub Enterprise Client Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/connecting-to-github-enterprise.md Instantiate the GitHub client with the `base_url` parameter pointing to your GitHub Enterprise Server's REST API endpoint. This ensures requests are directed to your instance. ```python from githubkit import GitHub from githubkit.versions.latest.models import PublicUser, PrivateUser github = GitHub("", base_url="https://example.ghe.com/api/v3/") ``` -------------------------------- ### Call GraphQL API (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Execute a GraphQL query synchronously using the `github.graphql` method. Ensure the `github` object is initialized. ```python data: dict[str, Any] = github.graphql(query) user_login: str = data["viewer"]["login"] ``` -------------------------------- ### Upload Release Asset (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use `github.request` for synchronous raw API calls. The `upload_url` from `get_release_by_tag` needs template parts removed before use. ```python from githubkit import GitHub from githubkit.versions.latest.models import Release, ReleaseAsset github = GitHub() resp = github.rest.repos.get_release_by_tag( "owner", "repo", "tag_name" ) release: Release = resp.parsed_data resp = github.request( "POST", release.upload_url.split("{? ")[0], # (1)! params={"name": "test", "label": "description"}, content=b"file content", headers={"Content-Type": "application/zip"}, response_model=ReleaseAsset, ) asset: ReleaseAsset = resp.parsed_data ``` -------------------------------- ### Configure GitHubKit with Redis Cache (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Use RedisCacheStrategy to store tokens and HTTP responses in Redis. Requires the 'redis' package. This strategy restricts the GitHub instance to sync-only operations. ```python from redis import Redis from githubkit import GitHub from githubkit.cache import RedisCacheStrategy github = GitHub( cache_strategy=RedisCacheStrategy( client=Redis(host="localhost", port=6379), prefix="githubkit:", ) ) ``` -------------------------------- ### Upload Release Asset (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use `github.arequest` for asynchronous raw API calls. The `upload_url` from `async_get_release_by_tag` needs template parts removed before use. ```python from githubkit import GitHub from githubkit.versions.latest.models import Release, ReleaseAsset github = GitHub() resp = await github.rest.repos.async_get_release_by_tag( "owner", "repo", "tag_name" ) release: Release = resp.parsed_data resp = await github.arequest( "POST", release.upload_url.split("{? ")[0], # (1)! params={"name": "test", "label": "description"}, content=b"file content", headers={"Content-Type": "application/zip"}, response_model=ReleaseAsset, ) asset: ReleaseAsset = resp.parsed_data ``` -------------------------------- ### Use GitHub Client Without Context Manager Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/reusing-client.md Instantiate GitHub without a context manager for single, one-off API calls. Note that this creates a new HTTP client per request, which is less efficient for multiple calls. ```python from githubkit import GitHub github = GitHub("") resp = github.rest.repos.get(owner="owner", repo="repo") ``` -------------------------------- ### Execute Simple GraphQL Query Source: https://context7.com/yanyongyu/githubkit/llms.txt Execute a simple GraphQL query against the GitHub API. Ensure you have the necessary permissions and the query is correctly formatted. ```python from typing import Any from githubkit import GitHub github = GitHub("") # Simple query query = """ { viewer { login name email } } """ data: dict[str, Any] = github.graphql(query) print(f"Logged in as: {data['viewer']['login']}") ``` -------------------------------- ### Create Issue with Request Body (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to create an issue synchronously, passing request body parameters as keyword arguments. Ensure you have a valid token and the correct owner and repository names. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import Issue github = GitHub("") resp: Response[Issue] = github.rest.issues.create( "owner", "repo", title="New Issue", body="This is issue body", ) išt: Issue = resp.parsed_data ``` -------------------------------- ### Render Raw Markdown (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to render raw markdown data synchronously. The response text will contain the rendered HTML. ```python from githubkit import GitHub github = GitHub("") resp = github.rest.markdown.render_raw( data="Hello **world**", ) rendered_html = resp.text ``` -------------------------------- ### Authenticate as User (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/oauth-web-flow.md Use this snippet to authenticate as a user for a single request after obtaining the authorization code. Ensure the `code` is valid and used only once. ```python from githubkit.versions.latest.models import PublicUser, PrivateUser from githubkit import GitHub, OAuthAppAuthStrategy, OAuthTokenAuthStrategy github = GitHub(OAuthAppAuthStrategy("", "")) # redirect user to github oauth page and get the code from callback user_github = github.with_auth(github.auth.as_web_user("")) # now you can act as the user resp = user_github.rest.users.get_authenticated() user: PublicUser | PrivateUser = resp.parsed_data # you can get the user name and id now username = user.login user_id = user.id ``` -------------------------------- ### Sync Test Client with Mock Transport Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/unit-test.md Use this snippet to create a synchronous test client with a mock transport. Ensure your mock handler correctly responds to expected requests. ```python import json from pathlib import Path import httpx import pytest from githubkit import GitHub from githubkit.versions.latest.models import FullRepository FAKE_RESPONSE = json.loads(Path("fake_response.json").read_text()) def target_sync_func(github: GitHub): resp = github.rest.repos.get("owner", "repo") return resp.parsed_data def mock_transport_handler(request: httpx.Request) -> httpx.Response: if request.method == "GET" and request.url.path == "/repos/owner/repo": return httpx.Response(status_code=200, json=FAKE_RESPONSE) raise RuntimeError(f"Unexpected request: {request.method} {request.url.path}") def test_sync_mock(): g = GitHub("xxxxx", transport=httpx.MockTransport(mock_transport_handler)) repo = target_sync_func(g) assert isinstance(repo, FullRepository) ``` -------------------------------- ### Import Default REST API Models (Latest Version) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md For backward compatibility, `githubkit.rest` is linked to the models of the 'latest' version by default. ```python from githubkit.rest import FullRepository ``` -------------------------------- ### Switch Authentication Strategy for GitHub App to OAuth App Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/authentication.md Configure the `AppAuthStrategy` with `client_id` and `client_secret` to create a new client authenticated as an OAuth App using the `with_auth` method. ```python from githubkit import GitHub, AppAuthStrategy github = GitHub( AppAuthStrategy( "", "", "", "" ) ) oauth_github = github.with_auth(github.auth.as_oauth_app()) ``` -------------------------------- ### Stream Repository Archive Download (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Enable streaming mode with `stream=True` for large responses like repository archives. Iterate over the response data in chunks using `resp.iter_bytes()`. ```python from githubkit import GitHub github = GitHub("") resp = github.rest.repos.download_tarball_archive( "owner", "repo", "branch", stream=True ) for chunk in resp.iter_bytes(chunk_size=8192): # do something with the chunk print(f"Received {len(chunk)} bytes") ``` -------------------------------- ### Use Async Context Manager for GitHub Client Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/reusing-client.md Use an `async with` block for asynchronous operations to ensure the HTTP client is shared and properly closed. This is the recommended approach for long-running asynchronous processes. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import FullRepository async with GitHub("") as github: resp: Response[FullRepository] = await github.rest.repos.async_get(owner="owner", repo="repo") repo: FullRepository = resp.parsed_data ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/yanyongyu/githubkit/blob/master/docs/contributing.md Executes the project's test suite using pytest. Ensure the GITHUB_TOKEN environment variable is set with a valid GitHub personal access token for authentication during tests. ```bash env GITHUB_TOKEN='' uv run --no-sync pytest -n auto tests ``` -------------------------------- ### Exchange and Refresh Token (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/oauth-web-flow.md Use this synchronous code to exchange an authorization code for a user token, store the refresh token, and then use it to obtain a new access token. Ensure the refresh token is persisted for future use. ```python from githubkit.versions.latest.models import PublicUser, PrivateUser from githubkit import GitHub, OAuthAppAuthStrategy, OAuthTokenAuthStrategy github = GitHub(OAuthAppAuthStrategy("", "")) # redirect user to github oauth page and get the code from callback auth: OAuthTokenAuthStrategy = github.auth.as_web_user("").exchange_token( github ) # (1)! refresh_token = auth.refresh_token auth = OAuthTokenAuthStrategy( "", "", refresh_token=refresh_token ) # (2)! auth.refresh(github) # (3)! refresh_token = auth.refresh_token user_github = github.with_auth(auth) # now you can act as the user resp = user_github.rest.users.get_authenticated() user: PublicUser | PrivateUser = resp.parsed_data # you can get the user name and id now username = user.login user_id = user.id ``` -------------------------------- ### Render Raw Markdown (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to render raw markdown data asynchronously. The response text will contain the rendered HTML. ```python from githubkit import GitHub github = GitHub("") resp = await github.rest.markdown.async_render_raw( data="Hello **world**", ) rendered_html = resp.text ``` -------------------------------- ### Call GraphQL API (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md Execute a GraphQL query asynchronously using the `github.async_graphql` method. Ensure the `github` object is initialized and the function is called within an async context. ```python data: dict[str, Any] = await github.async_graphql(query) user_login: str = data["viewer"]["login"] ``` -------------------------------- ### Create Issue with Request Body (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to create an issue asynchronously, passing request body parameters as keyword arguments. Ensure you have a valid token and the correct owner and repository names. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import Issue github = GitHub("") resp: Response[Issue] = await github.rest.issues.async_create( "owner", "repo", title="New Issue", body="This is issue body", ) išt: Issue = resp.parsed_data ``` -------------------------------- ### Configure GitHubKit with Async Redis Cache Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md Use AsyncRedisCacheStrategy for asynchronous Redis caching. Requires the 'redis' package with async support ('redis.asyncio'). This strategy restricts the GitHub instance to async-only operations. ```python from redis.asyncio import Redis from githubkit import GitHub from githubkit.cache import AsyncRedisCacheStrategy github = GitHub( cache_strategy=AsyncRedisCacheStrategy( client=Redis(host="localhost", port=6379), prefix="githubkit:", ) ) ``` -------------------------------- ### Authenticate as User (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/oauth-web-flow.md Use this asynchronous snippet to authenticate as a user for a single request after obtaining the authorization code. Ensure the `code` is valid and used only once. ```python from githubkit.versions.latest.models import PublicUser, PrivateUser from githubkit import GitHub, OAuthAppAuthStrategy, OAuthTokenAuthStrategy github = GitHub(OAuthAppAuthStrategy("", "")) # redirect user to github oauth page and get the code from callback user_github = github.with_auth(github.auth.as_web_user("")) # now you can act as the user resp = await user_github.rest.users.async_get_authenticated() user: PublicUser | PrivateUser = resp.parsed_data # you can get the user name and id now username = user.login user_id = user.id ``` -------------------------------- ### Stream Repository Archive Download (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Enable streaming mode with `stream=True` for large asynchronous responses like repository archives. Iterate over the response data in chunks using `resp.aiter_bytes()`. ```python from githubkit import GitHub github = GitHub("") resp = await github.rest.repos.async_download_tarball_archive( "owner", "repo", "branch", stream=True ) async for chunk in resp.aiter_bytes(chunk_size=8192): # do something with the chunk print(f"Received {len(chunk)} bytes") ``` -------------------------------- ### Create Issue with JSON Data (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to create an issue synchronously, passing the request body as a dictionary to the 'data' parameter. Ensure you have a valid token and the correct owner and repository names. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import Issue github = GitHub("") resp: Response[Issue] = github.rest.issues.create( "owner", "repo", data={"title": "New Issue", "body": "This is issue body"}, ) išt: Issue = resp.parsed_data ``` -------------------------------- ### GraphQL Forward Pagination Info Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md The `pageInfo` object structure for forward pagination, indicating if there are more pages and the cursor for the next page. ```graphql pageInfo { hasNextPage endCursor } ``` -------------------------------- ### Generate GitHub API Models and Clients Source: https://github.com/yanyongyu/githubkit/blob/master/docs/contributing.md Generates the latest models and API clients from GitHub's OpenAPI schema. This process can be memory-intensive and time-consuming. Set the GITHUB_TOKEN environment variable to avoid rate limiting. ```bash uv run bash ./scripts/run-codegen.sh ``` -------------------------------- ### Redis Caching Strategy for GitHubKit Source: https://context7.com/yanyongyu/githubkit/llms.txt Implement Redis caching for the GitHub client using RedisCacheStrategy. Requires a running Redis instance and the 'redis' Python package. ```python from redis import Redis from githubkit import GitHub from githubkit.cache import RedisCacheStrategy github = GitHub( "", cache_strategy=RedisCacheStrategy( client=Redis(host="localhost", port=6379), prefix="githubkit:" ) ) ``` -------------------------------- ### Configure GitHub Enterprise Server Base URL Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/configuration.md When using GitHub Enterprise Server, include the '/api/v3/' path suffix in the base_url. githubkit automatically appends a trailing slash if one is missing. ```python github = GitHub(base_url="https://github.example.com/api/v3/") ``` -------------------------------- ### Switch Pydantic Version for Dependencies Source: https://github.com/yanyongyu/githubkit/blob/master/docs/contributing.md Commands to synchronize project dependencies specifically for Pydantic v1 or v2. Use these to manage compatibility between Pydantic versions. ```bash # Pydantic v1 uv sync --all-extras --group pydantic-v1 ``` ```bash # Pydantic v2 uv sync --all-extras --group pydantic-v2 ``` -------------------------------- ### Create Issue with JSON Data (Async) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Use this to create an issue asynchronously, passing the request body as a dictionary to the 'data' parameter. Ensure you have a valid token and the correct owner and repository names. ```python from githubkit import GitHub, Response from githubkit.versions.latest.models import Issue github = GitHub("") resp: Response[Issue] = await github.rest.issues.async_create( "owner", "repo", data={"title": "New Issue", "body": "This is issue body"}, ) išt: Issue = resp.parsed_data ``` -------------------------------- ### GraphQL Backward Pagination Info Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/graphql.md The `pageInfo` object structure for backward pagination, indicating if there are previous pages and the cursor for the previous page. ```graphql pageInfo { hasPreviousPage startCursor } ``` -------------------------------- ### Create GitHub Issue Source: https://context7.com/yanyongyu/githubkit/llms.txt Use this to create a new issue in a GitHub repository. You can provide details like title, body, labels, and assignees as keyword arguments or a dictionary. ```python issue_resp: Response[Issue] = github.rest.issues.create( "owner", "repo", title="Bug Report: Login fails", body="Steps to reproduce:\n1. Click login\n2. Enter credentials", labels=["bug", "high-priority"], assignees=["username"] ) print(f"Created issue #{issue_resp.parsed_data.number}") ``` ```python issue_resp = github.rest.issues.create( "owner", "repo", data={"title": "Feature Request", "body": "Add dark mode support"} ) ``` -------------------------------- ### Import Versioned REST API Models Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Import models for a specific API version. Ensure the version string matches the desired API version. ```python from githubkit.versions.v2022_11_28.models import FullRepository ``` -------------------------------- ### Sync: Authenticate User with OAuth Device Flow Source: https://github.com/yanyongyu/githubkit/blob/master/docs/quickstart/oauth-device-flow.md Use this synchronous Python snippet for one-time user authentication via the OAuth device flow. It requires a client ID and a callback function to display the user code. ```python from githubkit.versions.latest.models import PublicUser, PrivateUser from githubkit import GitHub, OAuthDeviceAuthStrategy, OAuthTokenAuthStrategy # sync/async func for displaying user code to user def callback(data: dict): print(data["user_code"]) user_github = GitHub(OAuthDeviceAuthStrategy("", callback)) # now you can act as the user resp = user_github.rest.users.get_authenticated() user: PublicUser | PrivateUser = resp.parsed_data # you can get the user name and id now username = user.login user_id = user.id ``` -------------------------------- ### Paginate REST API Results (Sync) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/rest-api.md Iterate over all results from a paginated REST API endpoint using synchronous requests. Requires importing the relevant model. ```python from githubkit.versions.latest.models import Issue for issue in github.rest.paginate( github.rest.issues.list_for_repo, owner="owner", repo="repo", state="open" ): issue: Issue print(issue.number) ``` -------------------------------- ### Authenticate with Personal Access Token (PAT) Source: https://github.com/yanyongyu/githubkit/blob/master/docs/usage/getting-started/authentication.md Authenticate using a Personal Access Token (PAT). This method works for both classic and fine-grained PATs. Store tokens securely, not directly in source code. ```python from githubkit import GitHub, TokenAuthStrategy # Shorthand: pass a token string directly github = GitHub("") # Explicit: use TokenAuthStrategy github = GitHub(TokenAuthStrategy("")) ```