### Complete ZAP Spider Usage Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/SPIDER.md Demonstrates a full workflow of configuring the spider, starting a scan, monitoring its progress, and retrieving discovered URLs. ```python from zapv2 import ZAPv2 import time zap = ZAPv2(apikey='your-api-key') # Configure spider zap.spider.set_option_max_depth(5) zap.spider.set_option_max_children(50) # Start scan target_url = 'https://example.com' scan_id = zap.spider.scan(target_url, recurse=True) print(f"Spider scan started: {scan_id}") # Monitor progress while True: progress = zap.spider.status(scanid=scan_id) print(f"Progress: {progress}%") if progress >= 100: break time.sleep(2) # Get results urls = zap.spider.results(scanid=scan_id) print(f"\nDiscovered URLs:") for url in urls: print(f" - {url}") # Detailed results full = zap.spider.full_results(scanid=scan_id) print(f"\nFull results: {full}") # Check all discovered URLs all_urls = zap.spider.all_urls print(f"\nTotal unique URLs: {len(all_urls)}") ``` -------------------------------- ### Complete Alert Management Example in Python Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ALERT.md This comprehensive example demonstrates how to interact with the ZAP API to fetch alert summaries, retrieve alerts by risk level, view detailed alert information, mark alerts as false positives, and get the total number of alerts. Ensure you have the 'zapv2' library installed and replace 'your-api-key' with your actual ZAP API key. ```python from zapv2 import ZAPv2 zap = ZAPv2(apikey='your-api-key') # Get alert summary summary = zap.alert.alerts_summary() print(f"Alert Summary: {summary}") # Get all high-risk alerts high_risk_alerts = zap.alert.alerts(riskid=3) print(f"\nHigh-Risk Alerts ({len(high_risk_alerts)}):") for alert in high_risk_alerts[:5]: print(f" - {alert['alert']} on {alert['url']}") print(f" Risk: {alert['riskdesc']}, Confidence: {alert['confidencedesc']}") print(f" Parameter: {alert.get('param', 'N/A')}") print(f" CWE: {alert.get('cweid', 'N/A')}") # Get details of specific alert if high_risk_alerts: alert_id = high_risk_alerts[0]['id'] alert_details = zap.alert.alert(alert_id) print(f"\nAlert {alert_id} Details:") print(f" Description: {alert_details['description']}") print(f" Evidence: {alert_details.get('evidence', 'N/A')}") print(f" Solution: {alert_details.get('solution', 'N/A')}") # Manage false positives all_alerts = zap.alert.alerts() false_positives = [a for a in all_alerts if a.get('falsepositive')] if false_positives: ids = ','.join(str(a['id']) for a in false_positives) zap.alert.update_alerts_confidence(ids, confidenceid=0) print(f"\nMarked {len(false_positives)} alerts as false positives") # Generate report print(f"\nTotal alerts: {zap.alert.number_of_alerts()}") ``` -------------------------------- ### Complete Active Scan Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md This script demonstrates the full lifecycle of an active scan: configuring scanner options, setting exclusions, starting a scan, monitoring its progress, and retrieving alerts and messages. Ensure you have the 'zapv2' library installed and replace 'your-api-key' with your actual ZAP API key. ```python from zapv2 import ZAPv2 import time zap = ZAPv2(apikey='your-api-key') # Configure active scanner zap.ascan.set_option_thread_per_host(4) zap.ascan.set_option_delay_in_ms(100) zap.ascan.set_option_max_alerts_per_rule(20) # Exclude certain patterns zap.ascan.exclude_from_scan(r'.*\.(jpg|png|css|js)$') zap.ascan.exclude_from_scan(r'.*/admin/.*') # Start active scan target_url = 'https://example.com' scan_id = zap.ascan.scan( target_url, recurse=True, scanpolicyname='Default Policy' ) print(f"Active scan started: {scan_id}") # Monitor progress while True: progress = zap.ascan.status(scanid=scan_id) print(f"Scan progress: {progress}%") if progress >= 100: break time.sleep(5) # Get scan results alert_ids = zap.ascan.alerts_ids(scanid=scan_id) print(f"\nFound {len(alert_ids)} alerts") for alert_id in alert_ids[:5]: alert = zap.core.alert(alert_id) print(f"Alert: {alert['alert']} - Risk: {alert['riskdesc']}") # Get messages from scan msg_ids = zap.ascan.messages_ids(scanid=scan_id) print(f"Total messages sent: {len(msg_ids)}") ``` -------------------------------- ### Complete ZAP API Usage Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md A comprehensive example demonstrating common ZAP API Python client operations. Includes initialization, target exploration, state checking, alert retrieval, session management, and report generation. ```python from zapv2 import ZAPv2 zap = ZAPv2(apikey='your-api-key') # Explore the target print("Available sites:", zap.core.sites) print("All URLs:", zap.core.urls()) # Check current state print(f"Mode: {zap.core.mode}") print(f"Version: {zap.core.version}") # Get alerts summary = zap.core.alerts_summary() print(f"Alert summary: {summary}") high_risk = zap.core.alerts(riskid=3) for alert in high_risk: print(f"High-risk alert: {alert['alert']} at {alert['url']}") # Session management zap.core.new_session(name='test-scan', overwrite=True) # ... perform scanning ... zap.core.save_session(name='test-scan') # Generate reports html = zap.core.htmlreport() with open('scan-report.html', 'w') as f: f.write(html) ``` -------------------------------- ### Install ZAP Python API Source: https://github.com/zaproxy/zap-api-python/blob/main/README.md Install the latest released version of the ZAP Python API using pip. ```bash pip install zaproxy ``` -------------------------------- ### Performing Core Actions Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/INDEX.md Illustrates how to initiate new ZAP sessions and start spider scans. ```APIDOC ## Performing Core Actions ### Description Initiate actions such as creating a new session or starting a spider scan on a target URL. ### Method ```python # Start a new session result = zap.core.new_session(name='test') # Start a spider scan on a URL scan_id = zap.spider.scan('https://example.com') ``` ### Parameters - `zap.core.new_session`: `name` (str, required) - `zap.spider.scan`: `url` (str, required) ``` -------------------------------- ### Start a Spider Scan Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/SPIDER.md Initiates a new spider scan from a specified URL. Supports optional parameters for context, user authentication, recursion, and scan policies. Returns the unique ID of the started scan. ```python scan_id = zap.spider.scan('https://example.com') print(f"Started spider scan: {scan_id}") ``` ```python scan_id = zap.spider.scan( 'https://example.com', contextid=1, recurse=True, user='testuser' ) ``` -------------------------------- ### Start Active Scan as User Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Starts an active scan on a specified URL, authenticated as a particular user within a given context. Useful for scanning authenticated sections of a web application. ```python scan_id = zap.ascan.scan_as_user( 'https://example.com', contextid=1, user='authenticated-user' ) ``` -------------------------------- ### Start New ZAP Session and Spider Scan Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/INDEX.md Initiate a new ZAP session with a specified name or start a spider scan on a given URL. Returns a status dictionary or scan ID. ```python result = zap.core.new_session(name='test') # Returns status dict scan_id = zap.spider.scan('https://example.com') # Returns ID ``` -------------------------------- ### Error Handling Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/INDEX.md Provides a robust example of how to handle potential errors when interacting with the ZAP API. ```APIDOC ## Error Handling Example ### Description This example demonstrates how to use a try-except block to catch potential `ValueError` for invalid URLs or general `Exception` for other ZAP API errors. ### Method ```python try: # Initialize ZAP client with strict validation enabled zap = ZAPv2(apikey='key', validate_status_code=True) # Example action that might raise an error result = zap.core.urls(baseurl='https://example.com') except ValueError as e: print(f"Invalid URL: {e}") except Exception as e: print(f"ZAP API error: {e}") ``` ### Parameters - `ZAPv2`: `apikey` (str, required), `validate_status_code` (bool, optional) - `zap.core.urls`: `baseurl` (str, required) ``` -------------------------------- ### Start Spider Scan as User Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/SPIDER.md Starts a spider scan specifically as a defined user within a given context. Requires the URL, context ID, and user identifier. Supports optional parameters for recursion and scan policies. Returns the scan ID. ```python scan_id = zap.spider.scan_as_user( 'https://example.com', contextid=1, user='authenticated-user' ) ``` -------------------------------- ### Get Add Query Param Option Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Checks whether the option to add query parameters to GET requests during scanning is enabled. This affects how GET requests are fuzzed. ```python enabled = zap.ascan.option_add_query_param print(f"Add query param: {enabled}") ``` -------------------------------- ### Get Available Scan Policy Names Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Fetches a list of all available active scan policy names. This is useful for selecting a policy when starting a new scan. ```python policies = zap.ascan.scan_policy_names print(f"Available policies: {policies}") ``` -------------------------------- ### Navigate Site Tree and Retrieve URLs Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/USAGE_GUIDE.md This snippet shows how to use the ZAP API to get all sites, retrieve all URLs, filter URLs by a base URL, get child nodes of a specific URL, and access recent messages. ```python from zapv2 import ZAPv2 zap = ZAPv2(apikey='api-key') # Get all sites sites = zap.core.sites print(f"Sites: {sites}") # Get all URLs all_urls = zap.core.urls() print(f"Total URLs: {len(all_urls)}") # Get filtered URLs api_urls = zap.core.urls(baseurl='https://api.example.com') print(f"API URLs: {len(api_urls)}") # Get child nodes children = zap.core.child_nodes(url='https://example.com/') print(f"Child nodes: {children}") # Access messages messages = zap.core.messages(count=10) for msg in messages: print(f" {msg['requestHeader'].split()[0]} {msg['requestHeader'].split()[1]}") ``` -------------------------------- ### Get Option Add Query Param Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Checks whether query parameters are added to GET requests during scanning. This is a property that returns a boolean. ```APIDOC ## option_add_query_param ### Description Whether to add query parameters to GET requests. ### Method GET (property access) ### Endpoint N/A (property access) ### Parameters None ### Response #### Success Response (200) - **option_add_query_param** (bool) - True if enabled, False otherwise ### Response Example ```json true ``` ``` -------------------------------- ### version Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets the ZAP version. This is a property that returns the ZAP version as a string. ```APIDOC ## version ### Description Gets the ZAP version. ### Method GET ### Endpoint /JSON/core/view/version/ ### Parameters None ### Response #### Success Response (200) - **version** (string) - Version string (e.g., `"2.13.0"`) ### Request Example ```python version = zap.core.version print(f"ZAP Version: {version}") ``` ### Response Example ```json { "version": "2.13.0" } ``` ``` -------------------------------- ### alert Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets an alert by ID. Returns an alert object. ```APIDOC ## alert(id) ### Description Gets an alert by ID. ### Method GET (Assumed based on typical API patterns for retrieving data) ### Endpoint /JSON/core/view/alert/ ### Parameters #### Query Parameters - **id** (integer) - Required - Alert ID ### Response #### Success Response (200) - **alert** (dict) - Alert object with messageId, name, risk level, confidence, description, uri, param, attack, evidence, cweId, wascId, sourceid ### Request Example ```python alert = zap.core.alert(42) print(f"Alert: {alert['alert']}") print(f"Risk: {alert['riskdesc']}") print(f"URL: {alert['url']}") ``` ``` -------------------------------- ### Endpoint Structure Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/API_ENDPOINTS.md Illustrates the general pattern for ZAP API endpoints, including component, action type, operation, and parameters. ```text http://zap/JSON/{component}/{action-type}/{operation}/?{parameters} ``` -------------------------------- ### Authenticated Scanning Setup Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/USAGE_GUIDE.md Sets up ZAP for authenticated scanning by creating a new context, defining a user, and configuring credentials for testing. ```python from zapv2 import ZAPv2 zap = ZAPv2(apikey='api-key') # Step 1: Create context for authenticated testing context_id = zap.context.new_context(contextname='authenticated') print(f"[+] Context created: {context_id}") # Step 2: Add authentication details auth_type = 'form' # or 'script', 'http', etc. # Configure auth based on your application # Step 3: Create user for testing user_id = zap.users.new_user(contextid=context_id, name='testuser') print(f"[+] User created: {user_id}") # Step 4: Set user credentials zap.users.set_user_name(contextid=context_id, userid=user_id, name='testuser') # Step 5: Run scan as authenticated user target = 'https://example.com' scan_id = zap.ascan.scan_as_user( url=target, contextid=context_id, user=user_id, recurse=True ) print(f"[+] Authenticated scan started: {scan_id}") # Monitor and get results... ``` -------------------------------- ### Perform Active Scan Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/INDEX.md Starts an active scan on a target URL, waits for it to complete, and then retrieves any found alerts. ```python # Start active scan scan_id = zap.ascan.scan('https://example.com') # Wait for completion while True: progress = zap.ascan.status(scanid=scan_id) if progress >= 100: break time.sleep(5) # Get alerts alerts = zap.alert.alerts() for alert in alerts: print(f"{alert['alert']} - Risk: {alert['riskdesc']}") ``` -------------------------------- ### Python Method Call Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/MODULES.md Calls ZAP API methods that accept parameters. Parameters like 'baseurl' and 'count' are common. ```python alerts = zap.alert.alerts(baseurl='https://example.com', count=50) ``` ```python scan_id = zap.spider.scan('https://example.com') ``` -------------------------------- ### Python Property Access Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/MODULES.md Accesses view-only properties of ZAP API modules. Ensure the ZAP API client is initialized. ```python hosts = zap.core.hosts # Get all hosts ``` ```python sites = zap.spider.scans # Get all spider scans ``` -------------------------------- ### Get Available Sites Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Retrieves a list of all sites that ZAP has discovered or is aware of. This is useful for understanding the scope of the current session. ```APIDOC ## sites() ### Description Retrieves a list of all sites that ZAP has discovered or is aware of. ### Response #### Success Response (200) - **Sites** (list) - A list of site URLs ``` -------------------------------- ### scan_as_user Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Starts an active scan as a specific user within a given context. Allows for authenticated scanning scenarios. ```APIDOC ## scan_as_user ### Description Starts an active scan as a specific user within a given context. Allows for authenticated scanning scenarios. ### Method POST ### Endpoint /JSON/ascan/action/scanAsUser/ ### Parameters #### Query Parameters - **url** (string) - Yes - URL to scan - **contextid** (integer) - Yes - Context ID - **user** (string) - Yes - User ID or name - **recurse** (boolean) - No - Recursive scan - **inscopeonly** (boolean) - No - In-scope only - **scanpolicyname** (string) - No - Policy name - **method** (string) - No - HTTP method - **postdata** (string) - No - POST data - **apikey** (string) - No - API key ### Response #### Success Response (200) - **scanAsUser** (integer) - Scan ID ### Response Example ```json { "scanAsUser": "2" } ``` ``` -------------------------------- ### urls Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets URLs accessed through/by ZAP, optionally filtered by base URL. Returns a list of full URL strings. ```APIDOC ## urls(baseurl=None) ### Description Gets URLs accessed through/by ZAP, optionally filtered by base URL. ### Method GET (Assumed based on typical API patterns for retrieving data) ### Endpoint /JSON/core/view/urls/ ### Parameters #### Query Parameters - **baseurl** (string) - Optional - Filter results to URLs starting with this base URL ### Response #### Success Response (200) - **urls** (list) - List of full URL strings ### Request Example ```python # All URLs all_urls = zap.core.urls() # Filtered by base URL app_urls = zap.core.urls(baseurl='https://example.com/api') ``` ``` -------------------------------- ### Initialize ZAPv2 Client Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/CLIENT.md Demonstrates different ways to initialize the ZAPv2 client, including simple connections, production setups with API keys, and connections to remote ZAP instances. ```python from zapv2 import ZAPv2 # Simple connection (no API key required in development) zap = ZAPv2() ``` ```python # Production setup with API key zap = ZAPv2(apikey='your-api-key') ``` ```python # Remote ZAP instance zap = ZAPv2(proxies={ 'http': 'http://zap-server.example.com:8080', 'https': 'http://zap-server.example.com:8080' }, apikey='your-api-key') ``` -------------------------------- ### New Session Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Starts a new session in ZAP, optionally overwriting an existing session with the same name. This is crucial for isolating scan results. ```APIDOC ## new_session(name, overwrite) ### Description Starts a new session in ZAP. ### Parameters #### Query Parameters - **name** (string) - Required - The name for the new session. - **overwrite** (boolean) - Optional - Whether to overwrite an existing session with the same name. ### Request Example ```python zap.core.new_session(name='test-scan', overwrite=True) ``` ### Response #### Success Response (200) - **Result** (dict) - Result status dictionary ``` -------------------------------- ### Core View Endpoints Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/API_ENDPOINTS.md Lists read-only view endpoints available in the Core module. These are accessed via GET requests. ```text /core/view/hosts/ /core/view/sites/ /core/view/urls/ /core/view/childNodes/ /core/view/message/{id} /core/view/messages/ /core/view/messagesById/ /core/view/numberOfMessages/ /core/view/mode/ /core/view/version/ /core/view/excludedFromProxy/ /core/view/sessionLocation/ /core/view/zap HomeePath/ /core/view/alerts/ /core/view/alertsSummary/ /core/view/numberOfAlerts/ /core/view/getLogLevel/ /core/view/optionDefaultUserAgent/ /core/view/optionDnsTtlSuccessfulQueries/ /core/view/optionTimeoutInSecs/ ``` -------------------------------- ### Get All URLs Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Retrieves a list of all URLs that ZAP has observed during its operation. This provides a comprehensive view of the target application's structure. ```APIDOC ## urls() ### Description Retrieves a list of all URLs that ZAP has observed during its operation. ### Response #### Success Response (200) - **URLs** (list) - A list of observed URLs ``` -------------------------------- ### Core Action Endpoints Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/API_ENDPOINTS.md Lists action endpoints in the Core module that perform changes. These are accessed via GET requests with parameters. ```text /core/action/accessUrl/?url={url} /core/action/shutdown/ /core/action/newSession/?name={name}&overwrite={bool} /core/action/loadSession/?name={name} /core/action/saveSession/?name={name}&overwrite={bool} /core/action/snapshotSession/?name={name} /core/action/excludeFromProxy/?regex={regex} /core/action/clearExcludedFromProxy/ /core/action/deleteAllAlerts/ /core/action/deleteAlert/?id={id} /core/action/sendRequest/?request={request}&followRedirects={bool} /core/action/setMode/?mode={mode} ``` -------------------------------- ### Get Paginated HTTP Messages Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Retrieves paginated lists of HTTP messages sent by ZAP. Allows filtering by URL prefix and specifying the start index and count for results. ```python # Get first 100 messages messages = zap.core.messages(start=0, count=100) # Get messages for specific domain domain_messages = zap.core.messages(baseurl='https://api.example.com', count=50) ``` -------------------------------- ### Initialize ZAPv2 Instance and Access Modules Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/MODULES.md Instantiate the ZAPv2 client with an API key and access individual modules directly as properties. All 43 modules are available for use. ```python from zapv2 import ZAPv2 zap = ZAPv2(apikey='your-api-key') # Direct property access zap.core # Core module zap.spider # Spider module zap.ascan # Active scan module zap.pscan # Passive scan module zap.alert # Alert module zap.context # Context module # ... all 43 modules available ``` -------------------------------- ### Connect to ZAP Instance Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/INDEX.md Shows how to connect to a local, production (with API key), or remote ZAP instance. ```python from zapv2 import ZAPv2 # Connect to local ZAP instance zap = ZAPv2() # Connect with API key (production) zap = ZAPv2(apikey='your-api-key') # Connect to remote ZAP zap = ZAPv2( proxies={'http': 'http://zap-server:8080', 'https': 'http://zap-server:8080'}, apikey='your-api-key' ) ``` -------------------------------- ### Initialize ZAPv2 Client (Custom Proxy and API Key) Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/CLIENT.md Connect to a ZAP instance with a custom proxy address and provide an API key for authentication. The API key is sent as an 'X-ZAP-API-Key' header. ```python zap = ZAPv2( proxies={'http': 'http://192.168.1.100:8080', 'https': 'http://192.168.1.100:8080'}, apikey='your-api-key-here' ) ``` -------------------------------- ### Initialize ZAPv2 Client Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/USAGE_GUIDE.md Import and initialize the ZAPv2 client, with options for default, API key, remote instance, and strict error validation. ```python from zapv2 import ZAPv2 # Default: localhost:8080 zap = ZAPv2() ``` ```python # With API key zap = ZAPv2(apikey='your-secure-api-key') ``` ```python # Remote ZAP instance zap = ZAPv2( proxies={ 'http': 'http://zap.example.com:8080', 'https': 'http://zap.example.com:8080' }, apikey='your-api-key' ) ``` ```python # Enable strict error validation zap = ZAPv2(apikey='key', validate_status_code=True) ``` -------------------------------- ### Enable/Disable Adding Query Params to GET Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Controls whether query parameters are added to GET requests during active scans. This can affect scan coverage and performance. ```python zap.ascan.set_option_add_query_param(True) ``` -------------------------------- ### Initialize ZAPv2 Client (Default) Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/CLIENT.md Instantiate the ZAPv2 client to connect to a ZAP instance running with default settings (http://127.0.0.1:8080). ```python zap = ZAPv2() ``` -------------------------------- ### Complete Passive Scan Usage Example Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/PSCAN.md This snippet shows how to initialize the ZAP API client, check and configure passive scan settings, manage scanner rules, enable scanning, wait for completion, and retrieve alerts. Ensure you have a ZAP instance running and replace 'your-api-key' with your actual API key. ```python from zapv2 import ZAPv2 import time zap = ZAPv2(apikey='your-api-key') # Check passive scan status print(f"Messages to scan: {zap.pscan.records_to_scan}") print(f"Scanning only in-scope: {zap.pscan.scan_only_in_scope}") # Configure passive scanning zap.pscan.set_scan_only_in_scope(True) zap.pscan.set_max_alerts_per_rule(10) zap.pscan.set_max_body_size_in_bytes(10 * 1024 * 1024) # 10MB # Get available rules scanners = zap.pscan.scanners print(f"\nAvailable passive scan rules: {len(scanners)}") # Disable certain rules zap.pscan.disable_scanners('10010,10011') # Disable cookie-related rules # Re-enable all zap.pscan.enable_all_scanners() # Set specific rule thresholds for scanner in scanners: if 'XSS' in scanner['name']: zap.pscan.set_scanner_alert_threshold(scanner['id'], 'Medium') # Enable passive scanning zap.pscan.set_enabled(True) # Wait for passive scanning to complete print("\nWaiting for passive scan to complete...") while True: pending = zap.pscan.records_to_scan if pending == 0: break print(f" Remaining: {pending}") time.sleep(2) print("Passive scan complete") # Check what's running now current = zap.pscan.current_rule if current: print(f"Current rule: {current}") # Get results via alert module alerts = zap.alert.alerts() print(f"\nTotal alerts found: {len(alerts)}") ``` -------------------------------- ### Accessing Core Properties Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/INDEX.md Demonstrates how to retrieve the ZAP client version and the list of hosts. ```APIDOC ## Accessing Core Properties ### Description Retrieve read-only properties from the ZAP core. ### Method ```python # Get ZAP version version = zap.core.version # Get list of hosts hosts = zap.core.hosts ``` ### Parameters None ``` -------------------------------- ### Infrastructure & Tools Modules Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/MODULES.md Modules for network configuration, Selenium integration, and automatic updates. ```APIDOC ## Infrastructure & Tools ### `network` Module - **Property**: `zap.network` - **Methods**: 48 - **Description**: Manages network configuration. ### `selenium` Module - **Property**: `zap.selenium` - **Methods**: 26 - **Description**: Integrates with Selenium WebDriver. ### `autoupdate` Module - **Property**: `zap.autoupdate` - **Methods**: 32 - **Description**: Handles automatic updates and component management. ### `client` Module - **Property**: `zap.client` - **Methods**: 8 - **Description**: Manages client scanner operations (optional). ``` -------------------------------- ### ZAPv2 Constructor Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/CLIENT.md Initializes the ZAPv2 client, which is the main entry point for interacting with the ZAP API. It can be configured with proxy settings, an API key, and options for status code validation. ```APIDOC ## ZAPv2 Constructor ### Description Initializes the ZAPv2 client, which is the main entry point for interacting with the ZAP API. It can be configured with proxy settings, an API key, and options for status code validation. ### Signature ```python ZAPv2(proxies=None, apikey=None, validate_status_code=False) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | |---|---|---|---| | proxies | dict | No | `{'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}` | | apikey | str | No | None | | validate_status_code | bool | No | False | ### Returns ZAPv2 instance ### Example ```python from zapv2 import ZAPv2 # Connect to default ZAP instance (127.0.0.1:8080) zap = ZAPv2() # Connect with custom proxy and API key zap = ZAPv2( proxies={'http': 'http://192.168.1.100:8080', 'https': 'http://192.168.1.100:8080'}, apikey='your-api-key-here' ) # Enable strict status code validation zap = ZAPv2(apikey='your-api-key', validate_status_code=True) ``` ``` -------------------------------- ### messages_ids(scanid) Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Gets message IDs from an active scan. ```APIDOC ## messages_ids(scanid) ### Description Gets message IDs from an active scan. ### Method `messages_ids` ### Parameters #### Path Parameters None #### Query Parameters - **scanid** (int) - Required - Scan ID ### Returns - **list**: List of message IDs ### Example ```python msg_ids = zap.ascan.messages_ids(scanid=1) for msg_id in msg_ids: print(f"Message ID: {msg_id}") # Retrieve with: zap.core.message(msg_id) ``` ``` -------------------------------- ### set_option_add_query_param Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Enables or disables the addition of query parameters to GET requests. ```APIDOC ## set_option_add_query_param ### Description Enables/disables adding query parameters to GET requests. ### Method ```python def set_option_add_query_param(self, boolean, apikey='') -> dict ``` ### Parameters #### Path Parameters - **boolean** (bool) - Required - Enable or disable - **apikey** (str) - Optional - API key ### Request Example ```python zap.ascan.set_option_add_query_param(True) ``` ### Response #### Success Response (200) - **Result** (dict) - Result status dictionary ``` -------------------------------- ### Access ZAP Modules and Perform Actions Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/CLIENT.md Shows how to access different ZAP modules (e.g., core, ascan, spider, alert) through properties and perform common actions like scanning and status checks. ```python zap = ZAPv2() # Access modules through properties hosts = zap.core.hosts sites = zap.core.sites # Start an active scan zap.ascan.scan('https://target.com') # Check spider status spider_status = zap.spider.status()) # Get all alerts alerts = zap.alert.alerts() ``` -------------------------------- ### alerts_ids(scanid) Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Gets alert IDs raised during an active scan. ```APIDOC ## alerts_ids(scanid) ### Description Gets alert IDs raised during an active scan. ### Method `alerts_ids` ### Parameters #### Path Parameters None #### Query Parameters - **scanid** (int) - Required - Scan ID ### Returns - **list**: List of alert IDs ### Example ```python alert_ids = zap.ascan.alerts_ids(scanid=1) for alert_id in alert_ids: print(f"Alert ID: {alert_id}") # Retrieve with: zap.core.alert(alert_id) ``` ``` -------------------------------- ### Initialize ZAP API Client with API Key and Validation Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/USAGE_GUIDE.md This snippet demonstrates how to initialize the ZAP API client in Python. It loads the API key from an environment variable and enables strict status code validation for error detection. Ensure the ZAP_API_KEY environment variable is set before running. ```python import os from zapv2 import ZAPv2 # Load API key from environment api_key = os.environ.get('ZAP_API_KEY') if not api_key: raise ValueError("ZAP_API_KEY environment variable not set") zap = ZAPv2(apikey=api_key, validate_status_code=True) ``` -------------------------------- ### Create New Session Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Initiates a new ZAP session. Specify a name for the session file; if relative, it's resolved against ZAP's session directory. Overwriting an existing session is optional. ```python result = zap.core.new_session(name='myscan', overwrite=True) print(result) ``` -------------------------------- ### number_of_messages Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets the total count of HTTP messages. Returns the total message count. ```APIDOC ## number_of_messages(baseurl=None) ### Description Gets the total count of HTTP messages. ### Method GET (Assumed based on typical API patterns for retrieving data) ### Endpoint /JSON/core/view/numberOfMessages/ ### Parameters #### Query Parameters - **baseurl** (string) - Optional - Filter by URL prefix ### Response #### Success Response (200) - **numberOfMessages** (integer) - Total message count ### Request Example ```python total = zap.core.number_of_messages() print(f"Total messages: {total}") domain_count = zap.core.number_of_messages(baseurl='https://example.com') ``` ``` -------------------------------- ### option_timeout_in_secs Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets the connection timeout in seconds. This is a property that returns the timeout in seconds as an integer. ```APIDOC ## option_timeout_in_secs ### Description Gets the connection timeout in seconds. ### Method GET ### Endpoint /JSON/core/view/optionTimeoutInSecs/ ### Parameters None ### Response #### Success Response (200) - **optionTimeoutInSecs** (integer) - Timeout in seconds ### Request Example ```python timeout = zap.core.option_timeout_in_secs print(f"Timeout: {timeout}s") ``` ### Response Example ```json { "optionTimeoutInSecs": 30 } ``` ``` -------------------------------- ### messages Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets paginated HTTP messages sent by ZAP. Returns a list of message dictionaries. ```APIDOC ## messages(baseurl=None, start=None, count=None) ### Description Gets paginated HTTP messages sent by ZAP. ### Method GET (Assumed based on typical API patterns for retrieving data) ### Endpoint /JSON/core/view/messages/ ### Parameters #### Query Parameters - **baseurl** (string) - Optional - Filter by URL prefix - **start** (integer) - Optional - Starting message index (0-based) - **count** (integer) - Optional - Number of messages to return ### Response #### Success Response (200) - **messages** (list) - List of message dictionaries ### Request Example ```python # Get first 100 messages messages = zap.core.messages(start=0, count=100) # Get messages for specific domain domain_messages = zap.core.messages(baseurl='https://api.example.com', count=50) ``` ``` -------------------------------- ### message Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets an HTTP message by ID with full request/response details. Returns a message object. ```APIDOC ## message(id) ### Description Gets an HTTP message by ID with full request/response details. ### Method GET (Assumed based on typical API patterns for retrieving data) ### Endpoint /JSON/core/view/message/ ### Parameters #### Query Parameters - **id** (integer) - Required - Message ID ### Response #### Success Response (200) - **message** (dict) - Message object with id, request headers, response headers, request body, response body, cookies, note, type, RTT, timestamp ### Request Example ```python msg = zap.core.message(123) print(f"Request: {msg['requestHeader']}") print(f"Response: {msg['responseHeader']}") print(f"Response Body: {msg['responseBody']}") ``` ``` -------------------------------- ### Tag and Push New Version Source: https://github.com/zaproxy/zap-api-python/blob/main/RELEASING.md Tag the new version locally and push the tag to the upstream repository. This action triggers the PyPI release workflow. ```bash git tag -s 0.0.X -m "Version 0.x.0" git push upstream 0.x.0 ``` -------------------------------- ### option_default_user_agent Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets the HTTP User-Agent header used by ZAP. This is a property that returns the User-Agent string. ```APIDOC ## option_default_user_agent ### Description Gets the HTTP User-Agent header used by ZAP. ### Method GET ### Endpoint /JSON/core/view/optionDefaultUserAgent/ ### Parameters None ### Response #### Success Response (200) - **optionDefaultUserAgent** (string) - User-Agent string ### Request Example ```python agent = zap.core.option_default_user_agent print(f"User-Agent: {agent}") ``` ### Response Example ```json { "optionDefaultUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0" } ``` ``` -------------------------------- ### mode Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets the current ZAP operating mode. This is a property that returns the current mode as a string. ```APIDOC ## mode ### Description Gets the current ZAP operating mode. ### Method GET ### Endpoint /JSON/core/view/mode/ ### Parameters None ### Response #### Success Response (200) - **mode** (string) - One of: `'safe'`, `'protect'`, `'standard'`, `'attack'` ### Request Example ```python current_mode = zap.core.mode print(current_mode) ``` ### Response Example ```json { "mode": "standard" } ``` ``` -------------------------------- ### Generate Add-on API Files Source: https://github.com/zaproxy/zap-api-python/blob/main/CONTRIBUTING.md Regenerates API files for add-ons from the zap-extensions repository. This command should be run from the 'zap-extensions' directory after pulling the latest 'main' branch. ```bash cd zap-extensions git pull upstream main ./gradle generatePythonZapApiClientFiles --continue cd .. ``` -------------------------------- ### Get ZAP Version Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Retrieves the current version of ZAP. Useful for compatibility checks or reporting. ```python version = zap.core.version print(f"ZAP Version: {version}") ``` -------------------------------- ### Basic ZAP API Python Usage Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/README.md Connect to ZAP, spider a website, run an active scan, and retrieve alerts. Ensure you have an API key configured in ZAP. ```python from zapv2 import ZAPv2 # Connect to ZAP zap = ZAPv2(apikey='your-api-key') # Spider a website spider_id = zap.spider.scan('https://example.com') # Run active scan ascan_id = zap.ascan.scan('https://example.com') # Get alerts alerts = zap.alert.alerts(riskid=3) # High-risk only ``` -------------------------------- ### policies(scanpolicyname=None, policyid=None) Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/ASCAN.md Gets policy information. Can filter by policy name or policy ID. ```APIDOC ## policies(scanpolicyname=None, policyid=None) ### Description Gets policy information. ### Method `policies` ### Parameters #### Path Parameters None #### Query Parameters - **scanpolicyname** (str) - Optional - Policy name - **policyid** (int) - Optional - Policy ID ### Returns - **list**: Policy information list ### Example ```python policies = zap.ascan.policies() ``` ``` -------------------------------- ### Full Security Assessment with ZAP API Python Client Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/README.md This script demonstrates a complete security assessment workflow using the ZAP API Python client. It includes session creation, spidering, active scanning, retrieving alert summaries, and generating an HTML report. Ensure you have the ZAP API running and replace 'api-key' with your actual API key and 'https://target.com' with the target URL. ```python from zapv2 import ZAPv2 import time zap = ZAPv2(apikey='api-key') # Create session zap.core.new_session(name='assessment', overwrite=True) # Spider the target spider_id = zap.spider.scan('https://target.com') while zap.spider.status(scanid=spider_id) < 100: time.sleep(2) # Active scan ascan_id = zap.ascan.scan('https://target.com') while zap.ascan.status(scanid=ascan_id) < 100: time.sleep(5) # Get results summary = zap.alert.alerts_summary() alerts = zap.alert.alerts(riskid=3) # Generate report html = zap.core.htmlreport() with open('report.html', 'w') as f: f.write(html) print(f"Assessment complete. High-risk: {summary['High']}") ``` -------------------------------- ### full_results Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/SPIDER.md Gets complete results from a spider scan with detailed information. Requires a scan ID. ```APIDOC ## full_results(scanid) ### Description Gets complete results from a spider scan with detailed information. ### Method Not applicable (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **scanid** (int) - Required - Scan ID ### Returns Detailed results dictionary ### Example ```python details = zap.spider.full_results(scanid=1) print(details) ``` ``` -------------------------------- ### Configuration & Control Modules Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/MODULES.md Modules for configuring contexts, managing breakpoints, and controlling scan rules. ```APIDOC ## Configuration & Control ### `context` Module - **Property**: `zap.context` - **Methods**: 21 - **Description**: Manages contexts and scope definitions. ### `brk` Module - **Property**: `zap.brk` - **Methods**: 11 - **Description**: Controls HTTP breakpoints and request interception. ### `params` Module - **Property**: `zap.params` - **Methods**: 1 - **Description**: Assists with parameter discovery. ### `script` Module - **Property**: `zap.script` - **Methods**: 24 - **Description**: Manages the script engine and scripts. ### `ruleConfig` Module - **Property**: `zap.ruleConfig` - **Methods**: 5 - **Description**: Configures scan rules. ``` -------------------------------- ### option_max_duration Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/SPIDER.md Gets the maximum duration, in seconds, for a spider scan. This limits how long a scan can run. ```APIDOC ## option_max_duration ### Description Gets the maximum scan duration. ### Method GET ### Endpoint /JSON/spider/view/optionMaxDuration/ ### Parameters None ### Response #### Success Response (200) - **optionMaxDuration** (int) - Maximum duration value ### Response Example ```json { "optionMaxDuration": "3600" } ``` ``` -------------------------------- ### Proxy Configuration Actions Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Manage URL exclusions for the local proxy. ```APIDOC ## exclude_from_proxy(regex) ### Description Adds a regex pattern for URLs to exclude from local proxy. ### Method `exclude_from_proxy` ### Parameters #### Path Parameters - **regex** (str) - Required - Regex pattern for URLs to exclude ### Request Example ```python zap.core.exclude_from_proxy(r'.*\.internal\.example\.com') ``` ### Response - Result status dictionary ``` ```APIDOC ## clear_excluded_from_proxy() ### Description Clears all proxy exclusion patterns. ### Method `clear_excluded_from_proxy` ### Request Example ```python zap.core.clear_excluded_from_proxy() ``` ### Response - Result status dictionary ``` -------------------------------- ### alerts Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets alerts raised by ZAP, optionally filtered and paginated. Returns a list of alert dictionaries. ```APIDOC ## alerts(baseurl=None, start=None, count=None, riskid=None) ### Description Gets alerts raised by ZAP, optionally filtered and paginated. ### Method GET (Assumed based on typical API patterns for retrieving data) ### Endpoint /JSON/core/view/alerts/ ### Parameters #### Query Parameters - **baseurl** (string) - Optional - Filter by URL - **start** (integer) - Optional - Starting index - **count** (integer) - Optional - Maximum alerts to return - **riskid** (integer) - Optional - Filter by risk level (0=info, 1=low, 2=medium, 3=high) ### Response #### Success Response (200) - **alerts** (list) - List of alert dictionaries ### Request Example ```python # All alerts all_alerts = zap.core.alerts() # High-risk alerts only high_risk = zap.core.alerts(riskid=3) # Paginated results page_1 = zap.core.alerts(start=0, count=50) page_2 = zap.core.alerts(start=50, count=50) ``` ``` -------------------------------- ### child_nodes Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets the child nodes under a URL in the Sites tree. Returns a dictionary with child node structure. ```APIDOC ## child_nodes(url=None) ### Description Gets the child nodes under a URL in the Sites tree. ### Method GET (Assumed based on typical API patterns for retrieving data) ### Endpoint /JSON/core/view/childNodes/ ### Parameters #### Query Parameters - **url** (string) - Optional - Parent URL to get children for ### Response #### Success Response (200) - **childNodes** (dict) - Dictionary with child node structure ### Request Example ```python children = zap.core.child_nodes(url='https://example.com/') print(children) ``` ``` -------------------------------- ### session_location Source: https://github.com/zaproxy/zap-api-python/blob/main/_autodocs/api-reference/CORE.md Gets the current session file path. This is a property that returns the absolute file path to the session. ```APIDOC ## session_location ### Description Gets the current session file path. ### Method GET ### Endpoint /JSON/core/view/sessionLocation/ ### Parameters None ### Response #### Success Response (200) - **sessionLocation** (string) - Absolute file path to session ### Request Example ```python session_path = zap.core.session_location print(f"Session: {session_path}") ``` ### Response Example ```json { "sessionLocation": "/home/user/.ZAP/sessions/default.session" } ``` ```