### Install Checkmarx Python SDK from source Source: https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/master/README.md Clone the repository and install the SDK using the setup.py script. This method is useful if you need to access the sample scripts or contribute to the SDK. ```bash git clone https://github.com/checkmarx-ts/checkmarx-python-sdk.git python setup.py install ``` -------------------------------- ### Install Checkmarx Python SDK using pip Source: https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/master/README.md Use this command to install the SDK via pip. This is the recommended method for quick setup. ```bash pip install CheckmarxPythonSDK ``` -------------------------------- ### Raw GET Request Example Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Demonstrates how to make a raw GET request to an API endpoint, useful for endpoints not yet wrapped in a specific API class. ```APIDOC ## Raw GET Request ### Description This example shows how to perform a raw GET request to an API endpoint using the Checkmarx Python SDK client. It's useful for accessing API functionalities that might not have dedicated wrapper methods. ### Method GET ### Endpoint `/api/projects` ### Parameters #### Query Parameters - **offset** (integer) - Optional - The starting offset for the request. - **limit** (integer) - Optional - The maximum number of items to return. ### Request Example ```python response = client.get_request("/api/projects", params={"offset": 0, "limit": 10}) print(response.status_code, response.json()) ``` ### Response #### Success Response (200) Returns a JSON object containing project data. The exact structure depends on the API endpoint. #### Response Example ```json { "projects": [ { "id": "project-id-1", "name": "Project One", "status": "Active" } ], "totalCount": 100 } ``` ``` -------------------------------- ### Explicit Configuration and ApiClient for CxOne Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Instantiate Configuration and ApiClient directly for CxOne, enabling multi-system connections. This example uses a refresh token for authentication and demonstrates fetching projects. ```python from CheckmarxPythonSDK.configuration import Configuration from CheckmarxPythonSDK.api_client import ApiClient from CheckmarxPythonSDK.CxOne import ProjectsAPI, ScansAPI # CxOne with refresh token (API key) config = Configuration( server_base_url="https://ast.checkmarx.net", iam_base_url="https://iam.checkmarx.net", token_url="https://iam.checkmarx.net/auth/realms/myTenant/protocol/openid-connect/token", tenant_name="myTenant", grant_type="refresh_token", client_id="ast-app", api_key="", verify=True, # True = use certifi CA bundle; False = skip; str = path to cert timeout=60, max_retries=3, rate_limit_capacity=20000, rate_limit_period=300, ) api_client = ApiClient(configuration=config) projects_api = ProjectsAPI(api_client=api_client) scans_api = ScansAPI(api_client=api_client) # Verify connection all_projects = projects_api.get_all_projects() print(f"Total projects: {len(all_projects)}") # Total projects: 42 ``` -------------------------------- ### Manage CxSAST Users and Roles Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Provides examples for listing all users, creating a new user with specified roles and teams, and retrieving all available roles and teams. Requires an initialized AccessControlAPI object. ```python from CheckmarxPythonSDK.CxRestAPISDK import AccessControlAPI ac = AccessControlAPI() # List all users users = ac.get_all_users() for u in users: print(u.user_id, u.username, u.email) # Create a new user created = ac.create_user( username="jdoe", password="Str0ngP@ss!", role_ids=[1, 3], team_ids=[5], first_name="Jane", last_name="Doe", email="jdoe@example.com", active=True, authentication_provider_id=1, locale_id=1, ) print(f"Created user ID: {created}") # Get all roles and teams roles = ac.get_all_roles() for r in roles: print(r.role_id, r.name) teams = ac.get_all_teams() for t in teams: print(t.team_id, t.full_name) ``` -------------------------------- ### Instantiate ApiClient with Client Credentials and Proxies Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Initialize the ApiClient using client credentials and configure proxy settings for network requests. This example sets a timeout and rate limiting parameters. ```python from CheckmarxPythonSDK.configuration import Configuration from CheckmarxPythonSDK.api_client import ApiClient config = Configuration( server_base_url="https://ast.checkmarx.net", iam_base_url="https://iam.checkmarx.net", token_url="https://iam.checkmarx.net/auth/realms/myTenant/protocol/openid-connect/token", tenant_name="myTenant", grant_type="client_credentials", client_id="my-client", client_secret="my-secret", verify=True, timeout=120, proxies={"http": "http://proxy:8080", "https": "http://proxy:8080"}, rate_limit_capacity=5000, rate_limit_period=300, ) client = ApiClient(configuration=config) ``` -------------------------------- ### Raw POST Request Example Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Demonstrates how to make a raw POST request to an API endpoint, including a JSON payload. ```APIDOC ## Raw POST Request ### Description This example illustrates how to execute a raw POST request to an API endpoint with a JSON payload. This is useful for creating or updating resources where a specific SDK method is not available. ### Method POST ### Endpoint `/api/scans` ### Parameters #### Request Body - **project** (object) - Required - Contains project details. - **id** (string) - Required - The ID of the project. - **type** (string) - Required - The type of scan (e.g., "git"). ### Request Example ```python response = client.post_request( "/api/scans", json={"project": {"id": "proj-uuid"}, "type": "git"}, ) scan = response.json() print(scan["id"]) ``` ### Response #### Success Response (200 or 201) Returns a JSON object representing the created scan resource. #### Response Example ```json { "id": "scan-uuid-123", "status": "Pending", "createdAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Manage CxSAST Projects with CxRestAPISDK Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Provides examples for resolving a team ID, listing all projects within a team, creating a new project with default configuration, and uploading a source code ZIP file for a project. Requires `ProjectsAPI` and `TeamAPI`. ```python from CheckmarxPythonSDK.CxRestAPISDK import ProjectsAPI, TeamAPI team_api = TeamAPI() project_api = ProjectsAPI() # Resolve team ID team_id = team_api.get_team_id_by_team_full_name("/CxServer/MyTeam") print(f"Team ID: {team_id}") # List all projects in a team projects = project_api.get_all_project_details(team_id=team_id) for p in projects: print(p.id, p.name) # Create project project = project_api.create_project_with_default_configuration( project_name="WebShop", team_id=team_id, is_public=True, ) project_id = project.id print(f"New project ID: {project_id}") # Upload source ZIP project_api.upload_source_code_zip_file(project_id=project_id, zip_file="./WebShop.zip") ``` -------------------------------- ### Get All Roles Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves a list of all available roles in the CxSAST Access Control system. ```APIDOC ## Get all roles ```python roles = ac.get_all_roles() for r in roles: print(r.role_id, r.name) ``` ``` -------------------------------- ### Raw GET and POST Requests with Checkmarx Client Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Use these methods for endpoints not yet wrapped in a specific API class. They allow for direct HTTP requests to the Checkmarx API. ```python response = client.get_request("/api/projects", params={"offset": 0, "limit": 10}) print(response.status_code, response.json()) ``` ```python response = client.post_request( "/api/scans", json={"project": {"id": "proj-uuid"}, "type": "git"}, ) scan = response.json() print(scan["id"]) ``` -------------------------------- ### CxSAST Portal SOAP API - CxPortalWebService Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Manage CxSAST presets, queries, and reports using the SOAP API. Perform operations like getting server version, listing presets, creating custom presets, exporting/importing queries, and converting results to SARIF. ```APIDOC ## CxPortalWebService ### Description Provides methods to interact with the CxSAST Portal via SOAP for various administrative and reporting tasks. ### Methods #### get_version_number_as_int ##### Description Retrieves the CxSAST server version as an integer. ##### Response Example 10000 ``` ```APIDOC #### get_preset_list ##### Description Retrieves a list of all available presets. ##### Response Example [ { "id": 1, "presetName": "Default Preset" } ] ``` ```APIDOC #### create_new_preset ##### Description Creates a new custom preset based on a list of query IDs. ##### Parameters - **query_ids** (list[int]) - Required - A list of query IDs to include in the preset. - **name** (str) - Required - The name for the new preset. ##### Response Example { "preset": { "id": 5, "presetName": "MyCustomPreset" } } ``` ```APIDOC #### export_queries ##### Description Exports specified queries from the CxSAST system. ##### Parameters - **query_ids** (list[int]) - Required - A list of query IDs to export. ##### Response Example { "IsSuccesfull": true } ``` ```APIDOC #### import_queries ##### Description Imports queries into the CxSAST system from an XML data string. ##### Parameters - **query_xml_data** (bytes) - Required - The XML data containing the queries to import. ##### Response Example { "IsSuccesfull": true } ``` ```APIDOC #### get_results_and_write_to_sarif_format ##### Description Converts SAST XML scan results to SARIF format. ##### Parameters - **sast_xml** (bytes) - Required - The XML data of the SAST scan results. ##### Response Example "{\"version\": \"2.1.0\", ...}" ``` -------------------------------- ### Retrieve SAST Results by Scan ID Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt This example shows how to fetch SAST vulnerability results for a specific scan, with options to filter by severity, state, and limit the number of results returned. It uses a module-level convenience function. ```python from CheckmarxPythonSDK.CxOne import get_sast_results_by_scan_id from CheckmarxPythonSDK.CxOne.sastResultsAPI import SastResultsAPI # Module-level convenience function results = get_sast_results_by_scan_id( scan_id="abc123-scan-id", severity=["HIGH", "CRITICAL"], state=["TO_VERIFY", "CONFIRMED"], limit=50, ) print(f"Total results: {results.get('totalCount')}") for r in results.get("results", []): print(r.get("queryName"), r.get("severity"), r.get("status")) ``` -------------------------------- ### Manage CxOne Webhooks Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Demonstrates creating tenant-level and project-level webhooks with specified URLs and events. It also shows how to list existing tenant webhooks. Requires `WebHookInput` DTO. ```python from CheckmarxPythonSDK.CxOne.webhookAPI import WebHookAPI from CheckmarxPythonSDK.CxOne.dto import WebHookInput api = WebHookAPI() # Create a tenant-level webhook hook_input = WebHookInput( url="https://my-ci-system/checkmarx-events", events=["scan.completed", "scan.failed"], is_active=True, secret_token="my-hmac-secret", ) hook = api.create_a_webhook_for_a_tenant(webhook_input=hook_input) print(f"Webhook ID: {hook.id}") # Create a project-level webhook hook2 = api.create_a_webhook_on_project( project_id="3f2c1a0e-...", webhook_input=hook_input, ) print(f"Project webhook ID: {hook2.id}") # List tenant webhooks collection = api.get_a_list_of_webhooks_related_to_tenant(offset=0, limit=20) for wh in collection.webhooks: print(wh.id, wh.url, wh.is_active) ``` -------------------------------- ### Get SAST Scan Statistics Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves the vulnerability statistics for a completed SAST scan. ```APIDOC ## Get vulnerability statistics ```python stats = scan_api.get_statistics_results_by_scan_id(scan_id=scan_id) print(f"High: {stats.high_severity}, Medium: {stats.medium_severity}, Low: {stats.low_severity}") ``` ``` -------------------------------- ### Get All Teams (Access Control) Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves a list of all teams available in the CxSAST Access Control system. ```APIDOC ## Get all teams ```python teams = ac.get_all_teams() for t in teams: print(t.team_id, t.full_name) ``` ``` -------------------------------- ### ScansAPI - Get scan by ID Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves the status and details of a specific scan using its unique ID. ```APIDOC ## ScansAPI - Get scan by ID ### Description Fetches the current status and details of a scan identified by its unique ID. This is commonly used in loops to monitor scan progress. ### Method GET ### Endpoint `/api/scans/{scan_id}` (internal implementation) ### Parameters - **scan_id** (string) - Required - The unique identifier of the scan. ### Request Example ```python # Assuming 'scan' object from create_scan call current = scans_api.get_scan_by_id(scan_id=scan.id) print(f"Status: {current.status}") ``` ### Response #### Success Response (200) Returns a scan object with its current status and details. #### Response Example ```json { "id": "scan-uuid-456", "status": "Running", "progress": 50, "createdAt": "2023-10-27T11:00:00Z" } ``` ``` -------------------------------- ### Manage CxOne Applications Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Demonstrates creating a new application with specific details and rules, and listing applications filtered by name. Requires `ApplicationInput` and `RuleInput` DTOs. ```python from CheckmarxPythonSDK.CxOne import ( create_an_application, get_a_list_of_applications, get_application_id_by_name, create_an_application_rule, delete_an_application, ) from CheckmarxPythonSDK.CxOne.dto import ApplicationInput, RuleInput # Create an application app_input = ApplicationInput( name="PaymentService", description="Payment microservice security scope", criticality=4, rules=[], tags={"team": "payments"}, ) created_app = create_an_application(application_input=app_input) print(f"App ID: {created_app.id}") # Add a project-matching rule rule_input = RuleInput(rule_type="project.name.in", value="PaymentService,CheckoutAPI") create_an_application_rule(application_id=created_app.id, rule_input=rule_input) # List applications filtered by name apps = get_a_list_of_applications(name="Payment", limit=10) for app in apps.applications: print(app.id, app.name, app.criticality) ``` -------------------------------- ### Configure SDK via Environment Variables Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Configure SDK settings for CxSAST and CxOne services using environment variables. Prefix variables with the service name (e.g., CXSAST_, CXONE_). ```bash # CxSAST export CXSAST_BASE_URL=http://localhost:80 export CXSAST_USERNAME=admin export CXSAST_PASSWORD=secret export CXSAST_GRANT_TYPE=password export CXSAST_SCOPE=sast_rest_api export CXSAST_CLIENT_ID=resource_owner_client export CXSAST_CLIENT_SECRET=014DF517-39D1-4453-B7B3-9930C563627C # CxOne export CXONE_ACCESS_CONTROL_URL=https://iam.checkmarx.net export CXONE_SERVER=https://ast.checkmarx.net export CXONE_TENANT_NAME=myTenant export CXONE_GRANT_TYPE=refresh_token export CXONE_CLIENT_ID=ast-app export CXONE_REFRESH_TOKEN= ``` -------------------------------- ### Get Team ID by Full Name Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves the unique ID of a team given its full hierarchical name. ```APIDOC ## Get team ID by full path ```python team_id = team_api.get_team_id_by_team_full_name("/CxServer/SP/Engineering") print(f"Engineering team ID: {team_id}") ``` ``` -------------------------------- ### Manage CxOne Projects with ProjectsAPI Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt This snippet demonstrates how to list, create, retrieve, update, and delete projects using the ProjectsAPI. Ensure necessary imports are included. ```python import time from CheckmarxPythonSDK.CxOne import ( ProjectsAPI, create_a_project, get_all_projects, get_project_id_by_name, update_a_project, delete_a_project, ) from CheckmarxPythonSDK.CxOne.dto import ProjectInput # List all projects (auto-paginates) all_projects = get_all_projects() for p in all_projects[:3]: print(p.id, p.name, p.tags) ``` ```python # Create a project project_input = ProjectInput( name="MyAppScan", groups=["dev-team"], tags={"env": "staging", "owner": "alice"}, criticality=3, main_branch="main", repo_url="https://github.com/myorg/myapp.git", ) api = ProjectsAPI() created = api.create_a_project(project_input=project_input) print(f"Created project ID: {created.id}") # Created project ID: 3f2c1a0e-... ``` ```python # Retrieve project ID by name project_id = get_project_id_by_name("MyAppScan") print(f"Project ID: {project_id}") ``` ```python # Update tags api.add_project_single_tag(project_id=project_id, tag_key="reviewed", tag_value="true") ``` ```python # Delete a project delete_a_project(project_id=project_id) ``` -------------------------------- ### ScansAPI - Get a list of scans Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves a list of scans, with options to filter by project, status, and sort order. ```APIDOC ## ScansAPI - Get a list of scans ### Description Retrieves a collection of scans, allowing for filtering based on project ID and scan status, as well as specifying the number of results and sorting criteria. ### Method GET ### Endpoint `/api/scans` (internal implementation) ### Parameters #### Query Parameters - **project_id** (string) - Optional - Filter scans belonging to a specific project. - **statuses** (list of strings) - Optional - Filter scans by their status (e.g., "Completed", "Failed"). - **limit** (integer) - Optional - The maximum number of scans to return. - **sort** (list of strings) - Optional - Fields to sort by (e.g., "-created_at" for descending creation time). ### Request Example ```python collection = scans_api.get_a_list_of_scans( project_id="3f2c1a0e-abcd-1234-efgh-567890abcdef", statuses=["Completed"], limit=5, sort=["-created_at"], ) for s in collection.scans: print(s.id, s.status, s.created_at) ``` ### Response #### Success Response (200) Returns a collection object containing a list of scan objects. #### Response Example ```json { "scans": [ { "id": "scan-uuid-789", "status": "Completed", "created_at": "2023-10-27T12:00:00Z" } ], "totalCount": 10 } ``` ``` -------------------------------- ### ProjectsAPI - Create a project Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Creates a new project in CxOne with specified details including name, groups, tags, criticality, main branch, and repository URL. ```APIDOC ## ProjectsAPI - Create a project ### Description Creates a new project within the CxOne platform. You can define various attributes for the project, such as its name, associated groups, tags for organization, criticality level, the main branch for tracking, and the repository URL. ### Method POST ### Endpoint `/api/projects` (internal implementation) ### Parameters #### Request Body - **project_input** (ProjectInput) - Required - An object containing the project's configuration details. - **name** (string) - Required - The name of the project. - **groups** (list of strings) - Optional - A list of group IDs the project belongs to. - **tags** (object) - Optional - Key-value pairs for tagging the project. - **criticality** (integer) - Optional - The criticality level of the project (e.g., 1-5). - **main_branch** (string) - Optional - The name of the main branch. - **repo_url** (string) - Required - The URL of the project's repository. ### Request Example ```python from CheckmarxPythonSDK.CxOne.dto import ProjectInput project_input = ProjectInput( name="MyAppScan", groups=["dev-team"], tags={"env": "staging", "owner": "alice"}, criticality=3, main_branch="main", repo_url="https://github.com/myorg/myapp.git", ) api = ProjectsAPI() created = api.create_a_project(project_input=project_input) print(f"Created project ID: {created.id}") ``` ### Response #### Success Response (201) Returns the newly created project object, including its unique ID. #### Response Example ```json { "id": "3f2c1a0e-abcd-1234-efgh-567890abcdef", "name": "MyAppScan", "status": "Active" } ``` ``` -------------------------------- ### SastResultsAPI - Get SAST Results by Scan ID Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves SAST results for a given scan ID with various filtering and pagination options. ```APIDOC ## get_sast_results_by_scan_id ### Description Retrieves SAST results for a given scan ID, allowing filtering by severity, language, source file, and more, along with pagination and sorting. ### Method ```python api.get_sast_results_by_scan_id( scan_id: str, severity: list[str] = None, language: list[str] = None, source_file: str = None, source_file_operation: str = None, offset: int = 0, limit: int = 20, sort: list[str] = None ) ``` ### Parameters #### Path Parameters - **scan_id** (str) - Required - The ID of the scan to retrieve results for. #### Query Parameters - **severity** (list[str]) - Optional - Filters results by severity level (e.g., "HIGH"). - **language** (list[str]) - Optional - Filters results by programming language (e.g., "Java"). - **source_file** (str) - Optional - Filters results by source file name. - **source_file_operation** (str) - Optional - Operation for source file filtering (e.g., "CONTAINS"). - **offset** (int) - Optional - The number of results to skip (for pagination). - **limit** (int) - Optional - The maximum number of results to return (for pagination). - **sort** (list[str]) - Optional - Specifies the sorting order for results (e.g., "-severity", "+queryname"). ### Response #### Success Response (200) - **results** (list) - A list of vulnerability dictionaries, each containing details like 'queryName', 'sourceFileName', and 'sourceLine'. ### Request Example ```python api = SastResultsAPI() detail = api.get_sast_results_by_scan_id( scan_id="abc123-scan-id", severity=["HIGH"], language=["Java"], source_file="PaymentService", source_file_operation="CONTAINS", offset=0, limit=20, sort=["-severity", "+queryname"], ) for vuln in detail.get("results", []): print(vuln.get("queryName"), vuln.get("sourceFileName"), vuln.get("sourceLine")) ``` ``` -------------------------------- ### SastResultsAPI - Get SAST results by scan ID Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves Static Application Security Testing (SAST) vulnerability results for a completed scan, with extensive filtering capabilities. ```APIDOC ## SastResultsAPI - Get SAST results by scan ID ### Description Fetches detailed SAST vulnerability findings for a specific scan that has finished processing. This function allows granular filtering based on severity, state, query type, file path, and more, enabling targeted analysis of security issues. ### Method GET ### Endpoint `/api/scans/{scan_id}/sast-results` (internal implementation) ### Parameters #### Query Parameters - **scan_id** (string) - Required - The ID of the completed scan. - **severity** (list of strings) - Optional - Filter by severity level (e.g., "HIGH", "CRITICAL"). - **state** (list of strings) - Optional - Filter by vulnerability state (e.g., "TO_VERIFY", "CONFIRMED"). - **limit** (integer) - Optional - The maximum number of results to return. - **offset** (integer) - Optional - The starting offset for pagination. - **queryName** (string) - Optional - Filter by the name of the vulnerability query. - **fileName** (string) - Optional - Filter by the file where the vulnerability was found. ### Request Example ```python # Module-level convenience function results = get_sast_results_by_scan_id( scan_id="abc123-scan-id", severity=["HIGH", "CRITICAL"], state=["TO_VERIFY", "CONFIRMED"], limit=50, ) print(f"Total results: {results.get('totalCount')}") for r in results.get("results", []): print(r.get("queryName"), r.get("severity"), r.get("status")) ``` ### Response #### Success Response (200) Returns a JSON object containing the total count of matching results and a list of vulnerability details. #### Response Example ```json { "totalCount": 150, "results": [ { "queryName": "SQL Injection", "severity": "CRITICAL", "status": "CONFIRMED", "fileName": "database.php", "lineNumber": 42 } ] } ``` ``` -------------------------------- ### Integrate Repositories with CxOne RepoManagerAPI Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Shows how to list available repositories for a given SCM integration, construct a repository import request, and perform a batch import of repositories into CxOne. The batch import polls until completion. ```python from CheckmarxPythonSDK.CxOne import ( batch_import_repo, get_repos, construct_repo_request, get_job_status, ) # List available repos for a GitHub SCM integration repos = get_repos(scm_id=1, org_identity="myorg", limit=20) for repo in repos.repos: print(repo.name, repo.url, repo.defaultBranch) # Build a repo import request for one repo repo_request = construct_repo_request( repo_id="myorg/myapp", scm_id=1, org_identity="myorg", branch="main", project_name="MyApp", tags={"owner": "backend-team"}, ) # Batch import (polls until done) results = batch_import_repo( scm_id=1, org_identity="myorg", repo_requests=[repo_request], delay_request_timeout=30, ) print(results) ``` -------------------------------- ### CxSAST OData API - ResultsODataAPI Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Access scan results using the OData API. Retrieve results for a specific scan and get the query name for a particular scan result. ```APIDOC ## ResultsODataAPI ### Description Provides methods to retrieve detailed results for CxSAST scans via OData. ### Methods #### get_results_for_a_specific_scan_id ##### Description Retrieves all results for a specific scan ID. This method supports OData pagination using $skip and $top. ##### Parameters - **scan_id** (int) - Required - The ID of the scan. ##### Response Example [ { "Severity": "High", "QueryName": "SQL_Injection" }, { "Severity": "Medium", "QueryName": "Cross_Site_Scripting" } ] #### get_the_query_that_was_run_for_a_particular_unique_scan_result ##### Description Retrieves the name of the query that was run for a specific unique scan result. ##### Parameters - **result_id** (int) - Required - The unique ID of the scan result. - **scan_id** (int) - Required - The ID of the scan. ##### Response Example "SQL_Injection" ``` -------------------------------- ### Enable Debug Mode and Configuration Override Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Demonstrates how to enable verbose logging for the Checkmarx SDK, either via command-line arguments or by setting the logging level in the configuration. ```python import sys ``` -------------------------------- ### Manage CxSAST Teams Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Demonstrates listing all teams, retrieving a team ID by its full path, creating a sub-team, and deleting a team. Requires an initialized TeamAPI object. ```python from CheckmarxPythonSDK.CxRestAPISDK import TeamAPI team_api = TeamAPI() # List all teams teams = team_api.get_all_teams() for t in teams: print(f"{t.team_id}: {t.full_name}") # Get team ID by full path team_id = team_api.get_team_id_by_team_full_name("/CxServer/SP/Engineering") print(f"Engineering team ID: {team_id}") # Create sub-team new_team = team_api.create_team(team_name="BackendTeam", parent_id=team_id) print(f"New sub-team ID: {new_team.id}") # Delete team team_api.delete_team(team_id=new_team.id) ``` -------------------------------- ### Get SAST Results by Scan ID Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves SAST results for a given scan ID with optional filters for severity, language, and source file. It iterates through the results to print vulnerability details. ```python api = SastResultsAPI() detail = api.get_sast_results_by_scan_id( scan_id="abc123-scan-id", severity=["HIGH"], language=["Java"], source_file="PaymentService", source_file_operation="CONTAINS", offset=0, limit=20, sort=["-severity", "+queryname"], ) for vuln in detail.get("results", []): print(vuln.get("queryName"), vuln.get("sourceFileName"), vuln.get("sourceLine")) ``` -------------------------------- ### Configure SDK via config.ini Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Configure SDK settings for different Checkmarx services (CxSAST, CxSCA, CxOne, CxReporting) using a local config.ini file. Ensure the correct section and parameters are used for each service. ```ini [CxSAST] base_url = http://localhost:80 username = admin password = secret grant_type = password scope = sast_rest_api client_id = resource_owner_client client_secret = 014DF517-39D1-4453-B7B3-9930C563627C [CxSCA] access_control_url = https://platform.checkmarx.net server = https://api-sca.checkmarx.net account = myAccount username = admin password = secret [CxOne] access_control_url = https://iam.checkmarx.net server = https://ast.checkmarx.net tenant_name = myTenant grant_type = refresh_token client_id = ast-app refresh_token = [CxReporting] base_url = http://localhost reporting_client_url = http://localhost:5001 username = admin password = secret grant_type = password scope = reporting_api client_id = reporting_service_api client_secret = 014DF517-39D1-4453-B7B3-9930C563627C ``` -------------------------------- ### Configure Project Settings Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Configure Git source, data retention, and exclude patterns for a project. Ensure project_id is set before use. ```python project_api.set_remote_source_setting_to_git( project_id=project_id, url="https://github.com/myorg/webshop.git", branch="refs/heads/main", ) project_api.set_data_retention_settings_by_project_id(project_id=project_id, scans_to_keep=5) project_api.set_project_exclude_settings_by_project_id( project_id=project_id, exclude_folders_pattern="test,target,node_modules", exclude_files_pattern="*.min.js,*.generated.*", ) ``` -------------------------------- ### Configure Checkmarx Python SDK with Debugging Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Instantiate `ApiClient` with a `Configuration` object to enable debug output. This configuration includes server URLs, authentication details, and logging level. Debug output will show configuration loading and HTTP requests. ```python from CheckmarxPythonSDK.configuration import Configuration from CheckmarxPythonSDK.api_client import ApiClient config = Configuration( server_base_url="https://ast.checkmarx.net", iam_base_url="https://iam.checkmarx.net", token_url="https://iam.checkmarx.net/auth/realms/myTenant/protocol/openid-connect/token", tenant_name="myTenant", grant_type="refresh_token", client_id="ast-app", api_key="", logging_level="DEBUG", # DEBUG, INFO, WARNING, ERROR, CRITICAL ) client = ApiClient(configuration=config) # Debug output will print config loading sequence and every HTTP request ``` -------------------------------- ### CxOne Configuration using config.ini (Refresh Token) Source: https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/master/README.md Configuration for CxOne using a config.ini file with the refresh_token grant type. Requires specific client ID 'ast-app'. ```ini [CxOne] access_control_url = https://iam.checkmarx.net server = https://ast.checkmarx.net tenant_name = *** grant_type = refresh_token client_id = ast-app client_secret = *** username = *** password = *** refresh_token = *** ``` -------------------------------- ### Enable Debug Mode Source: https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/master/README.md Enable debug mode using a command-line option. This will print configuration loading details and outgoing HTTP requests. ```bash --cx_debug true ``` -------------------------------- ### Create and Monitor Scans with ScansAPI Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt This section shows how to create scans from Git repositories, poll for their status, and list recent scans with filtering. Requires ScanInput DTO and time module. ```python import time from CheckmarxPythonSDK.CxOne import ( ScansAPI, create_scan, get_scan_by_id, get_a_list_of_scans, cancel_scan, ) from CheckmarxPythonSDK.CxOne.dto import ScanInput # Create a scan from a Git repository scan_input = ScanInput( project_id="3f2c1a0e-மையில்", scan_type="git", handler={"branch": "main", "repoUrl": "https://github.com/myorg/myapp.git"}, config=[{"type": "sast", "value": {"incremental": "false", "presetName": "Checkmarx Default"}}], tags={"trigger": "ci"}, ) scans_api = ScansAPI() scan = scans_api.create_scan(scan_input=scan_input) print(f"Scan ID: {scan.id}, Status: {scan.status}") ``` ```python # Poll until finished while True: current = scans_api.get_scan_by_id(scan_id=scan.id) if current.status in ("Completed", "Failed", "Canceled", "Partial"): print(f"Scan finished: {current.status}") break print(f"Status: {current.status} — waiting 30s...") time.sleep(30) ``` ```python # List recent scans filtered by project and status collection = scans_api.get_a_list_of_scans( project_id="3f2c1a0e-மையில்", statuses=["Completed"], limit=5, sort=["-created_at"], ) for s in collection.scans: print(s.id, s.status, s.created_at) ``` -------------------------------- ### CxReporting Configuration using config.ini Source: https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/master/README.md Configuration for CxReporting using a config.ini file. Includes URLs for the base and reporting client. ```ini [CxReporting] base_url = http://localhost reporting_client_url = http://localhost:5001 username = *** password = *** grant_type = password scope = reporting_api client_id = reporting_service_api client_secret = 014DF517-39D1-4453-B7B3-9930C563627C ``` -------------------------------- ### Upload ZIP for Scanning with UploadsAPI Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt This workflow generates a pre-signed S3 URL, uploads a ZIP file, and then triggers a scan. It's useful for scanning without a Git connection. Requires ScanInput DTO and time module. ```python from CheckmarxPythonSDK.CxOne import ( create_a_pre_signed_url_to_upload_files, upload_zip_content_for_scanning, ScansAPI, ) from CheckmarxPythonSDK.CxOne.dto import ScanInput import time # Step 1: get a pre-signed upload URL upload_url = create_a_pre_signed_url_to_upload_files() print(f"Upload URL: {upload_url}") ``` ```python # Step 2: upload the ZIP success = upload_zip_content_for_scanning( upload_link=upload_url, zip_file_path="./JavaVulnerableLab.zip", ) print(f"Upload successful: {success}") ``` ```python # Step 3: trigger a scan scan_input = ScanInput( project_id="3f2c1a0e-மையில்", scan_type="upload", handler={"uploadUrl": upload_url, "branch": "main"}, config=[{"type": "sast", "value": {"presetName": "All"}}], ) scans_api = ScansAPI() scan = scans_api.create_scan(scan_input=scan_input) print(f"Scan ID: {scan.id}") ``` ```python # Poll while True: s = scans_api.get_scan_by_id(scan.id) if s.status in ("Completed", "Failed", "Canceled"): break time.sleep(20) print(f"Final status: {s.status}") ``` -------------------------------- ### ProjectsAPI (CxRestAPISDK) - Manage CxSAST Projects Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Manages CxSAST projects, including creation, source configuration, and settings. ```APIDOC ## ProjectsAPI (CxRestAPISDK) Operations ### Description Manages CxSAST projects, covering creation, source code configuration (local ZIP, Git, SVN, TFS, Perforce), settings, and data retention policies. ### Methods #### get_team_id_by_team_full_name Resolves a team ID from its full name. - **Parameters**: - **team_full_name** (str) - Required - The full path of the team (e.g., "/CxServer/MyTeam"). #### get_all_project_details Retrieves details for all projects within a specified team. - **Parameters**: - **team_id** (int) - Required - The ID of the team whose projects are to be listed. #### create_project_with_default_configuration Creates a new CxSAST project with default configuration settings. - **Parameters**: - **project_name** (str) - Required - The name for the new project. - **team_id** (int) - Required - The ID of the team to which the project belongs. - **is_public** (bool) - Optional - Whether the project should be public. #### upload_source_code_zip_file Uploads a ZIP file containing the source code for a project. - **Parameters**: - **project_id** (str) - Required - The ID of the project to upload the source code to. - **zip_file** (str) - Required - The path to the ZIP file containing the source code. ### Response #### Success Response (get_team_id_by_team_full_name) - **team_id** (int) - The ID of the team. #### Success Response (get_all_project_details) - **projects** (list[ProjectDetails]) - A list of project detail objects, each containing 'id' and 'name'. #### Success Response (create_project_with_default_configuration) - **project** (Project) - The newly created project object, including its ID. ### Request Example ```python from CheckmarxPythonSDK.CxRestAPISDK import ProjectsAPI, TeamAPI team_api = TeamAPI() project_api = ProjectsAPI() # Resolve team ID team_id = team_api.get_team_id_by_team_full_name("/CxServer/MyTeam") print(f"Team ID: {team_id}") # List all projects in a team projects = project_api.get_all_project_details(team_id=team_id) for p in projects: print(p.id, p.name) # Create project project = project_api.create_project_with_default_configuration( project_name="WebShop", team_id=team_id, is_public=True, ) project_id = project.id print(f"New project ID: {project_id}") # Upload source ZIP project_api.upload_source_code_zip_file(project_id=project_id, zip_file="./WebShop.zip") ``` ``` -------------------------------- ### CxSAST Configuration using config.ini Source: https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/master/README.md Configuration for CxSAST using a config.ini file. Ensure all sensitive information is kept secure. ```ini [CxSAST] base_url = http://localhost:80 username = ****** password = ****** grant_type = password scope = sast_rest_api client_id = resource_owner_client client_secret = 014DF517-39D1-4453-B7B3-9930C563627C ``` -------------------------------- ### ProjectsAPI - List all projects Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Retrieves a list of all projects managed by CxOne. This function automatically handles pagination to fetch all available projects. ```APIDOC ## ProjectsAPI - List all projects ### Description Fetches all projects from CxOne. This method automatically handles pagination, ensuring that all projects are retrieved even if there are many. ### Method GET ### Endpoint `/api/projects` (internal implementation) ### Parameters None ### Request Example ```python # List all projects (auto-paginates) all_projects = get_all_projects() for p in all_projects[:3]: print(p.id, p.name, p.tags) ``` ### Response #### Success Response (200) Returns a list of project objects, each containing details like ID, name, and tags. #### Response Example ```json [ { "id": "proj-uuid-1", "name": "Project Alpha", "tags": {"env": "prod"} }, { "id": "proj-uuid-2", "name": "Project Beta", "tags": {"team": "backend"} } ] ``` ``` -------------------------------- ### Create User Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Creates a new user in the CxSAST Access Control system with specified roles and team assignments. ```APIDOC ## Create a new user ```python created = ac.create_user( username="jdoe", password="Str0ngP@ss!", role_ids=[1, 3], team_ids=[5], first_name="Jane", last_name="Doe", email="jdoe@example.com", active=True, authentication_provider_id=1, locale_id=1, ) print(f"Created user ID: {created}") ``` ``` -------------------------------- ### UploadsAPI - Create a pre-signed URL for upload Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Generates a pre-signed URL that allows direct upload of a ZIP file to an S3 bucket for subsequent scanning. ```APIDOC ## UploadsAPI - Create a pre-signed URL for upload ### Description Generates a temporary, secure URL that permits uploading a ZIP file directly to cloud storage. This URL is used as a precursor to initiating a scan from an uploaded file, bypassing Git integration. ### Method POST ### Endpoint `/api/uploads/url` (internal implementation) ### Parameters None ### Request Example ```python upload_url = create_a_pre_signed_url_to_upload_files() print(f"Upload URL: {upload_url}") ``` ### Response #### Success Response (200) Returns the generated pre-signed URL as a string. #### Response Example ```json { "uploadUrl": "https://s3.amazonaws.com/bucket-name/uploads/uuid?AWSAccessKeyId=... } ``` ``` -------------------------------- ### Create and Download CxOne Scan Report Source: https://context7.com/checkmarx-ts/checkmarx-python-sdk/llms.txt Generates a scan report in PDF format for specified scan engines and scan IDs. It then downloads the generated report content and saves it to a local file. ```python from CheckmarxPythonSDK.CxOne import create_scan_report_v2, get_scan_report from CheckmarxPythonSDK.CxOne.reportAPI import ReportAPI # Create report (blocks until completed) api = ReportAPI() report_id = api.create_scan_report_v2( file_format="pdf", scan_engines=["sast", "sca"], scan_id="abc123-scan-id", ) print(f"Report ID: {report_id}") # Download the report content report_content = get_scan_report(report_id=report_id) with open("scan_report.pdf", "wb") as f: f.write(report_content) print("Report saved to scan_report.pdf") ```