Skip to main content

Module client

Module client 

Source
Expand description

GitHub API client for authenticated operations.

This module provides the primary interface for interacting with GitHub’s REST API as a GitHub App. It handles authentication, rate limiting, retries, pagination, and provides type-safe operations for repositories, issues, pull requests, projects, and more.

§Overview

The client operates at two levels:

  • App-level (GitHubClient) - Operations as the GitHub App itself (using JWT)
  • Installation-level (InstallationClient) - Operations within a specific installation (using installation tokens)

Most operations happen at the installation level, where you interact with repositories, issues, pull requests, etc. on behalf of the installation.

§Features

  • Automatic Authentication - Tokens are injected and refreshed automatically
  • Rate Limit Handling - Detects rate limits and backs off appropriately
  • Retry Logic - Exponential backoff for transient failures (network errors, 5xx responses)
  • Pagination Support - Helper methods for paginated API responses
  • Type Safety - Strongly-typed request and response models
  • Configurable - Timeouts, retry behavior, rate limit margins

§Quick Start

use github_bot_sdk::{
    auth::{AuthenticationProvider, InstallationId},
    client::{GitHubClient, ClientConfig},
    error::ApiError,
};
use std::time::Duration;

// Create client with custom configuration
let client = GitHubClient::builder(auth)
    .config(ClientConfig::default()
        .with_user_agent("my-bot/1.0")
        .with_timeout(Duration::from_secs(30))
        .with_max_retries(5))
    .build()?;

// Get app information (app-level operation)
let app = client.get_app().await?;
println!("Running as: {}", app.name);

// Get installation information
let installation_id = InstallationId::new(12345);
let installation = client.get_installation(installation_id).await?;
println!("Installation: {}", installation.id.as_u64());

§Configuration

Use ClientConfig to customize client behavior:

use github_bot_sdk::client::ClientConfig;
use std::time::Duration;

let config = ClientConfig::default()
    .with_user_agent("my-github-bot/1.0")           // Required by GitHub
    .with_timeout(Duration::from_secs(60))          // Request timeout
    .with_max_retries(5)                            // Max retry attempts
    .with_rate_limit_margin(0.1)                    // Keep 10% rate limit buffer
    .with_github_api_url("https://api.github.com"); // Override for GHE

// Or use the builder pattern
let config = ClientConfig::builder()
    .user_agent("my-bot/2.0")
    .timeout(Duration::from_secs(45))
    .max_retries(3)
    .build();

§Operations by Category

§Repository Operations

let installation_id = InstallationId::new(12345);
let _installation = client.get_installation(installation_id).await?;

// Repository operations are available through client methods
// See InstallationClient and related modules for detailed API

§Issue Operations

let installation_id = InstallationId::new(12345);
let _installation = client.get_installation(installation_id).await?;

// Issue operations through client methods
// Create, comment, label, and manage issues

§Pull Request Operations

let installation_id = InstallationId::new(12345);
let _installation = client.get_installation(installation_id).await?;

// Pull request operations through client methods
// Create, review, merge, and manage PRs

§Project Operations (GitHub Projects V2)

let installation_id = InstallationId::new(12345);
let _installation = client.get_installation(installation_id).await?;

// Project operations through client methods

§Rate Limiting

The client automatically handles GitHub’s rate limits:

  • Detection - Monitors X-RateLimit-* headers in responses
  • Proactive Backoff - Slows down when approaching limit (configurable margin)
  • Reactive Handling - Respects Retry-After headers on 429 responses
  • Secondary Rate Limits - Handles abuse detection (403 with retry-after)
// Configure rate limit behavior
let config = ClientConfig::default()
    .with_rate_limit_margin(0.15);  // Start backing off at 85% of limit

let client = GitHubClient::builder(auth)
    .config(config)
    .build()?;

// Client will automatically handle rate limits
// No manual rate limit checking needed

§Retry Behavior

The client automatically retries transient failures with exponential backoff:

  • Retryable Errors:

    • Network errors (timeouts, connection failures)
    • 5xx server errors (GitHub is having issues)
    • 429 rate limit exceeded (respects Retry-After)
    • 403 with Retry-After (secondary rate limit)
  • Non-Retryable Errors:

    • 4xx client errors (except 429 and some 403s)
    • Authentication failures
    • Validation errors
use github_bot_sdk::client::ClientConfig;
use std::time::Duration;

// Configure retry behavior
let config = ClientConfig::default()
    .with_max_retries(5)                            // Max attempts
    .with_timeout(Duration::from_secs(30));         // Request timeout

// Default exponential backoff is applied automatically

§Pagination

GitHub’s API uses Link headers for pagination. See specific operation documentation for examples.

let installation_id = InstallationId::new(12345);

// Get installation
let installation = client.get_installation(installation_id).await?;
println!("Installation: {}", installation.id.as_u64());

§Error Handling

All operations return Result<T, ApiError>:

let installation_id = InstallationId::new(12345);

// Error handling example
match client.get_installation(installation_id).await {
    Ok(installation) => println!("Found installation: {}", installation.id.as_u64()),
    Err(ApiError::NotFound { .. }) => {
        println!("Installation doesn't exist or no access");
    }
    Err(ApiError::RateLimitExceeded { reset_at, .. }) => {
        println!("Rate limited, resets at: {:?}", reset_at);
    }
    Err(ApiError::AuthorizationFailed) => {
        println!("Insufficient permissions");
    }
    Err(e) => return Err(e),
}

§GitHub Enterprise Support

To use with GitHub Enterprise Server, configure the API base URL:

use github_bot_sdk::client::ClientConfig;

let config = ClientConfig::default()
    .with_github_api_url("https://github.example.com/api/v3");

§See Also

Structs§

AddProjectV2ItemRequest
Request to add an item to a project.
App
GitHub App metadata.
Branch
Git branch with commit information.
ClientConfig
Configuration for GitHub API client behavior.
ClientConfigBuilder
Builder for constructing ClientConfig instances.
Comment
Comment on an issue.
Commit
Commit reference (used in branches, tags, and pull requests).
CommitDetails
Git-level commit metadata.
CommitReference
A minimal reference to a Git object containing only its SHA and API URL.
Comparison
The result of comparing two Git refs (commits, branches, or tags).
CreateCommentRequest
Request to create a comment.
CreateIssueRequest
Request to create a new issue.
CreateLabelRequest
Request to create a label.
CreateMilestoneRequest
Request to create a new milestone.
CreatePullRequestCommentRequest
Request to create a pull request comment.
CreatePullRequestRequest
Request to create a new pull request.
CreateReleaseRequest
Request to create a release.
CreateReviewRequest
Request to create a review.
DismissReviewRequest
Request to dismiss a review.
FileChange
A single file change within a Comparison.
FullCommit
A complete GitHub commit with all metadata.
GitHubClient
GitHub API client for authenticated operations.
GitHubClientBuilder
Builder for constructing GitHubClient instances.
GitRef
Git reference (branch, tag, etc.).
GitSignature
An identity record stored in a Git commit object.
InstallationClient
Installation-scoped GitHub API client.
Issue
GitHub issue.
IssueActivityEvent
A discrete activity event recorded on an issue.
IssueRename
Issue rename payload inside activity events.
IssueUser
User associated with an issue.
IssuesClient
Domain client for GitHub issue operations.
Label
GitHub label.
LabelsClient
Domain client for repository-level label catalogue operations.
MergePullRequestRequest
Request to merge a pull request.
MergeResult
Result of merging a pull request.
Milestone
Milestone associated with an issue or pull request.
MilestoneSummary
Brief milestone reference used inside activity events.
MilestonesClient
Domain client for milestone lifecycle operations.
PagedResponse
Paginated response wrapper.
Pagination
Pagination metadata extracted from Link headers.
ProjectOwner
Project owner (organisation or user).
ProjectV2
GitHub Projects v2 project.
ProjectV2Item
Item in a GitHub Projects v2 project.
ProjectsClient
Domain client for GitHub Projects V2 operations.
PullRequest
GitHub pull request.
PullRequestBranch
Branch information in a pull request.
PullRequestComment
Comment on a pull request (review comment on code).
PullRequestRepo
Repository information in a pull request branch.
PullRequestsClient
Domain client for pull request operations.
RateLimit
Rate limit information from GitHub API response headers.
RateLimitInfo
Rate limit information from GitHub API.
RateLimiter
Thread-safe rate limit tracker for GitHub API operations.
Reaction
A single reaction on an issue or issue comment.
Release
GitHub release.
ReleaseAsset
Asset attached to a release.
ReleasesClient
Domain client for release operations.
RepositoriesClient
Domain client for repository, branch, tag, git-ref, and commit operations.
Repository
GitHub repository with metadata.
RepositoryOwner
Repository owner (user or organization).
RetryPolicy
Retry policy for transient errors.
Review
Pull request review.
Tag
Git tag information.
TriggerWorkflowRequest
Request to trigger a workflow.
UpdateCommentRequest
Request to update a comment.
UpdateIssueRequest
Request to update an existing issue.
UpdateLabelRequest
Request to update a label.
UpdateMilestoneRequest
Request to update an existing milestone.
UpdatePullRequestCommentRequest
Request to update a pull request comment.
UpdatePullRequestRequest
Request to update an existing pull request.
UpdateReleaseRequest
Request to update a release.
UpdateReviewRequest
Request to update a review.
Verification
GPG or SSH signature verification status for a commit.
Workflow
GitHub Actions workflow.
WorkflowRun
GitHub Actions workflow run.
WorkflowsClient
Domain client for GitHub Actions workflow and run operations.

Enums§

LockReason
Reason used when locking an issue.
MilestoneSortField
Sort field for milestone list queries.
MilestoneState
Milestone state.
OwnerType
Owner type classification.
RateLimitContext
Authentication context for rate limit tracking.
ReactionContent
Emoji content for a GitHub reaction.
SortDirection
Sort direction for list queries.
TimelineEvent
A single item in an issue’s full timeline.
WorkflowRunConclusion
Conclusion of a completed GitHub Actions workflow run.
WorkflowRunStatus
Status of a GitHub Actions workflow run.
WorkflowState
State of a GitHub Actions workflow.

Functions§

calculate_rate_limit_delay
Calculate delay for rate limit exceeded (429) response.
detect_secondary_rate_limit
Detect secondary rate limit (abuse detection) from 403 response.
extract_page_number
Extract page number from a URL.
parse_link_header
Parse pagination metadata from Link header.
parse_rate_limit_from_headers
Parse rate limit information from HTTP response headers.
parse_retry_after
Parse Retry-After header from HTTP response.