Octokit.net Documentation

repository·main·Indexed 25 days ago

https://github.com/octokit/octokit.net

A .NET client library for interacting with the GitHub API. It provides a high-level interface for common GitHub operations and supports .NET 4.6.1+ and .NET Standard 2.0+. The library includes the standard Octokit package and Octokit.Reactive for IObservable-based interactions. It features specialized models for Request and Response bodies, support for GitHub Enterprise administration APIs, and integration with SourceLink for debugging in Visual Studio.

Tokens
14.4K
Snippets
46
Records
74
Agent score
83%

What's inside Octokit.net

  1. Understand Strong Naming in Octokit.net

    main
    Octokit.net is being strong-named to ensure compatibility with Visual Studio extensibility and to prevent assembly collisions in environments like the Global Assembly Cache (GAC). This is a planned feature that will be integrated into the build process prior to the 1.0 release.
  2. Understand Octokit.net Model Design Principles

    main

    Octokit.net uses two primary types of models to represent GitHub API interactions: Request models and Response models.

    Request Models

    Used for the body of an API request. They follow these rules:

    • Required Properties: Properties required by the GitHub API are passed via the constructor and do not have a setter.
    • Optional Properties: All other properties have both a getter and a setter.
    • Naming Convention: Octokit.net automatically converts C# property names to the snake_case (Ruby casing) required by the GitHub API. For example, a property named BreakingBad is serialized as breaking_bad.

    Response Models

    Used for the body of an API response. They follow these rules:

    • Immutability: Properties have a public getter and a protected setter to ensure they are read-only for consumers while allowing for mocking.
    • Serialization: Models include both a default constructor and a constructor that accepts all parameters to facilitate easy serialization/deserialization.
    • Note on Testing: Because of the protected setters, creating response models manually in unit tests can be complex.
  3. Authenticate with a Personal Access Token or OAuth token

    main

    To access private repositories or perform actions on behalf of a user, assign Credentials to the GitHubClient.Credentials property. You can use a Personal Access Token (PAT), an OAuth access token, or an installation token from a GitHub App.

    var tokenAuth = new Credentials("token"); // This can be a PAT or an OAuth token.
    client.Credentials = tokenAuth;
  4. Step into Octokit source code during debugging

    main

    Once Enable source server support is active in Visual Studio, you can debug Octokit internals directly:

    1. Set a breakpoint in your own application code where you call Octokit.
    2. When the breakpoint is hit, use F11 (Step Into) to enter the Octokit source code.
    3. Visual Studio will automatically retrieve the source file associated with the specific type and cache it in your local symbols cache.
    4. You can then set subsequent breakpoints within the retrieved Octokit source code to continue your debugging session.
  5. Initialize a GitHubClient

    main

    To use Octokit, instantiate a GitHubClient. You must provide a ProductHeaderValue which populates the User-Agent header. GitHub requires this header to identify the application making the request. Using an unauthenticated client allows access to public APIs but is subject to lower rate limits.

    var client = new GitHubClient(new ProductHeaderValue("my-cool-app"));
  6. Create a branch using the Git Database

    main

    To create a branch, you must create a NewReference object and then use the Reference.Create API.

    Requirements for the reference name:

    • It must start with refs/.
    • It must contain two / characters (e.g., refs/heads/branch-name).

    Requirements for the commit SHA:

    • The SHA must correspond to an existing commit in the repository.
    // 1. Define the new reference
    var reference = new NewReference($"refs/heads/{branchName}", commit.Sha);
    
    // 2. Create the reference using either owner/repo name or repository ID
    var branch = await github.Git.Reference.Create(owner, repo, reference);
    // OR
    var branch = await github.Git.Reference.Create(id, reference);
  7. Start the GitHub OAuth Flow

    main

    To initiate authentication, use OauthLoginRequest to define the required permissions (Scopes) and a State value to prevent CSRF attacks. Use client.Oauth.GetGitHubLoginUrl(request) to generate the URL that the user must be navigated to.

    If you do not specify Scopes, the application will only have read access to the user's public data. You can also specify a custom RedirectUri within the request.

  8. Access GitHub Enterprise Administration APIs

    main

    Octokit provides support for GitHub Enterprise administration APIs to script administrative tasks. To use these APIs, you must initialize the GitHubClient with the enterprise instance URI and ensure your credentials have the site_admin scope. Only administrators of the GitHub Enterprise instance can access these endpoints.

    var enterprise = new Uri("https://github.myenterprise.com/");
    var github = new GitHubClient("some app name", enterprise);
    gitHub.Credentials = new Credentials("some-token-here");
    
    var stats = await github.Enterprise.AdminStats.GetStatisticsUsers();
    Console.WriteLine($"Found {stats.AdminUsers} admins, {stats.TotalUsers} total users and {stats.SuspendedUsers} suspended users");
  9. Configure Proxy Support in Octokit

    main

    To use a proxy with Octokit, you must manually construct the Connection using an HttpClientAdapter that utilizes a custom HttpMessageHandler. This is achieved by passing a factory method to the adapter that calls HttpMessageHandlerFactory.CreateDefault(proxy).

    Note: GitHub Enterprise support with a custom proxy is currently broken. Auto-wiring of proxy details at runtime is not yet supported.

    // set your proxy details here
    var proxy = new WebProxy(); 
    
    // this is the core connection
    var connection = new Connection(new ProductHeaderValue("my-cool-app"),
        new HttpClientAdapter(() => HttpMessageHandlerFactory.CreateDefault(proxy)));
    
    // and pass this connection to your client
    var client = new GitHubClient(connection);
  10. Handle label color hex codes

    main
    The GitHub API returns label colors as hex strings without the leading # character. For example, white is returned as FFFFFF instead of #FFFFFF. If you are using these values for UI styling or CSS, you must manually prepend the # symbol.