octocrab

repository·main·Indexed 23 days ago

https://github.com/xampprocky/octocrab

A modern, extensible GitHub API client for Rust, version 0.54.1. It provides a high-level Semantic API with strongly typed models and a lower-level HTTP API for custom requests. Features include support for GitHub webhooks, notification management via NotificationsHandler, GitHub Classroom assignment tracking, and a static API for global client access.

Tokens
18.1K
Snippets
74
Records
101
Agent score
81%

What's inside octocrab

  1. How the HTTP API works

    main

    The HTTP API is a lower-level interface used to extend Octocrab when the Semantic API does not yet support a specific GitHub feature.

    There are two types of HTTP methods:

    1. Standard methods (get, post, patch, put, delete): These accept a relative route and an optional body. They automatically format the URL with the base URL and return an error if GitHub does not return a successful status.
    2. Companion methods (_get, _post, etc.): These perform no additional pre or post-processing, allowing you to manually inspect response status or headers.
  2. How the Static API works

    main

    Octocrab provides a statically reference-counted version of its API. This allows you to access the client globally without passing the instance through your entire application.

    • octocrab::initialise(builder): Sets up the global instance with specific configuration.
    • octocrab::instance(): Retrieves the global instance. If initialise hasn't been called, it returns a default client.
    // Initialises the static instance with your configuration and returns an
    // instance of the client.
    octocrab::initialise(octocrab::Octocrab::builder());
    
    // Gets a instance of `Octocrab` from the static API. If you call this
    // without first calling `octocrab::initialise` a default client will be
    // initialised and returned instead.
    let octocrab = octocrab::instance();
  3. How the Semantic API works

    main

    The Semantic API provides a high-level, strongly typed interface for interacting with GitHub. It uses a set of models that map directly to GitHub's types and provides specialized handlers for different GitHub features.

    Many methods that require multiple optional parameters use the Builder pattern, allowing you to chain configuration methods before calling .send().await.

  4. Handle GitHub Webhooks

    main

    Octocrab provides deserializable datatypes for GitHub webhook payloads. You can use WebhookEvent::try_from_header_and_body to convert an incoming HTTP request into a typed WebhookEvent, which can then be processed using pattern matching on event.kind.

    use http::request::Request;
    use tracing::{warn, info};
    use octocrab::models::webhook_events::*;
    
    let request_from_github = Request::post("https://my-webhook-url.com").body(vec![0_u8]).unwrap();
    // request_from_github is the HTTP request your webhook handler received
    let (parts, body) = request_from_github.into_parts();
    let header = parts.headers.get("X-GitHub-Event").unwrap().to_str().unwrap();
    
    let event = WebhookEvent::try_from_header_and_body(header, &body).unwrap();
    // Now you can match on event type and call any specific handling logic
    match event.kind {
        WebhookEventType::Ping => info!("Received a ping"),
        WebhookEventType::PullRequest => info!("Received a pull request event"),
        // ...
        _ => warn!("Ignored event"),
    };
  5. Extend Octocrab using the HTTP API

    main

    When the Semantic API does not cover a specific GitHub feature, you can use the lower-level HTTP API. This allows you to use the same authentication and configuration while controlling the request and response directly.

    • Standard HTTP methods: get, post, patch, put, delete accept a relative route and an optional body. These methods automatically error if GitHub returns a non-success status.
    • Companion methods: _get, _post, etc., perform no additional pre or post-processing, allowing you to manually inspect response status or headers.

    You can extend Octocrab by implementing traits for it using these methods.

    // Using the standard HTTP API
    let user: octocrab::models::Author = octocrab::instance()
        .get("/user", None::<&()>)
        .await?;
    
    // Using a companion method for manual response handling
    let response = octocrab._get("https://api.github.com/organizations").await?;
    
    // Extending Octocrab via a trait
    #[async_trait::async_trait]
    trait OrganisationExt {
      async fn list_every_organisation(&self) -> Result<Page<models::orgs::Organization>>;
    }
    
    #[async_trait::async_trait]
    impl OrganisationExt for Octocrab {
      async fn list_every_organisation(&self) -> Result<Page<models::orgs::Organization>> {
        self.get("organizations", None::<&()>).await
      }
    }
  6. Use the Semantic API for strongly typed GitHub interactions

    main

    Octocrab provides a high-level, strongly typed Semantic API that maps directly to GitHub's resources. This API uses Builder structs for methods with optional parameters, allowing for a fluent interface.

    Available modules include:

    • actions, activity, apps, checks, code_scannings, commits, current, events, gists, gitignore, issues, licenses, markdown, orgs, projects, pulls, ratelimit, repos, search, teams, users, workflows, and more.
    • Octocrab::graphql for GraphQL queries.

    To handle paginated results, use the all_pages method on a Page object.

    // Get pull request #404 from `octocrab/repo`.
    let pr = octocrab::instance().pulls("octocrab", "repo").get(404).await?;
    
    // Listing issues with optional parameters
    use octocrab::{models, params};
    let octocrab = octocrab::instance();
    let mut page = octocrab.issues("octocrab", "repo")
        .list()
        .creator("octocrab")
        .state(params::State::All)
        .per_page(50)
        .send()
        .await?;
    
    // Iterate through all pages
    let results = octocrab.all_pages::<models::issues::Issue>(page).await?;
  7. Access information about the currently authenticated user

    main

    Use the current() handler to access data related to the authenticated user or the authenticated GitHub App. Note that all methods in this handler require authentication (e.g., a personal access token).

    // Example: Fetching the current user
    let user = octocrab
        .current()
        .user()
        .await?;
    
    // Example: Fetching the currently authenticated app
    let app = octocrab
        .current()
        .app()
        .await?;
  8. Manage repository secrets with RepoSecretsHandler

    main

    The RepoSecretsHandler (accessed via .repos(owner, repo).secrets()) provides an interface to manage GitHub Actions repository secrets.

    Important Security Note: To create or update secrets, you must first retrieve the repository's public key using get_public_key() and encrypt your secret value (e.g., using the crypto_box crate) before sending it to GitHub.

    Permissions Required:

    • Most operations require an access token with the repo scope or a GitHub App with secrets repository permissions.
    • delete_secret requires admin:org scope or secrets organization permissions.
    • get_public_key is public for open repositories but requires repo scope for private ones.
  9. Manage GitHub notifications with NotificationsHandler

    main

    The NotificationsHandler provides methods to interact with GitHub's notifications API. All methods require an authenticated Octocrab instance with appropriate GitHub Access Token privileges. You can access this handler via octocrab.activity().notifications().

    Key capabilities include:

    • Retrieving specific notifications.
    • Marking notifications as read (individually, per repository, or globally).
    • Managing thread subscriptions (checking, setting, or deleting/muting).
    • Listing notifications using a builder pattern for filtering.
    let notifications = octocrab::instance()
        .activity()
        .notifications();
  10. Manage GitHub issues with IssueHandler

    main

    The IssueHandler provides a high-level API for interacting with GitHub's Issues. It allows you to create, list, update, and retrieve individual issues.

    Note on Pull Requests: GitHub's REST API v3 treats every pull request as an issue. Consequently, endpoints for 'Issues' may return both issues and pull requests. You can distinguish them by checking for the presence of the pull_request key in the response object.

    let issue = octocrab.issues("owner", "repo").get(3).await?;
  11. Initialize an Octocrab client

    main
    You can create a new Octocrab client using Octocrab::builder() for custom configurations or by using the Default implementation if the default-client feature is enabled. The default client uses https://api.github.com as the base URI and provides no authentication by default.