### Generate Security Reports with ZAP API Source: https://context7.com/zaproxy/zap-api-java/llms.txt Demonstrates how to generate formatted security reports (e.g., HTML, XML) using ZAP's Reports add-on. Requires the Reports add-on to be installed. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // List available report templates System.out.println(api.reports.templates().toString(0)); // Generate an HTML report String reportPath = ((ApiResponseElement) api.reports.generate( "Security Scan Report", // title "traditional-html", // template name null, // theme (null = default) "Automated scan of MyApp", // description "MyApp", // contexts (comma-separated) null, // sites filter null, // sections "Low,Medium,High,Confirmed",// includedConfidences "Low,Medium,High", // includedRisks "scan-report", // reportFileName (no extension) null, // reportFileNamePattern "/tmp/zap-reports", // reportDir null // display )).getValue(); System.out.println("Report saved to: " + reportPath); // Generate XML report directly via core byte[] xmlBytes = api.core.xmlreport(); java.nio.file.Files.write(java.nio.file.Paths.get("/tmp/zap-report.xml"), xmlBytes); ``` -------------------------------- ### Launch and Monitor AJAX Spider Scan Source: https://context7.com/zaproxy/zap-api-java/llms.txt Starts an AJAX spider scan for JavaScript-heavy applications using a browser. Polls for the scan status until it's no longer running. Requires Selenium to be configured. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String target = "http://spa.example.com/"; // Start AJAX spider (url, inScope, contextName, subtreeOnly) api.ajaxSpider.scan(target, null, null, null); // Poll until stopped String status; do { Thread.sleep(2000); status = ((ApiResponseElement) api.ajaxSpider.status()).getValue(); System.out.println("AJAX Spider status: " + status); } while ("running".equalsIgnoreCase(status)); System.out.println("AJAX Spider complete"); ``` -------------------------------- ### Start and Monitor Traditional Spider Scan Source: https://context7.com/zaproxy/zap-api-java/llms.txt Initiates a traditional link-following spider crawl on a target URL. Returns a scan ID for progress tracking. Ensure the target URL is correctly formatted. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String target = "http://testapp.example.com/"; // Start spider scan (url, maxChildren, recurse, contextName, subtreeOnly) String scanId = ((ApiResponseElement) api.spider.scan(target, null, null, null, null)).getValue(); // Poll until complete int progress; do { Thread.sleep(1000); progress = Integer.parseInt(((ApiResponseElement) api.spider.status(scanId)).getValue()); System.out.printf("Spider progress: %d%%%n", progress); } while (progress < 100); // Retrieve discovered URLs System.out.println("Discovered URLs: " + api.spider.results(scanId).toString(0)); ``` -------------------------------- ### Manage ZAP Sessions and Proxy Settings Source: https://context7.com/zaproxy/zap-api-java/llms.txt Covers core ZAP operations including getting the ZAP version, listing sites, accessing URLs, inspecting messages, saving/loading sessions, excluding URLs from the proxy, and setting the operating mode. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Get ZAP version System.out.println("ZAP: " + ((ApiResponseElement) api.core.version()).getValue()); // List all sites captured System.out.println(api.core.sites().toString(0)); // Access a URL through ZAP (add it to the Sites tree) api.accessUrl("http://testapp.example.com/api/health"); // Inspect a captured HTTP message by ID System.out.println(api.core.message("42").toString(0)); // Save and load sessions api.core.saveSession("/tmp/mysession", "true"); api.core.loadSession("/tmp/mysession"); // Exclude a URL pattern from the proxy api.core.excludeFromProxy(".*\.png"); // Set ZAP operating mode (safe, protect, standard, attack) api.core.setMode("standard"); ``` -------------------------------- ### Retrieve and Filter Security Alerts Source: https://context7.com/zaproxy/zap-api-java/llms.txt Fetches security alerts generated by ZAP scans. Alerts can be retrieved in a typed `Alert` object list, filtered by URL, risk level, and pagination. Also shows how to get a summary of alerts by risk level. ```java import java.util.List; import org.zaproxy.clientapi.core.Alert; import org.zaproxy.clientapi.core.ApiResponseList; import org.zaproxy.clientapi.core.ApiResponseSet; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Get all alerts (high-level, returns typed Alert objects) List alerts = api.getAlerts(null, -1, -1); for (Alert alert : alerts) { System.out.printf("[%s] %s at %s (param: %s)%n", alert.getRisk(), alert.getName(), alert.getUrl(), alert.getParam()); } // Get alerts filtered by base URL and paginated List filteredAlerts = api.getAlerts("http://testapp.example.com/", 0, 50); // Get count of alerts by risk level ApiResponseList summary = (ApiResponseList) api.alert.alertsSummary(null); System.out.println("Alert summary: " + summary.toString(0)); // Output: High: 2, Medium: 5, Low: 12, Informational: 3 ``` -------------------------------- ### ClientApi - Constructing the API Client Source: https://context7.com/zaproxy/zap-api-java/llms.txt Demonstrates how to instantiate the ClientApi class to connect to a ZAP instance, with and without an API key, and how to wait for ZAP to become ready. ```APIDOC ## ClientApi — Constructing the API Client The entry point to the library. Connects to a running ZAP instance and optionally authenticates with an API key sent via the `X-ZAP-API-Key` header on every request. ```java import org.zaproxy.clientapi.core.ClientApi; import org.zaproxy.clientapi.core.ClientApiException; // No API key (ZAP configured with no key) ClientApi api = new ClientApi("localhost", 8090); // With API key ClientApi api = new ClientApi("localhost", 8090, "my-secret-api-key"); // With API key and debug output to stdout ClientApi api = new ClientApi("localhost", 8090, "my-secret-api-key", true); // Wait for ZAP to be ready (e.g., after launching ZAP programmatically) try { api.waitForSuccessfulConnectionToZap(30); // wait up to 30 seconds System.out.println("ZAP is ready"); } catch (ClientApiException e) { System.err.println("ZAP did not start in time: " + e.getMessage()); } ``` ``` -------------------------------- ### Constructing the ClientApi Instance Source: https://context7.com/zaproxy/zap-api-java/llms.txt Initialize the ClientApi to connect to a running ZAP instance. Supports connections with or without an API key, and optionally enables debug output. Includes a method to wait for ZAP to become ready. ```java import org.zaproxy.clientapi.core.ClientApi; import org.zaproxy.clientapi.core.ClientApiException; // No API key (ZAP configured with no key) ClientApi api = new ClientApi("localhost", 8090); // With API key ClientApi api = new ClientApi("localhost", 8090, "my-secret-api-key"); // With API key and debug output to stdout ClientApi api = new ClientApi("localhost", 8090, "my-secret-api-key", true); // Wait for ZAP to be ready (e.g., after launching ZAP programmatically) try { api.waitForSuccessfulConnectionToZap(30); // wait up to 30 seconds System.out.println("ZAP is ready"); } catch (ClientApiException e) { System.err.println("ZAP did not start in time: " + e.getMessage()); } ``` -------------------------------- ### Build Release Artifacts Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Clean the project and build the necessary artifacts and libraries for the release using Gradle. ```bash ./gradlew clean build ``` -------------------------------- ### Import API Definitions into ZAP Source: https://context7.com/zaproxy/zap-api-java/llms.txt Shows how to import API definitions (OpenAPI, GraphQL, Postman) into ZAP to populate the Sites tree for scanning. This is typically followed by initiating a scan. ```java import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Import OpenAPI definition from URL api.openapi.importUrl("http://testapp.example.com/v3/api-docs", null); // Import OpenAPI from a local file api.openapi.importFile("/tmp/openapi.yaml", "http://testapp.example.com", null); // Import GraphQL schema from URL api.graphql.importUrl("http://testapp.example.com/graphql", null); // Import Postman collection from file api.postman.importFile("/tmp/myapp.postman_collection.json", null); // After import, the Sites tree is populated — start scanning api.ascan.scan("http://testapp.example.com/", "True", "False", null, null, null); ``` -------------------------------- ### Checkout Tagged Version Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Checkout the specific tagged version from which to build the release artifacts. ```bash git checkout v ``` -------------------------------- ### Publish to Maven Central Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Upload the built artifacts to OSSRH (Online Repository for Snapshot and Release Artifacts) using Gradle. ```bash ./gradlew publish ``` -------------------------------- ### Merge Release Branch to Master Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Checkout master and merge the release branch, then tag the new version. ```bash git checkout master git merge -S --no-ff release- -m "Merge branch 'release-' into master" ``` ```bash git tag -s v -m "Version " ``` -------------------------------- ### Reintegrate Release Branch to Develop Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Checkout develop and merge the release branch back, resolving conflicts and bumping to the next developing version. ```bash git checkout develop git merge -S --no-ff release- -m "Merge branch 'release-' into develop" ``` ```bash git commit -S -m "Bump version number to -SNAPSHOT" ``` -------------------------------- ### ClientApi.callApi - Low-Level Raw API Call Source: https://context7.com/zaproxy/zap-api-java/llms.txt Shows how to make generic XML API calls to any ZAP component and action/view, including how to pass parameters and handle responses. ```APIDOC ## ClientApi.callApi — Low-Level Raw API Call Sends a generic XML API call to any ZAP component/action/view. Useful for components or endpoints not yet covered by a typed wrapper. ```java import java.util.HashMap; import java.util.Map; import org.zaproxy.clientapi.core.ApiResponse; import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Call the core/view/version endpoint ApiResponse resp = api.callApi("core", "view", "version", null); System.out.println("ZAP version: " + ((ApiResponseElement) resp).getValue()); // Call an action with parameters Map params = new HashMap<>(); params.put("url", "http://example.com"); params.put("recurse", "true"); ApiResponse scanResp = api.callApi("spider", "action", "scan", params); String scanId = ((ApiResponseElement) scanResp).getValue(); System.out.println("Started spider scan ID: " + scanId); ``` ``` -------------------------------- ### Push Branches and Tag Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Push the updated develop and master branches, along with the new tag, to the remote repository. ```bash git push upstream develop master v ``` -------------------------------- ### Manage Scan Contexts with ZAP API Client Source: https://context7.com/zaproxy/zap-api-java/llms.txt Creates and configures scan contexts to scope ZAP's activity. Includes operations for creating contexts, including/excluding URL patterns, and listing contexts. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Create a new context String contextId = ((ApiResponseElement) api.context.newContext("MyApp")).getValue(); // Include URL patterns in scope api.context.includeInContext("MyApp", "http://testapp\.example\.com.*", null); // Exclude specific paths api.context.excludeFromContext("MyApp", "http://testapp\.example\.com/logout.*", null); api.context.excludeFromContext("MyApp", "http://testapp\.example\.com/static/.*", null); // List all context names System.out.println("Contexts: " + api.context.contextList().toString(0)); // Scope spider scan to context api.spider.scan(null, null, null, "MyApp", null); ``` -------------------------------- ### GitHub Release Draft Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Draft a new release on GitHub, including the tag, title, and a summary of changes. ```markdown - Tag: `v` - Title: `Version ` - Description: (Add a summary of the changes done in the new version and mention the artifacts/libraries available.) ``` -------------------------------- ### ApiResponse — Parsing Typed Responses Source: https://context7.com/zaproxy/zap-api-java/llms.txt Demonstrates how to parse different types of API responses: scalar values, lists, and key-value sets. ```APIDOC ## ApiResponse — Parsing Typed Responses All API calls return `ApiResponse` subclasses. Use `ApiResponseElement` for scalar values, `ApiResponseList` for arrays, and `ApiResponseSet` for key-value objects. ```java import java.util.List; import org.zaproxy.clientapi.core.*; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // ApiResponseElement — single scalar value ApiResponseElement elem = (ApiResponseElement) api.core.version(); String version = elem.getValue(); // e.g. "2.15.0" // ApiResponseList — list of items ApiResponseList sitesList = (ApiResponseList) api.core.sites(); for (ApiResponse item : sitesList.getItems()) { System.out.println("Site: " + ((ApiResponseElement) item).getValue()); } // ApiResponseSet — named key-value map (e.g., a single alert) ApiResponseList alertList = (ApiResponseList) api.alert.alerts(null, null, null, null); for (ApiResponse item : alertList.getItems()) { ApiResponseSet alertSet = (ApiResponseSet) item; System.out.printf("Alert: %s | Risk: %s | URL: %s%n", alertSet.getStringValue("name"), alertSet.getStringValue("risk"), alertSet.getStringValue("url")); } ``` ``` -------------------------------- ### context Source: https://context7.com/zaproxy/zap-api-java/llms.txt Creates and configures scan contexts to scope ZAP's activity to specific URL patterns. ```APIDOC ## context — Scan Context Management Creates and configures scan contexts to scope ZAP's activity to specific URL patterns. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Create a new context String contextId = ((ApiResponseElement) api.context.newContext("MyApp")).getValue(); // Include URL patterns in scope api.context.includeInContext("MyApp", "http://testapp\\.example\\.com.*"); // Exclude specific paths api.context.excludeFromContext("MyApp", "http://testapp\\.example\\.com/logout.*"); api.context.excludeFromContext("MyApp", "http://testapp\\.example\\.com/static/.*"); // List all context names System.out.println("Contexts: " + api.context.contextList().toString(0)); // Scope spider scan to context api.spider.scan(null, null, null, "MyApp", null); ``` ``` -------------------------------- ### Full End-to-End Scan with ZAP Java API Source: https://context7.com/zaproxy/zap-api-java/llms.txt Demonstrates a complete automated scan workflow including spider, passive scan, active scan, and alert verification. Ensure ZAP is running and accessible before execution. ```java import java.nio.charset.StandardCharsets; import java.util.Collections; import org.zaproxy.clientapi.core.*; public class FullScanExample { public static void main(String[] args) throws Exception { String target = "http://testapp.example.com/"; ClientApi api = new ClientApi("localhost", 8090, "my-api-key"); // Wait for ZAP to be ready api.waitForSuccessfulConnectionToZap(60); // 1. Spider String spiderScanId = ((ApiResponseElement) api.spider.scan(target, null, null, null, null)).getValue(); int spiderProgress; do { Thread.sleep(1000); spiderProgress = Integer.parseInt( ((ApiResponseElement) api.spider.status(spiderScanId)).getValue()); } while (spiderProgress < 100); System.out.println("Spider done"); // 2. Wait for passive scan int recordsLeft; do { Thread.sleep(1000); recordsLeft = Integer.parseInt( ((ApiResponseElement) api.pscan.recordsToScan()).getValue()); } while (recordsLeft > 0); System.out.println("Passive scan done"); // 3. Active scan String ascanId = ((ApiResponseElement) api.ascan.scan(target, "True", "False", null, null, null)).getValue(); int ascanProgress; do { Thread.sleep(5000); ascanProgress = Integer.parseInt( ((ApiResponseElement) api.ascan.status(ascanId)).getValue()); } while (ascanProgress < 100); System.out.println("Active scan done"); // 4. Report alerts — fail build if any High risk alerts remain Alert ignoreInfoDisclosure = new Alert( "X-Powered-By Header Information Leak", null, Alert.Risk.Low, Alert.Confidence.Medium); api.checkAlerts( Collections.singletonList(ignoreInfoDisclosure), Collections.emptyList() ); // 5. Save XML report byte[] report = api.core.xmlreport(); System.out.println(new String(report, StandardCharsets.UTF_8)); } } ``` -------------------------------- ### Create Release Branch Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Create a new release branch from the develop branch following git-flow. ```bash git checkout -b release- develop ``` -------------------------------- ### openapi / graphql / postman — API Definition Import Source: https://context7.com/zaproxy/zap-api-java/llms.txt Imports API definitions from OpenAPI (Swagger), GraphQL schema, or Postman collections to automatically populate the Sites tree for scanning. ```APIDOC ## openapi / graphql / postman — API Definition Import Imports OpenAPI (Swagger), GraphQL schema, or Postman collections to automatically populate the Sites tree for scanning. ```java import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Import OpenAPI definition from URL api.openapi.importUrl("http://testapp.example.com/v3/api-docs", null); // Import OpenAPI from a local file api.openapi.importFile("/tmp/openapi.yaml", "http://testapp.example.com", null); // Import GraphQL schema from URL api.graphql.importUrl("http://testapp.example.com/graphql", null); // Import Postman collection from file api.postman.importFile("/tmp/myapp.postman_collection.json", null); // After import, the Sites tree is populated — start scanning api.ascan.scan("http://testapp.example.com/", "True", "False", null, null, null); ``` ``` -------------------------------- ### Configure Form-Based Authentication with ZAP API Client Source: https://context7.com/zaproxy/zap-api-java/llms.txt Sets up form-based authentication for a ZAP scan context, including defining login URLs, request bodies, logged-in indicators, user credentials, and enabling forced user mode. ```java import java.net.URLEncoder; import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String contextId = "1"; // existing context ID // Configure form-based authentication String loginUrl = "http://testapp.example.com/login"; String loginBody = "username={%username%}&password={%password%}"; String authConfig = "loginUrl=" + URLEncoder.encode(loginUrl, "UTF-8") + "&loginRequestData=" + URLEncoder.encode(loginBody, "UTF-8"); api.authentication.setAuthenticationMethod(contextId, "formBasedAuthentication", authConfig); // Set logged-in indicator (regex matching something present only when logged in) api.authentication.setLoggedInIndicator(contextId, "\Qwelcome, testuser\E"); // Create a user and set credentials String userId = ((ApiResponseElement) api.users.newUser(contextId, "TestUser")).getValue(); String userCreds = "username=" + URLEncoder.encode("testuser@example.com", "UTF-8") + "&password=" + URLEncoder.encode("s3cr3tP@ss", "UTF-8"); api.users.setAuthenticationCredentials(contextId, userId, userCreds); api.users.setUserEnabled(contextId, userId, "true"); // Enable forced user mode to scan as this user api.forcedUser.setForcedUser(contextId, userId); api.forcedUser.setForcedUserModeEnabled(true); ``` -------------------------------- ### authentication + users Source: https://context7.com/zaproxy/zap-api-java/llms.txt Configures a ZAP scan context to authenticate via HTML form login, enabling authenticated scanning. ```APIDOC ## authentication + users — Form-Based Authentication Setup Configures a ZAP scan context to authenticate via HTML form login, enabling authenticated scanning. ```java import java.net.URLEncoder; import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String contextId = "1"; // existing context ID // Configure form-based authentication String loginUrl = "http://testapp.example.com/login"; String loginBody = "username={%username%}&password={%password%}"; String authConfig = "loginUrl=" + URLEncoder.encode(loginUrl, "UTF-8") + "&loginRequestData=" + URLEncoder.encode(loginBody, "UTF-8"); api.authentication.setAuthenticationMethod(contextId, "formBasedAuthentication", authConfig); // Set logged-in indicator (regex matching something present only when logged in) api.authentication.setLoggedInIndicator(contextId, "\\Qwelcome, testuser\\E"); // Create a user and set credentials String userId = ((ApiResponseElement) api.users.newUser(contextId, "TestUser")).getValue(); String userCreds = "username=" + URLEncoder.encode("testuser@example.com", "UTF-8") + "&password=" + URLEncoder.encode("s3cr3tP@ss", "UTF-8"); api.users.setAuthenticationCredentials(contextId, userId, userCreds); api.users.setUserEnabled(contextId, userId, "true"); // Enable forced user mode to scan as this user api.forcedUser.setForcedUser(contextId, userId); api.forcedUser.setForcedUserModeEnabled(true); ``` ``` -------------------------------- ### alert / ClientApi.getAlerts Source: https://context7.com/zaproxy/zap-api-java/llms.txt Fetches alerts raised during scanning, filterable by URL, risk level, and pagination. ```APIDOC ## alert / ClientApi.getAlerts — Retrieving Security Alerts Fetches alerts raised during scanning, filterable by URL, risk level, and pagination. ```java import java.util.List; import org.zaproxy.clientapi.core.Alert; import org.zaproxy.clientapi.core.ApiResponseList; import org.zaproxy.clientapi.core.ApiResponseSet; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Get all alerts (high-level, returns typed Alert objects) List alerts = api.getAlerts(null, -1, -1); for (Alert alert : alerts) { System.out.printf("[%s] %s at %s (param: %s)%n", alert.getRisk(), alert.getName(), alert.getUrl(), alert.getParam()); } // Get alerts filtered by base URL and paginated List filteredAlerts = api.getAlerts("http://testapp.example.com/", 0, 50); // Get count of alerts by risk level ApiResponseList summary = (ApiResponseList) api.alert.alertsSummary(null); System.out.println("Alert summary: " + summary.toString(0)); // Output: High: 2, Medium: 5, Low: 12, Informational: 3 ``` ``` -------------------------------- ### ClientApi.callApiJson - JSON Response API Call Source: https://context7.com/zaproxy/zap-api-java/llms.txt Explains how to use `callApiJson` to send an API call and receive the raw JSON string response, available since version 1.16.0. ```APIDOC ## ClientApi.callApiJson — JSON Response API Call Sends an API call and returns the raw JSON string response, available since version 1.16.0. ```java import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Get all alerts as JSON String json = api.callApiJson("alert", "view", "alerts", null); System.out.println(json); // Output: {"alerts":[{"sourceid":"3","other":"","method":"GET","evidence":"...","pluginId":"...","cweid":"...","confidence":"Medium","wascid":"...","description":"...","messageId":"...","url":"http://example.com/","reference":"...","solution":"...","alert":"...","param":"","attack":"","name":"...","risk":"Low","id":"1"},...]} ``` ``` -------------------------------- ### Making Low-Level Raw API Calls Source: https://context7.com/zaproxy/zap-api-java/llms.txt Use callApi for generic XML API calls to any ZAP component or endpoint, especially useful for undocumented features. Parameters can be passed as a Map. The response must be cast to extract values. ```java import java.util.HashMap; import java.util.Map; import org.zaproxy.clientapi.core.ApiResponse; import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Call the core/view/version endpoint ApiResponse resp = api.callApi("core", "view", "version", null); System.out.println("ZAP version: " + ((ApiResponseElement) resp).getValue()); // Call an action with parameters Map params = new HashMap<>(); params.put("url", "http://example.com"); params.put("recurse", "true"); ApiResponse scanResp = api.callApi("spider", "action", "scan", params); String scanId = ((ApiResponseElement) scanResp).getValue(); System.out.println("Started spider scan ID: " + scanId); ``` -------------------------------- ### core — Session and Proxy Management Source: https://context7.com/zaproxy/zap-api-java/llms.txt Provides core ZAP operations including URL history, HTTP message inspection, session control, and proxy configuration. ```APIDOC ## core — Session and Proxy Management Provides core ZAP operations: URL history, HTTP message inspection, session control, and proxy configuration. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Get ZAP version System.out.println("ZAP: " + ((ApiResponseElement) api.core.version()).getValue()); // List all sites captured System.out.println(api.core.sites().toString(0)); // Access a URL through ZAP (add it to the Sites tree) api.accessUrl("http://testapp.example.com/api/health"); // Inspect a captured HTTP message by ID System.out.println(api.core.message("42").toString(0)); // Save and load sessions api.core.saveSession("/tmp/mysession", "true"); api.core.loadSession("/tmp/mysession"); // Exclude a URL pattern from the proxy api.core.excludeFromProxy(".*\.png"); // Set ZAP operating mode (safe, protect, standard, attack) api.core.setMode("standard"); ``` ``` -------------------------------- ### Parse ZAP API Responses in Java Source: https://context7.com/zaproxy/zap-api-java/llms.txt Explains how to handle different types of API responses from ZAP using `ApiResponse` subclasses: `ApiResponseElement` for scalar values, `ApiResponseList` for arrays, and `ApiResponseSet` for key-value maps. ```java import java.util.List; import org.zaproxy.clientapi.core.*; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // ApiResponseElement — single scalar value ApiResponseElement elem = (ApiResponseElement) api.core.version(); String version = elem.getValue(); // e.g. "2.15.0" // ApiResponseList — list of items ApiResponseList sitesList = (ApiResponseList) api.core.sites(); for (ApiResponse item : sitesList.getItems()) { System.out.println("Site: " + ((ApiResponseElement) item).getValue()); } // ApiResponseSet — named key-value map (e.g., a single alert) ApiResponseList alertList = (ApiResponseList) api.alert.alerts(null, null, null, null); for (ApiResponse item : alertList.getItems()) { ApiResponseSet alertSet = (ApiResponseSet) item; System.out.printf("Alert: %s | Risk: %s | URL: %s%n", alertSet.getStringValue("name"), alertSet.getStringValue("risk"), alertSet.getStringValue("url")); } ``` -------------------------------- ### Check Alerts with ZAP API Client Source: https://context7.com/zaproxy/zap-api-java/llms.txt Verifies that required alerts are present and no unexpected alerts remain. Throws an exception if conditions are not met. Can also write results to a file. ```java import java.util.Arrays; import java.util.Collections; import org.zaproxy.clientapi.core.Alert; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Alerts to ignore (known false positives) Alert ignoreXPoweredBy = new Alert("X-Powered-By Header Information Leak", null, Alert.Risk.Low, Alert.Confidence.Medium); // Alerts that MUST be present (expected findings) Alert requireSqlInjection = new Alert("SQL Injection", "http://testapp.example.com/search", Alert.Risk.High, Alert.Confidence.Medium); // Throws ClientApiException if unexpected alerts remain or required alerts not found api.checkAlerts( Arrays.asList(ignoreXPoweredBy), Collections.singletonList(requireSqlInjection) ); // Alternatively, write results to file and throw on failure java.io.File outputFile = new java.io.File("/tmp/alert-results.xml"); api.checkAlerts( Arrays.asList(ignoreXPoweredBy), Collections.singletonList(requireSqlInjection), outputFile ); ``` -------------------------------- ### ajaxSpider.scan Source: https://context7.com/zaproxy/zap-api-java/llms.txt Launches the AJAX spider, which uses a browser (Selenium) to crawl JavaScript-rendered content. ```APIDOC ## ajaxSpider.scan — AJAX Spider for JavaScript-Heavy Apps Launches the AJAX spider, which uses a browser (Selenium) to crawl JavaScript-rendered content. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String target = "http://spa.example.com/"; // Start AJAX spider (url, inScope, contextName, subtreeOnly) api.ajaxSpider.scan(target, null, null, null); // Poll until stopped String status; do { Thread.sleep(2000); status = ((ApiResponseElement) api.ajaxSpider.status()).getValue(); System.out.println("AJAX Spider status: " + status); } while ("running".equalsIgnoreCase(status)); System.out.println("AJAX Spider complete"); ``` ``` -------------------------------- ### ClientApi.callApiOther - Binary/Non-XML Response Source: https://context7.com/zaproxy/zap-api-java/llms.txt Details how to use `callApiOther` to download raw byte content from ZAP `other` endpoints, such as HAR exports or binary reports. ```APIDOC ## ClientApi.callApiOther — Binary/Non-XML Response Downloads raw byte content from a ZAP `other` endpoint (e.g., HAR exports, binary reports). ```java import java.nio.file.Files; import java.nio.file.Paths; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Download an XML report as bytes byte[] xmlReport = api.core.xmlreport(); Files.write(Paths.get("/tmp/zap-report.xml"), xmlReport); // Download messages as HAR via callApiOther byte[] har = api.callApiOther("core", "other", "messagesHar", null); Files.write(Paths.get("/tmp/messages.har"), har); ``` ``` -------------------------------- ### ClientApi.checkAlerts Source: https://context7.com/zaproxy/zap-api-java/llms.txt Verifies that a set of required alerts are present and no unexpected alerts remain. Designed for use in automated test pipelines. ```APIDOC ## ClientApi.checkAlerts — Assert Alert Conditions in Tests Verifies that a set of required alerts are present and no unexpected alerts remain. Designed for use in automated test pipelines. ```java import java.util.Arrays; import java.util.Collections; import org.zaproxy.clientapi.core.Alert; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Alerts to ignore (known false positives) Alert ignoreXPoweredBy = new Alert("X-Powered-By Header Information Leak", null, Alert.Risk.Low, Alert.Confidence.Medium); // Alerts that MUST be present (expected findings) Alert requireSqlInjection = new Alert("SQL Injection", "http://testapp.example.com/search", Alert.Risk.High, Alert.Confidence.Medium); // Throws ClientApiException if unexpected alerts remain or required alerts not found api.checkAlerts( Arrays.asList(ignoreXPoweredBy), Collections.singletonList(requireSqlInjection) ); // Alternatively, write results to file and throw on failure java.io.File outputFile = new java.io.File("/tmp/alert-results.xml"); api.checkAlerts( Arrays.asList(ignoreXPoweredBy), Collections.singletonList(requireSqlInjection), outputFile ); ``` ``` -------------------------------- ### Execute and Monitor Active Security Scan Source: https://context7.com/zaproxy/zap-api-java/llms.txt Initiates an active security scan to probe for vulnerabilities. Returns a scan ID for progress polling. The `activeScanSiteInScope` method provides a convenient way to wait for completion. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String target = "http://testapp.example.com/"; // Start active scan (url, recurse, inScopeOnly, scanPolicyName, method, postData) String scanId = ((ApiResponseElement) api.ascan.scan(target, "True", "False", null, null, null)).getValue(); // Poll until complete int progress; do { Thread.sleep(5000); progress = Integer.parseInt(((ApiResponseElement) api.ascan.status(scanId)).getValue()); System.out.printf("Active scan progress: %d%%%n", progress); } while (progress < 100); System.out.println("Active scan complete"); // Block until finished using high-level convenience method api.activeScanSiteInScope(target); // polls internally, returns when done ``` -------------------------------- ### Downloading Binary/Non-XML Responses Source: https://context7.com/zaproxy/zap-api-java/llms.txt Use callApiOther for endpoints that return binary content or non-XML data, such as HAR exports or binary reports. The response is returned as a byte array. ```java import java.nio.file.Files; import java.nio.file.Paths; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Download an XML report as bytes byte[] xmlReport = api.core.xmlreport(); Files.write(Paths.get("/tmp/zap-report.xml"), xmlReport); // Download messages as HAR via callApiOther byte[] har = api.callApiOther("core", "other", "messagesHar", null); Files.write(Paths.get("/tmp/messages.har"), har); ``` -------------------------------- ### reports.generate — Structured Report Generation Source: https://context7.com/zaproxy/zap-api-java/llms.txt Generates a formatted security report using ZAP's Reports add-on. Supports various formats like HTML, XML, JSON, and Markdown. ```APIDOC ## reports.generate — Structured Report Generation Generates a formatted security report using ZAP's Reports add-on, supporting HTML, XML, JSON, and Markdown templates. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // List available report templates System.out.println(api.reports.templates().toString(0)); // Generate an HTML report String reportPath = ((ApiResponseElement) api.reports.generate( "Security Scan Report", // title "traditional-html", // template name null, // theme (null = default) "Automated scan of MyApp", // description "MyApp", // contexts (comma-separated) null, // sites filter null, // sections "Low,Medium,High,Confirmed",// includedConfidences "Low,Medium,High", // includedRisks "scan-report", // reportFileName (no extension) null, // reportFileNamePattern "/tmp/zap-reports", // reportDir null // display )).getValue(); System.out.println("Report saved to: " + reportPath); // Generate XML report directly via core byte[] xmlBytes = api.core.xmlreport(); java.nio.file.Files.write(java.nio.file.Paths.get("/tmp/zap-report.xml"), xmlBytes); ``` ``` -------------------------------- ### ascan.scan Source: https://context7.com/zaproxy/zap-api-java/llms.txt Runs ZAP's active scanner, which probes for vulnerabilities by sending attack payloads. Returns a scan ID for progress polling. ```APIDOC ## ascan.scan — Active Security Scan Runs ZAP's active scanner, which probes for vulnerabilities by sending attack payloads. Returns a scan ID for progress polling. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String target = "http://testapp.example.com/"; // Start active scan (url, recurse, inScopeOnly, scanPolicyName, method, postData) String scanId = ((ApiResponseElement) api.ascan.scan(target, "True", "False", null, null, null)).getValue(); // Poll until complete int progress; do { Thread.sleep(5000); progress = Integer.parseInt(((ApiResponseElement) api.ascan.status(scanId)).getValue()); System.out.printf("Active scan progress: %d%%%n", progress); } while (progress < 100); System.out.println("Active scan complete"); // Block until finished using high-level convenience method api.activeScanSiteInScope(target); // polls internally, returns when done ``` ``` -------------------------------- ### Manage Passive Scanner and Rules Source: https://context7.com/zaproxy/zap-api-java/llms.txt Provides control over ZAP's passive scanner, including waiting for the scan queue to drain, listing available scanners, disabling specific rules by ID, and setting the maximum alerts per rule. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Wait for passive scan queue to drain after spidering int recordsLeft; do { Thread.sleep(1000); recordsLeft = Integer.parseInt( ((ApiResponseElement) api.pscan.recordsToScan()).getValue()); System.out.println("Passive scan records left: " + recordsLeft); } while (recordsLeft > 0); // List all passive scan rules System.out.println(api.pscan.scanners().toString(0)); // Disable a specific passive scan rule by ID api.pscan.disableScanners("10015"); // Incomplete or No Cache-control and Pragma HTTP Header // Set maximum alerts per rule api.pscan.setMaxAlertsPerRule("5"); ``` -------------------------------- ### spider.scan Source: https://context7.com/zaproxy/zap-api-java/llms.txt Crawls a target URL using ZAP's traditional link-following spider. Returns a scan ID that can be polled for progress. ```APIDOC ## spider.scan — Traditional Spider Crawl Crawls a target URL using ZAP's traditional link-following spider. Returns a scan ID that can be polled for progress. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); String target = "http://testapp.example.com/"; // Start spider scan (url, maxChildren, recurse, contextName, subtreeOnly) String scanId = ((ApiResponseElement) api.spider.scan(target, null, null, null, null)).getValue(); // Poll until complete int progress; do { Thread.sleep(1000); progress = Integer.parseInt(((ApiResponseElement) api.spider.status(scanId)).getValue()); System.out.printf("Spider progress: %d%%%n", progress); } while (progress < 100); // Retrieve discovered URLs System.out.println("Discovered URLs: " + api.spider.results(scanId).toString(0)); ``` ``` -------------------------------- ### pscan Source: https://context7.com/zaproxy/zap-api-java/llms.txt Manages the passive scanner, which analyses proxied traffic without sending extra requests. Records are queued as traffic flows through ZAP. ```APIDOC ## pscan — Passive Scanner Control Manages the passive scanner, which analyses proxied traffic without sending extra requests. Records are queued as traffic flows through ZAP. ```java import org.zaproxy.clientapi.core.ApiResponseElement; import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Wait for passive scan queue to drain after spidering int recordsLeft; do { Thread.sleep(1000); recordsLeft = Integer.parseInt( ((ApiResponseElement) api.pscan.recordsToScan()).getValue()); System.out.println("Passive scan records left: " + recordsLeft); } while (recordsLeft > 0); // List all passive scan rules System.out.println(api.pscan.scanners().toString(0)); // Disable a specific passive scan rule by ID api.pscan.disableScanners("10015"); // Incomplete or No Cache-control and Pragma HTTP Header // Set maximum alerts per rule api.pscan.setMaxAlertsPerRule("5"); ``` ``` -------------------------------- ### Making JSON Response API Calls Source: https://context7.com/zaproxy/zap-api-java/llms.txt Utilize callApiJson to retrieve raw JSON string responses from API calls, available since version 1.16.0. This is useful for endpoints that return structured JSON data. ```java import org.zaproxy.clientapi.core.ClientApi; ClientApi api = new ClientApi("localhost", 8090, "api-key"); // Get all alerts as JSON String json = api.callApiJson("alert", "view", "alerts", null); System.out.println(json); // Output: {"alerts":[{"sourceid":"3","other":"","method":"GET","evidence":"...","pluginId":"...","cweid":"...","confidence":"Medium","wascid":"...","description":"...","messageId":"...","url":"http://example.com/","reference":"...","solution":"...","alert":"...","param":"","attack":"","name":"...","risk":"Low","id":"1"},...]} ``` -------------------------------- ### Commit Version Bump Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Commit changes after updating the version number in relevant files. ```bash git commit -S -m "Bump version number to " ``` -------------------------------- ### Delete Release Branch Source: https://github.com/zaproxy/zap-api-java/blob/main/RELEASING.md Delete the local release branch after reintegration. ```bash git branch -d release- ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.