Skip to content

Commit 6c2344e

Browse files
authored
Merge pull request #8 from advanced-security/copilot/add-githubapi-docs
Add githubapi.py module documentation to README
2 parents 60ffd76 + dd49993 commit 6c2344e

File tree

1 file changed

+144
-5
lines changed

1 file changed

+144
-5
lines changed

README.md

Lines changed: 144 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,9 @@ 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-
## 🚀 Usage
23+
## 🚀 Scripts usage
2424

25-
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).
26-
27-
Run each specific script according to the help for each script.
25+
A note on common arguments: 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).
2826

2927
### List secret scanning alerts
3028

@@ -327,7 +325,148 @@ options:
327325
ISO date string to filter secrets detected after this date (e.g., 2023-01-01)
328326
```
329327

330-
## 🛠️ Alternatives
328+
## 🔧 The `githubapi.py` Module
329+
330+
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.
331+
332+
### Key Features
333+
334+
- **Authentication**: Automatically handles GitHub token authentication via the `GITHUB_TOKEN` environment variable or passed token
335+
- **Automatic Pagination**: Supports cursor-based pagination to retrieve all results across multiple pages
336+
- **Rate Limiting**: Automatically detects and handles GitHub API rate limits by waiting and retrying
337+
- **Flexible Scoping**: Query at repository, organization, or Enterprise level
338+
- **Date Filtering**: Filter results by date with support for ISO 8601 formats or relative dates (e.g., `7d` for 7 days ago)
339+
- **TLS Support**: Configurable TLS certificate verification, including support for custom CA bundles and self-signed certificates
340+
- **Error Handling**: Robust error handling with detailed logging
341+
342+
### The `GitHub` Class
343+
344+
The main class in the module is `GitHub`, which provides methods to interact with the GitHub API.
345+
346+
#### Initialization
347+
348+
```python
349+
from githubapi import GitHub
350+
351+
# Initialize with token from environment variable
352+
gh = GitHub()
353+
354+
# Or provide token explicitly
355+
gh = GitHub(token=some_variable)
356+
357+
# For GitHub Enterprise Server with custom hostname
358+
gh = GitHub(hostname="github.example.com")
359+
360+
# With custom CA certificate bundle
361+
gh = GitHub(verify="/path/to/ca-bundle.pem")
362+
363+
# Disable TLS verification (not recommended)
364+
gh = GitHub(verify=False)
365+
```
366+
367+
#### Main Methods
368+
369+
**`query(scope, name, endpoint, query=None, data=None, method="GET", since=None, date_field="created_at", paging="cursor", progress=True)`**
370+
371+
The core method for querying the GitHub API with automatic pagination and rate limiting.
372+
373+
- `scope`: One of `"repo"`, `"org"`, or `"ent"` (Enterprise)
374+
- `name`: Repository name (format: `owner/repo`), organization name, or Enterprise slug
375+
- `endpoint`: API endpoint path (e.g., `/secret-scanning/alerts`)
376+
- `query`: Optional dictionary of query parameters
377+
- `since`: Optional datetime to filter results by creation date
378+
- `date_field`: Field name used for date filtering (default: `"created_at"`)
379+
- `paging`: Pagination mode - `"cursor"`, `"page"`, or `None` for no pagination
380+
- `progress`: Whether to show a progress bar (default: `True`)
381+
382+
**`query_once(scope, name, endpoint, query=None, data=None, method="GET")`**
383+
384+
Make a single API request without pagination.
385+
386+
**`_get(url, headers=None, params=None)`**
387+
388+
Make a GET request to the specified URL with optional headers and parameters, respecting rate limits automatically by raising a `RateLimited` exception when necessary.
389+
390+
**`_do(url, headers=None, params=None, data=None, method="GET")`**
391+
392+
Make an HTTP request with the specified method, handling rate limits and errors.
393+
394+
**`list_code_scanning_alerts(name, state=None, since=None, scope="org", progress=True)`**
395+
396+
List code scanning alerts with optional state and date filtering.
397+
398+
**`list_secret_scanning_alerts(name, state=None, since=None, scope="org", bypassed=False, generic=False, progress=True)`**
399+
400+
List secret scanning alerts with optional filtering by state, date, bypass status, and secret type.
401+
402+
**`list_dependabot_alerts(name, state=None, since=None, scope="org", progress=True)`**
403+
404+
List Dependabot alerts with optional state and date filtering.
405+
406+
### Utility Functions
407+
408+
**`parse_date(date_string)`**
409+
410+
Parse a date string into a datetime object. Supports:
411+
412+
- Relative dates: `"7d"` (7 days ago), `"30d"` (30 days ago)
413+
- ISO 8601 dates: `"2024-10-08"`, `"2024-10-08T12:00:00Z"`
414+
- Partial ISO dates (timezone automatically added if missing)
415+
416+
```python
417+
from githubapi import parse_date
418+
419+
# Relative date
420+
since = parse_date("7d") # 7 days ago
421+
422+
# Absolute date
423+
since = parse_date("2024-10-08") # Specific date
424+
```
425+
426+
### Usage Example
427+
428+
Here's a complete example showing how to use `githubapi.py` in your own scripts:
429+
430+
```python
431+
#!/usr/bin/env python3
432+
433+
import os
434+
from githubapi import GitHub, parse_date
435+
436+
# Initialize the GitHub client
437+
gh = GitHub(token=os.getenv("GITHUB_TOKEN"))
438+
439+
# List secret scanning alerts for an organization from the last 30 days
440+
since = parse_date("30d")
441+
for alert in gh.list_secret_scanning_alerts(
442+
name="my-org",
443+
scope="org",
444+
state="open",
445+
since=since
446+
):
447+
print(f"Alert: {alert['secret_type']} in {alert['repository']['full_name']}")
448+
449+
# Query a custom endpoint with pagination
450+
for result in gh.query(
451+
scope="org",
452+
name="my-org",
453+
endpoint="/repos",
454+
paging="cursor"
455+
):
456+
print(f"Repository: {result['name']}")
457+
```
458+
459+
### Error Handling and Rate Limiting
460+
461+
The module automatically handles:
462+
463+
- **Rate Limits**: When approaching the API rate limit, the client automatically slows down requests and waits when the limit is reached
464+
- **Connection Errors**: Gracefully handles network issues and stops with available data
465+
- **HTTP Errors**: Raises appropriate exceptions for 4xx and 5xx status codes
466+
467+
All operations include debug logging that can be enabled with `logging.basicConfig(level=logging.DEBUG)`.
468+
469+
## 🛠️ Alternative tools
331470

332471
There are several alternative tools and scripts available for managing GitHub Advanced Security alerts. Some popular options include:
333472

0 commit comments

Comments
 (0)