Python Library Guide

apikeyscanner is designed from the ground up to be a robust, importable Python library. This guide explains every function and parameter you need to build custom security pipelines, hook into web backends, or script custom checks.

The Main Function: scan()

The entire scanning engine is exposed through a single, powerful function: scan(). When you call this function, the scanner resolves the target path, recursively collects files, applies over 100+ detection patterns, and returns a rich ScanResult object.

import apikeyscanner as aks

# The scan function signature
result = aks.scan(
    path=".",                        # 1. The target to scan
    severity=["HIGH", "MEDIUM"],     # 2. Filter severities (optional)
    ignore=["tests", "mocks"],       # 3. Custom ignores (optional)
    recursive=True,                  # 4. Search recursively (default: True)
    verbose=False                    # 5. Enable debug logs (default: False)
)

1. path (str or Path)

The target you want to scan. This can be a single file ("config.py"), a specific directory ("src/"), or the current working directory (".").

2. severity (list[str])

A list of severity levels to filter by. Options are "HIGH", "MEDIUM", and "LOW". If left as None, it returns all findings.

3. ignore (list[str])

A list of directory names to skip. The scanner already ignores common folders (like .git, node_modules, venv), but you can add custom ones here.

4. recursive & verbose

recursive controls if it searches inside sub-folders. verbose enables detailed logging to standard output.

Example: Line-by-Line Code Breakdown

Let's look at a practical example of writing a custom security script that fails if it finds HIGH-risk secrets, but simply warns for MEDIUM-risk secrets.

# 1. Import the library
import sys
import apikeyscanner as aks
# 2. Run the scan on the src directory, ignoring test files
result = aks.scan(
path="./src",
ignore=["tests", "fixtures"]
)
# 3. The result object gives you direct access to counts
print(f"Scanned {result.scanned_files} files.")
print(f"Found {result.total_findings} total secrets.")
# 4. We can iterate over the findings list
for finding in result.findings:
if finding.severity == "MEDIUM":
# You get exact file paths, line numbers, and the masked secret!
print(f"⚠️ Warning: {finding.type} in {finding.file} on line {finding.line}")
# 5. Use the helper properties for easy boolean checks
if result.has_high_risk:
print(f"❌ FAILED: {result.high_count} critical secrets detected!")
result.save_json("failed_scan.json") # Save a report
sys.exit(1) # Block the pipeline
else:
print("✅ Passed: No critical secrets found.")
sys.exit(0)

Real-World: FastAPI Integration

You can embed apikeyscanner directly into your web backend. For example, you could create a webhook that scans incoming PR code before allowing it to merge.

from fastapi import FastAPI, HTTPException
import apikeyscanner as aks

app = FastAPI()

@app.post("/security/scan-repo")
def scan_project(repo_path: str):
    # Scan the provided path, but only care about HIGH severity
    result = aks.scan(
        path=repo_path,
        severity=["HIGH"], 
    )

    if result.has_high_risk:
        # result.findings is a list of Finding objects.
        # We can easily convert them to dictionaries to return as JSON!
        raise HTTPException(
            status_code=403,
            detail={
                "message": "Deployment blocked. Secrets detected.",
                "findings": [finding.to_dict() for finding in result.findings],
            }
        )

    # result.summary provides a great quick-overview dict
    return {
        "message": "Safe to deploy.",
        "summary": result.summary
    }