Skip to content

Commit 646cda5

Browse files
Copilotaegilops
andcommitted
Add comprehensive documentation for githubapi.py module to README.md
Co-authored-by: aegilops <41705651+aegilops@users.noreply.github.com>
1 parent 47a61d2 commit 646cda5

File tree

1 file changed

+127
-0
lines changed

1 file changed

+127
-0
lines changed

README.md

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,133 @@ This is a set of scripts that use these APIs to access and manage alerts. The sc
2020
- requires read access to the repository, organization or Enterprise you are querying
2121
- Note that Secret Scanning alerts are only available to admins of the repository, organization or Enterprise, a security manager, or where otherwise granted access
2222

23+
## 🔧 The `githubapi.py` Module
24+
25+
The `githubapi.py` module is a lightweight GitHub API client that provides a wrapper around the GitHub REST API. It handles authentication, pagination, rate limiting, and provides convenient methods for accessing GitHub Advanced Security alerts. All scripts in this repository use this module as their foundation.
26+
27+
### Key Features
28+
29+
- **Authentication**: Automatically handles GitHub token authentication via the `GITHUB_TOKEN` environment variable or passed token
30+
- **Automatic Pagination**: Supports cursor-based pagination to retrieve all results across multiple pages
31+
- **Rate Limiting**: Automatically detects and handles GitHub API rate limits by waiting and retrying
32+
- **Flexible Scoping**: Query at repository, organization, or Enterprise level
33+
- **Date Filtering**: Filter results by date with support for ISO 8601 formats or relative dates (e.g., `7d` for 7 days ago)
34+
- **TLS Support**: Configurable TLS certificate verification, including support for custom CA bundles and self-signed certificates
35+
- **Error Handling**: Robust error handling with detailed logging
36+
37+
### The `GitHub` Class
38+
39+
The main class in the module is `GitHub`, which provides methods to interact with the GitHub API.
40+
41+
#### Initialization
42+
43+
```python
44+
from githubapi import GitHub
45+
46+
# Initialize with token from environment variable
47+
gh = GitHub()
48+
49+
# Or provide token explicitly
50+
gh = GitHub(token="ghp_your_token_here")
51+
52+
# For GitHub Enterprise Server with custom hostname
53+
gh = GitHub(hostname="github.example.com")
54+
55+
# With custom CA certificate bundle
56+
gh = GitHub(verify="/path/to/ca-bundle.pem")
57+
58+
# Disable TLS verification (not recommended)
59+
gh = GitHub(verify=False)
60+
```
61+
62+
#### Main Methods
63+
64+
**`query(scope, name, endpoint, query=None, data=None, method="GET", since=None, date_field="created_at", paging="cursor", progress=True)`**
65+
66+
The core method for querying the GitHub API with automatic pagination and rate limiting.
67+
68+
- `scope`: One of `"repo"`, `"org"`, or `"ent"` (Enterprise)
69+
- `name`: Repository name (format: `owner/repo`), organization name, or Enterprise slug
70+
- `endpoint`: API endpoint path (e.g., `/secret-scanning/alerts`)
71+
- `query`: Optional dictionary of query parameters
72+
- `since`: Optional datetime to filter results by creation date
73+
- `date_field`: Field name used for date filtering (default: `"created_at"`)
74+
- `paging`: Pagination mode - `"cursor"`, `"page"`, or `None` for no pagination
75+
- `progress`: Whether to show a progress bar (default: `True`)
76+
77+
**`list_code_scanning_alerts(name, state=None, since=None, scope="org", progress=True)`**
78+
79+
List code scanning alerts with optional state and date filtering.
80+
81+
**`list_secret_scanning_alerts(name, state=None, since=None, scope="org", bypassed=False, generic=False, progress=True)`**
82+
83+
List secret scanning alerts with optional filtering by state, date, bypass status, and secret type.
84+
85+
**`list_dependabot_alerts(name, state=None, since=None, scope="org", progress=True)`**
86+
87+
List Dependabot alerts with optional state and date filtering.
88+
89+
### Utility Functions
90+
91+
**`parse_date(date_string)`**
92+
93+
Parse a date string into a datetime object. Supports:
94+
- Relative dates: `"7d"` (7 days ago), `"30d"` (30 days ago)
95+
- ISO 8601 dates: `"2024-10-08"`, `"2024-10-08T12:00:00Z"`
96+
- Partial ISO dates (timezone automatically added if missing)
97+
98+
```python
99+
from githubapi import parse_date
100+
101+
# Relative date
102+
since = parse_date("7d") # 7 days ago
103+
104+
# Absolute date
105+
since = parse_date("2024-10-08") # Specific date
106+
```
107+
108+
### Usage Example
109+
110+
Here's a complete example showing how to use `githubapi.py` in your own scripts:
111+
112+
```python
113+
#!/usr/bin/env python3
114+
115+
import os
116+
from githubapi import GitHub, parse_date
117+
118+
# Initialize the GitHub client
119+
gh = GitHub(token=os.getenv("GITHUB_TOKEN"))
120+
121+
# List secret scanning alerts for an organization from the last 30 days
122+
since = parse_date("30d")
123+
for alert in gh.list_secret_scanning_alerts(
124+
name="my-org",
125+
scope="org",
126+
state="open",
127+
since=since
128+
):
129+
print(f"Alert: {alert['secret_type']} in {alert['repository']['full_name']}")
130+
131+
# Query a custom endpoint with pagination
132+
for result in gh.query(
133+
scope="org",
134+
name="my-org",
135+
endpoint="/repos",
136+
paging="cursor"
137+
):
138+
print(f"Repository: {result['name']}")
139+
```
140+
141+
### Error Handling and Rate Limiting
142+
143+
The module automatically handles:
144+
- **Rate Limits**: When approaching the API rate limit, the client automatically slows down requests and waits when the limit is reached
145+
- **Connection Errors**: Gracefully handles network issues and stops with available data
146+
- **HTTP Errors**: Raises appropriate exceptions for 4xx and 5xx status codes
147+
148+
All operations include debug logging that can be enabled with `logging.basicConfig(level=logging.DEBUG)`.
149+
23150
## 🚀 Usage
24151

25152
Generally, the date in `--since` can be specified as `YYYY-MM-DD` or as `Nd` where `N` is the number of days ago. Full ISO formats are also supported. If a timezone is not specified, the date is assumed to be in UTC (`Z` timezone).

0 commit comments

Comments
 (0)