Expand description
§Octocrab: A modern, extensible GitHub API client.
Octocrab is an third party GitHub API client, allowing you to easily build
your own GitHub integrations or bots. octocrab comes with two primary
set of APIs for communicating with GitHub, a high level strongly typed
semantic API, and a lower level HTTP API for extending behaviour.
§Semantic API
The semantic API provides strong typing around GitHub’s API, as well as a
set of models that maps to GitHub’s types. Currently the following
modules are available.
actionsGitHub ActionsactivityGitHub ActivityappsGitHub AppsbillingBillingchecksGitHub Checkscode_scanningsCode ScanningcodespacesGitHub CodespacescopilotGitHub CopilotcommitsGitHub CommitscurrentInformation about the current user.dependency_graphDependency GrapheventsGitHub EventsgistsGistsgitGitHub Git Database APIgitignoreGitignore templatesOctocrab::graphqlGraphQL.issuesIssues and related items, e.g. comments, labels, etc.licensesLicense Metadata.markdownRendering Markdown with GitHubmarketplaceGitHub MarketplacemigrationsMigrationsorgsGitHub OrganisationsprojectsGitHub ProjectspullsPull RequestsratelimitRate LimitingreposRepositoriesrepos::activityRepository activityrepos::autolinksAutolinksrepos::branchesBranches and branch protectionrepos::codeownersCODEOWNERS errorsrepos::codespacesRepository codespacesrepos::commentsCommit commentsrepos::custom_propertiesRepository custom property valuesrepos::dependency_graphRepository dependency graphrepos::deploymentsDeployments and deployment statusesrepos::environmentsEnvironments and deployment protection rulesrepos::forksRepository forksrepos::hooksRepository webhooksrepos::importRepository source importsrepos::keysDeploy keysrepos::pagesGitHub Pagesrepos::releasesRepository releasesrepos::rulesetsRepository rulesets and rule suitesrepos::securityVulnerability alerts and automated security fixesrepos::statsRepository statisticsrepos::topicsRepository topicsrepos::trafficRepository trafficrepos::transferRepository transfer
searchUsing GitHub’s search.teamsTeamsusersUsersclassroomGitHub ClassroomworkflowsGitHub WorkflowsmetaGitHub Meta data
§Working with Repositories
let octocrab = octocrab::instance();
let repo = octocrab.repos("octocrab", "repo");
// Fetch repository metadata
let info = repo.get().await?;
// Check if vulnerability alerts are enabled
let alerts_enabled = repo.vulnerability_alerts().check().await?;
// List active rules that apply to a branch
let rules = repo.rules_for_branch("main").send().await?;§Getting a Pull Request
// Get pull request #404 from `octocrab/repo`.
let pr = octocrab::instance().pulls("octocrab", "repo").get(404).await?;All methods with multiple optional parameters are built as Builder
structs, allowing you to easily specify parameters.
§Listing issues
use octocrab::{models, params};
let octocrab = octocrab::instance();
// Returns the first page of all issues.
let mut page = octocrab.issues("octocrab", "repo")
.list()
// Optional Parameters
.creator("octocrab")
.state(params::State::All)
.per_page(50)
.send()
.await?;
// Go through every page of issues. Warning: There's no rate limiting so
// be careful.
let results = octocrab.all_pages::<models::issues::Issue>(page).await?;
§HTTP API
The typed API currently doesn’t cover all of GitHub’s API at this time, and
even if it did GitHub is in active development and this library will
likely always be somewhat behind GitHub at some points in time. However that
shouldn’t mean that in order to use those features that you have to now fork
or replace octocrab with your own solution.
Instead octocrab exposes a suite of HTTP methods allowing you to easily
extend Octocrab’s existing behaviour. Using these HTTP methods allows you
to keep using the same authentication and configuration, while having
control over the request and response. There is a method for each HTTP
method get, post, patch, put, delete, all of which accept a
relative route and a optional body.
let user: octocrab::models::Author = octocrab::instance()
.get("/user", None::<&()>)
.await?;Each of the HTTP methods expects a body, formats the URL with the base
URL, and errors if GitHub doesn’t return a successful status, but this isn’t
always desired when working with GitHub’s API, sometimes you need to check
the response status or headers. As such there are companion methods _get,
_post, etc. that perform no additional pre or post-processing to
the request.
let octocrab = octocrab::instance();
let response = octocrab
._get("https://api.github.com/organizations")
.await?;
// You can also use `Uri::builder().authority("<my custom base>").path_and_query("<my custom path>")` if you want to customize the base uri and path.
let response = octocrab
._get(Uri::builder().path_and_query("/organizations").build().expect("valid uri"))
.await?;You can use the those HTTP methods to easily create your own extensions to
Octocrab’s typed API.
use octocrab::{Octocrab, Page, Result, models};
trait OrganisationExt {
async fn list_every_organisation(&self) -> Result<Page<models::orgs::Organization>>;
}
impl OrganisationExt for Octocrab {
async fn list_every_organisation(&self) -> Result<Page<models::orgs::Organization>> {
self.get("organizations", None::<&()>).await
}
}You can also easily access new properties that aren’t available in the
current models using serde.
use serde::Deserialize;
#[derive(Deserialize)]
struct RepositoryWithVisibility {
#[serde(flatten)]
inner: octocrab::models::Repository,
visibility: String,
}
let my_repo = octocrab::instance()
.get::<RepositoryWithVisibility, _, _>("https://api.github.com/repos/XAMPPRocky/octocrab", None::<&()>)
.await?;§Static API
octocrab also provides a statically reference count version of its API,
allowing you to easily plug it into existing systems without worrying
about having to integrate and pass around the client.
// Initialises the static instance with your configuration and returns an
// instance of the client.
tokio_test::block_on(async {
octocrab::initialise(Octocrab::default());
// 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.
octocrab::instance();§GitHub webhook application support
octocrab provides deserializable datatypes
for the payloads received by a GitHub application responding to
webhooks.
This allows you to write a typesafe application using Rust with
pattern-matching/enum-dispatch to respond to events.
Note: Webhook support in octocrab is still beta, not all known webhook events are
strongly typed.
// 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"),
};Modules§
- actions
- GitHub Actions
- activity
- Github Activity API
- apps
- auth
- Authentication related types and functions.
- billing
- The GitHub Billing API.
- checks
- classroom
- code_
scannings - The code scanning API.
- codespaces
- GitHub Codespaces API.
- commits
- The commit API.
- copilot
- GitHub Copilot API.
- current
- Get data about the currently authenticated user.
- dependency_
graph - GitHub Dependency Graph API.
- enterprises
- The Enterprise API.
- etag
- Types for handling etags.
- events
- GitHub Events
- gist_
comments - The gist comments API.
- gists
- The gist API
- git
- GitHub Git Database API.
- gitignore
- The gitignore API
- hooks
- The hooks API.
- issues
- The issue API.
- licenses
- Metadata about popular open source licenses and information about a project’s license file.
- markdown
- The markdown API
- marketplace
- GitHub Marketplace API.
- meta
- The metadata API.
- migrations
- User Migrations API.
- models
- Serde mappings from GitHub’s JSON to structs.
- orgs
- The Organization API.
- packages
- The GitHub Packages API.
- params
- Common GitHub Parameter Types
- projects
- The Projects API.
- pulls
- The pull request API.
- ratelimit
- Github RateLimit API
- repos
- The repositories API.
- search
- Using GitHub’s search.
- security_
advisories - service
- teams
- The Teams API
- users
- The users API.
- workflows
Structs§
- Cached
Token - A cached API access token (which may be None)
- Default
Octocrab Builder Config - GitHub
Error - An error returned from GitHub’s API.
- Graphql
Error - An individual GraphQL error. Following the GraphQL October 2021 Spec.
- Graphql
Error Location - Graphql
Error Response - Graphql
OkResponse - Layer
Ready - NoAuth
- NoConfig
- NoSvc
- NotLayer
Ready - Octo
Body - Octocrab
- The GitHub API client.
- Octocrab
Builder - A builder struct for
Octocrab, allowing you to configure the client, such as using GitHub previews, the github instance, authentication, etc. - Page
- A Page of GitHub results, with links to the next and previous page.
Enums§
- Auth
State - State used for authenticate to Github
- Error
- An error that could have occurred while using
crate::Octocrab. - Graphql
Path Segment - A path can consist of field names (Strings) and list indices (usize).
- Graphql
Response - GraphQL Response.
GraphQL can return a response with
dataorerrors, or both in the case of a partial success. - Reqwest
Client Config reqwest - Which
reqwest::ClientOctocrabBuilder::build_with_reqwestshould use.
Constants§
Traits§
- From
Response - A trait for mapping from a
http::Responseto an another type.
Functions§
- format_
media_ type - Formats a media type from it’s name into the full value for the
Acceptheader. - format_
preview - Formats a GitHub preview from it’s name into the full value for the
Acceptheader. - initialise
default-client - Initialises the static instance using the configuration set by
builder. - instance
default-client - Returns a new instance of
Octocrab. If it hasn’t been previously initialised it returns a default instance with no authentication set. - map_
github_ error - Maps a GitHub error response into and
Err()variant if the status is not a success.
Type Aliases§
- Octocrab
Service - Result
- A convenience type with a default error type of
Error.