### Authentication Examples Source: https://pan.dev/prisma-cloud/api/cwpp Examples of how to authenticate API requests using cURL, with options for authentication tokens, username/password, or username only. ```APIDOC ## Authentication Examples ### Description Examples of how to authenticate API requests using cURL. You can use an authentication token, username and password, or username only. ### Method POST (for authentication token generation) ### Endpoint `/api/vVERSION/authenticate` (example endpoint for token generation) ### Parameters #### Query Parameters None #### Request Body None (for token generation, typically requires username/password in the request or headers) ### Request Example (Using Authentication Token) ```bash curl -k \ -H 'Authorization: Bearer ' \ -X POST \ https:///api/vVERSION/ ``` ### Request Example (Using Username and Password) ```bash curl -k \ -u \ -p \ -X POST \ https:///api/vVERSION/ ``` ### Request Example (Using Username Only) ```bash curl -k \ -u \ -X POST \ https:///api/vVERSION/ ``` ### Response #### Success Response (200) - **token** (string) - The authentication token. #### Response Example ```json { "token": "" } ``` ``` -------------------------------- ### Get Integration By ID - Go Example Source: https://pan.dev/prisma-cloud/api/cspm/get-integration-by-id Provides a Go code example for fetching integration details. This snippet shows how to construct and send an HTTP GET request with custom headers. ```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { url := "https://api.prismacloud.io/integration/:id" client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println(err) return } req.Header.Add("Accept", "application/json; charset=UTF-8") req.Header.Add("x-redlock-auth", "") resp, err := client.Do(req) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Startup Binary Details Source: https://pan.dev/prisma-cloud/api/cwpp/get-policies-firewall-app-host-impacted Provides information about startup binaries, including their names, paths, versions, and associated CVE counts. Also indicates if a package is missing and lists dependencies. ```json { "startupBinaries": [ { "altered": true, "cveCount": 0, "deps": ["string"], "fileMode": 0, "functionLayer": "string", "md5": "string", "missingPkg": true, "name": "string", "path": "string", "pkgRootDir": "string", "services": ["string"], "version": "string" } ] } ``` -------------------------------- ### Get Defender Install Bundle (cURL) Source: https://pan.dev/prisma-cloud/api/cwpp/get-defenders-install-bundle Example cURL command to retrieve the Defender install bundle. It requires authentication and specifies the console address. The response contains the base64 encoded certificate bundle and WebSocket address. ```bash $ curl -k \ -u \ -H 'Content-Type: application/json' \ -X GET \ "https:///api/v/defenders/install-bundle?consoleaddr=" ``` ```bash curl -L 'PATH_TO_CONSOLE/api/v34.03/defenders/install-bundle' \ -H 'Accept: application/json' ``` -------------------------------- ### Startup Binaries Source: https://pan.dev/prisma-cloud/api/cwpp/post-sandbox Information about binaries expected to run when a container is created from an image. ```APIDOC ## Startup Binaries Schema ### Description This schema describes binaries that are expected to run when a container is created from a specific image, including their details and dependencies. ### Method N/A (Schema definition) ### Endpoint N/A (Schema definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **startupBinaries** (array) - An array of objects, where each object represents a binary expected to run. - **altered** (boolean) - Indicates if the binary was installed from a package manager and modified/replaced. - **cveCount** (integer) - Total number of CVEs for this specific binary. - **deps** (string[]) - Third-party package files used by the binary. - **fileMode** (integer) - Represents the file's mode and permission bits. - **functionLayer** (string) - ID of the serverless layer in which the package was discovered. - **md5** (string) - MD5 hashset of the binary. - **missingPkg** (boolean) - Indicates if this binary is not related to any package. - **name** (string) - Name of the binary. - **path** (string) - Path of the binary. - **pkgRootDir** (string) - Path for searching packages used by the binary. - **services** (string[]) - Names of services which use the binary. - **version** (string) - Version of the binary. #### Response Example ```json { "startupBinaries": [ { "altered": false, "cveCount": 2, "deps": ["libssl.so", "libcrypto.so"], "fileMode": 493, "functionLayer": "layer-id-123", "md5": "abcdef1234567890abcdef1234567890", "missingPkg": false, "name": "nginx", "path": "/usr/sbin/nginx", "pkgRootDir": "/usr", "services": ["webserver"], "version": "1.20.1" } ] } ``` ``` -------------------------------- ### Startup Binaries Source: https://pan.dev/prisma-cloud/api/cwpp/get-tas-droplets Information about binaries expected to run when a container is created from an image, including their properties and dependencies. ```APIDOC ## Startup Binaries ### Description This section describes binaries that are expected to run when a container is created from an image. It includes details like their paths, versions, CVE counts, and dependencies. ### Request Body #### StartupBinaries - **startupBinaries** (object[]) - Optional - Binaries which are expected to run when the container is created from this image. - **altered** (boolean) - Optional - Indicates if the binary was installed from a package manager and modified/replaced (true) or not (false). - **cveCount** (integer) - Optional - Total number of CVEs for this specific binary. - **deps** (string[]) - Optional - Third-party package files which are used by the binary. - **fileMode** (integer) - Optional - Represents the file's mode and permission bits. - **functionLayer** (string) - Optional - ID of the serverless layer in which the package was discovered. - **md5** (string) - Optional - Md5 hashset of the binary. - **missingPkg** (boolean) - Optional - Indicates if this binary is not related to any package (true) or not (false). - **name** (string) - Optional - Name of the binary. - **path** (string) - Optional - Path is the path of the binary. - **pkgRootDir** (string) - Optional - Path for searching packages used by the binary. - **services** (string[]) - Optional - Names of services which use the binary. - **version** (string) - Optional - Version of the binary. ``` -------------------------------- ### Get All Groups (Python) Source: https://pan.dev/prisma-cloud/api/cwpp/get-groups Retrieves a list of all groups using Python. This example demonstrates how to make a GET request to the Prisma Cloud API endpoint for groups. Ensure you have the 'requests' library installed. ```python import requests url = "https:///api/v/groups" headers = { 'Content-Type': 'application/json' } response = requests.get(url, headers=headers, auth=('', '')) if response.status_code == 200: print(response.json()) else: print(f"Error: {response.status_code}") print(response.text) ``` -------------------------------- ### Startup Binaries and Tags Source: https://pan.dev/prisma-cloud/api/cwpp/post-coderepos-ci-evaluate Information about binaries expected to run on container startup and associated image tags. ```APIDOC ## Startup Binaries and Tags ### Description This section describes the binaries that are expected to run when a container is created from an image, including their properties and dependencies. It also details the associated image tags. ### Fields **startupBinaries** (object[]) - Binaries which are expected to run when the container is created from this image. - **altered** (boolean) - Indicates if the binary was installed from a package manager and modified/replaced (true) or not (false). - **cveCount** (integer) - Total number of CVEs for this specific binary. - **deps** (string[]) - Third-party package files which are used by the binary. - **fileMode** (integer) - Represents the file's mode and permission bits. - **functionLayer** (string) - ID of the serverless layer in which the package was discovered. - **md5** (string) - Md5 hashset of the binary. - **missingPkg** (boolean) - Indicates if this binary is not related to any package (true) or not (false). - **name** (string) - Name of the binary. - **path** (string) - Path is the path of the binary. - **pkgRootDir** (string) - Path for searching packages used by the binary. - **services** (string[]) - Names of services which use the binary. - **version** (string) - Version of the binary. **tags** (object[]) - Tags associated with the given image. - **digest** (string) - Image digest (requires V2 or later registry). - **id** (string) - ID of the image. - **registry** (string) - Registry name to which the image belongs. - **repo** (string) - Repository name to which the image belongs. ``` -------------------------------- ### Get Discovery Criteria (Node.js) Source: https://pan.dev/prisma-cloud/api/cspm/get-4 Node.js example using the `axios` library to fetch discovery criteria. This code snippet demonstrates setting up the request with headers and query parameters. Make sure to install `axios` (`npm install axios`). ```javascript const axios = require('axios'); const apiUrl = 'https://api.prismacloud.io/appid/api/v1/app/criteria'; const authToken = ''; const params = { fetch_deleted: false // Set to true to include deleted criteria }; const headers = { 'Accept': 'application/json', 'x-redlock-auth': authToken }; axios.get(apiUrl, { headers: headers, params: params }) .then(response => { console.log('Discovery Criteria:'); console.log(response.data); }) .catch(error => { if (error.response) { if (error.response.status === 401) { console.error('Error: Unauthorized. Please check your authentication token.'); } else if (error.response.status === 403) { console.error('Error: Forbidden. You do not have the required permissions.'); } else { console.error(`Error: ${error.response.status} - ${error.response.data}`); } } else if (error.request) { console.error('Error: No response received from server.'); } else { console.error('Error:', error.message); } }); ``` -------------------------------- ### Fetch Affected Packages by Licenses - Go Example Source: https://pan.dev/prisma-cloud/api/code/get-affected-resources-by-packages Illustrates how to call the Prisma Cloud API to retrieve affected packages using Go. This example shows setting up the HTTP client, request headers, and the JSON payload. ```go package main import ( "bytes" "fmt" "net/http" ) func main() { url := "https://api.prismacloud.io/code/api/v1/packagesAlerts/affectedByPackages" requestBody := []byte(`{ "packages": [ "string" ] }`) req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") rereq.Header.Set("authorization", "") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %s\n", err) return } defer resp.Body.Close() fmt.Printf("Status Code: %d\n", resp.StatusCode) // Process response body here } ``` -------------------------------- ### Get Discovery Criteria (Python) Source: https://pan.dev/prisma-cloud/api/cspm/get-4 Python script to retrieve discovery criteria using the `requests` library. This example shows how to construct the API request, including headers and query parameters. Ensure you have the `requests` library installed (`pip install requests`). ```python import requests api_url = "https://api.prismacloud.io/appid/api/v1/app/criteria" headers = { "Accept": "application/json", "x-redlock-auth": "" } params = { "fetch_deleted": False # Set to True to include deleted criteria } response = requests.get(api_url, headers=headers, params=params) if response.status_code == 200: print("Discovery Criteria:") print(response.json()) elif response.status_code == 401: print("Error: Unauthorized. Please check your authentication token.") elif response.status_code == 403: print("Error: Forbidden. You do not have the required permissions.") else: print(f"Error: {response.status_code} - {response.text}") ``` -------------------------------- ### Get All Groups (Node.js) Source: https://pan.dev/prisma-cloud/api/cwpp/get-groups Retrieves a list of all groups using Node.js. This example utilizes the 'axios' library to make an HTTP GET request to the Prisma Cloud API. Ensure 'axios' is installed via npm. ```javascript const axios = require('axios'); const url = 'https:///api/v/groups'; const username = ''; const password = ''; axios.get(url, { headers: { 'Content-Type': 'application/json' }, auth: { username: username, password: password } }) .then(response => { console.log(response.data); }) .catch(error => { console.error(`Error: ${error.response.status}`); console.error(error.response.data); }); ``` -------------------------------- ### Startup Binary Information Source: https://pan.dev/prisma-cloud/api/cwpp/post-sandbox This structure details information about binaries that start automatically on a system. It includes flags for whether the binary has been altered, its CVE count, and its file path. ```json { "altered": true, "cveCount": 0, "deps": [ "string" ], "fileMode": 0, "functionLayer": "string", "md5": "string", "missingPkg": true, "name": "string", "path": "string", "pkgRootDir": "string" } ``` -------------------------------- ### Retrieve Runtime Host Audits using Node.js Source: https://pan.dev/prisma-cloud/api/cwpp/get-audits-runtime-host This Node.js example fetches runtime host audit data from the Prisma Cloud API using the 'axios' library. It demonstrates setting headers and query parameters for the GET request. Ensure you have 'axios' installed (`npm install axios`). ```javascript const axios = require('axios'); const apiUrl = 'PATH_TO_CONSOLE/api/v34.03/audits/runtime/host'; const headers = { 'Accept': 'application/json' }; const params = { limit: 100, offset: 0, sort: 'time', reverse: 'true' }; axios.get(apiUrl, { headers: headers, params: params }) .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching data:', error.response ? error.response.data : error.message); }); ``` -------------------------------- ### Fetch CVE Overview using Go Source: https://pan.dev/prisma-cloud/api/cspm/cve-overview-v-3 Example of how to fetch CVE overview data from the Prisma Cloud API using Go. This code demonstrates setting up the HTTP request, marshalling the JSON payload, and unmarshalling the response. ```go package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { url := "https://pan.dev/uve/api/v2/cve-overview" payload := map[string]interface{}{ "assetTypes": "package,serverlessFunction,iac,deployedImage,vmImage,registryImage,host", "lifeCycle": "code,build,deploy,run", "severities": "critical,high,low,medium,informational", "accountGroups": []string{"string"}, "accountIds": []string{"string"}, "clusters": []string{"string"}, "clusterNamespaces": []string{"string"} } jsonPayload, err := json.Marshal(payload) if err != nil { fmt.Printf("Error marshalling JSON: %v\n", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload)) if err != nil { fmt.Printf("Error creating request: %v\n", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %v\n", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %v\n", err) return } if resp.StatusCode == 200 { fmt.Println(string(body)) } else { fmt.Printf("Error: %d\n%s\n", resp.StatusCode, string(body)) } } ``` -------------------------------- ### Get Host Firewall Policies (Python) Source: https://pan.dev/prisma-cloud/api/cwpp/get-policies-firewall-app-host Fetches host firewall policies using Python's requests library. This example demonstrates how to make a GET request to the Prisma Cloud API endpoint for host firewall policies and handle the JSON response. It requires the 'requests' library to be installed. ```python import requests url = "PATH_TO_CONSOLE/api/v34.03/policies/firewall/app/host" headers = { 'Accept': 'application/json' } response = requests.get(url, headers=headers) if response.status_code == 200: print(response.json()) else: print(f"Error: {response.status_code}") ``` -------------------------------- ### Get Compliance Trend API Request Examples Source: https://pan.dev/prisma-cloud/api/cspm/get-compliance-posture-trend Examples of how to call the 'Get Compliance Trend' API endpoint using different programming languages. These examples demonstrate authentication and parameter usage. ```curl curl -L 'https://api.prismacloud.io/compliance/posture/trend' \ -H 'Accept: application/json; charset=UTF-8' \ -H 'x-redlock-auth: ' ``` ```python # Python example for Get Compliance Trend API # Note: Actual Python code would require an HTTP client library like 'requests' # This is a placeholder to indicate the availability of Python examples. ``` ```go // Go example for Get Compliance Trend API // Note: Actual Go code would require an HTTP client library. // This is a placeholder to indicate the availability of Go examples. ``` ```nodejs // Node.js example for Get Compliance Trend API // Note: Actual Node.js code would require an HTTP client library like 'axios' or 'node-fetch'. // This is a placeholder to indicate the availability of Node.js examples. ``` ```csharp // C# example for Get Compliance Trend API // Note: Actual C# code would require an HttpClient. // This is a placeholder to indicate the availability of C# examples. ``` ```php // PHP example for Get Compliance Trend API // Note: Actual PHP code would typically use cURL or a library like Guzzle. // This is a placeholder to indicate the availability of PHP examples. ``` -------------------------------- ### Configure Defender Features (Go) Source: https://pan.dev/prisma-cloud/api/cwpp/post-defenders-id-features This Go program illustrates how to configure defender features by sending a POST request to the Prisma Cloud API. It includes setting up the request body, headers, and handling the API response. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "PATH_TO_CONSOLE/api/v34.03/defenders/{defender_id}/features" payload := map[string]interface{}{ "clusterMonitoring": true, "proxyListenerType": "string", } jsonPayload, _ := json.Marshal(payload) req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() var result map[string]interface{} json.NewDecoder(res.Body).Decode(&result) fmt.Println(result) } ``` -------------------------------- ### List Integrations API Examples (cURL, Python, Go, Node.js, C#, PHP) Source: https://pan.dev/prisma-cloud/api/cspm/get-all-integrations-v-1 Provides code examples for making the 'List Integrations' GET request using cURL, Python, Go, Node.js, C#, and PHP. These examples demonstrate how to construct the request, including setting headers and parameters. ```curl curl -L 'https://api.prismacloud.io/api/v1/tenant/:prismaId/integration' \ -H 'Accept: application/json' \ -H 'x-redlock-auth: ' ``` ```python # Python example would go here, demonstrating the GET request ``` ```go // Go example would go here, demonstrating the GET request ``` ```nodejs // Node.js example would go here, demonstrating the GET request ``` ```csharp // C# example would go here, demonstrating the GET request ``` ```php // PHP example would go here, demonstrating the GET request ``` -------------------------------- ### Get Convertible Assets API - Go Example Source: https://pan.dev/prisma-cloud/api/cspm/list-assets Example of how to call the Get Convertible Assets API using Go. This illustrates making an HTTP GET request with custom headers. ```go // Placeholder for Go code example ``` -------------------------------- ### Get Vulnerabilities Trend Request Examples Source: https://pan.dev/prisma-cloud/api/cspm/value-widgets-get-vulnerabilities-trend Examples of how to call the Get Vulnerabilities Trend API endpoint using cURL and various programming languages. These examples demonstrate how to construct the request body and include necessary headers. ```curl curl -L 'https://api.prismacloud.io/adoptionadvisor/api/v2/compute/vulnerabilities/trend' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json; charset=UTF-8' \ -H 'x-redlock-auth: ' \ -d '{ "timeRange": { "relativeTimeType": "BACKWARD", "type": "relative", "value": { "amount": 0, "unit": "minute" } } }' ``` ```python import requests url = "https://api.prismacloud.io/adoptionadvisor/api/v2/compute/vulnerabilities/trend" headers = { "Content-Type": "application/json", "Accept": "application/json; charset=UTF-8", "x-redlock-auth": "" } payload = { "timeRange": { "relativeTimeType": "BACKWARD", "type": "relative", "value": { "amount": 0, "unit": "minute" } } } response = requests.post(url, headers=headers, json=payload) print(response.json()) ``` ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://api.prismacloud.io/adoptionadvisor/api/v2/compute/vulnerabilities/trend" requestBody := map[string]interface{}{ "timeRange": map[string]interface{}{ "relativeTimeType": "BACKWARD", "type": "relative", "value": map[string]interface{}{ "amount": 0, "unit": "minute" } } } jsonBody, err := json.Marshal(requestBody) if err != nil { fmt.Println("Error marshalling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json; charset=UTF-8") req.Header.Set("x-redlock-auth", "") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() var result map[string]interface{} err = json.NewDecoder(res.Body).Decode(&result) if err != nil { fmt.Println("Error decoding response:", err) return } fmt.Println(result) } ``` ```nodejs const fetch = require('node-fetch'); const url = 'https://api.prismacloud.io/adoptionadvisor/api/v2/compute/vulnerabilities/trend'; const apiKey = ''; const requestBody = { "timeRange": { "relativeTimeType": "BACKWARD", "type": "relative", "value": { "amount": 0, "unit": "minute" } } }; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json; charset=UTF-8', 'x-redlock-auth': apiKey }, body: JSON.stringify(requestBody) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; public class VulnerabilityTrend { public class TimeRangeValue { public int amount { get; set; } public string unit { get; set; } } public class TimeRange { public string relativeTimeType { get; set; } public string type { get; set; } public TimeRangeValue value { get; set; } } public class RequestBody { public TimeRange timeRange { get; set; } } public static async Task Main(string[] args) { using (var httpClient = new HttpClient()) { var url = "https://api.prismacloud.io/adoptionadvisor/api/v2/compute/vulnerabilities/trend"; var apiKey = ""; var requestBody = new RequestBody { timeRange = new TimeRange { relativeTimeType = "BACKWARD", type = "relative", value = new TimeRangeValue { amount = 0, unit = "minute" } } }; var json = System.Text.Json.JsonSerializer.Serialize(requestBody); var content = new StringContent(json, Encoding.UTF8, "application/json"); httpClient.DefaultRequestHeaders.Add("Accept", "application/json; charset=UTF-8"); httpClient.DefaultRequestHeaders.Add("x-redlock-auth", apiKey); var response = await httpClient.PostAsync(url, content); var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` ```php '; $requestBody = [ 'timeRange' => [ 'relativeTimeType' => 'BACKWARD', 'type' => 'relative', 'value' => [ 'amount' => 0, 'unit' => 'minute' ] ] ]; $options = [ 'http' => [ 'method' => 'POST', 'header' => "Content-Type: application/json\r\n" . "Accept: application/json; charset=UTF-8\r\n" . "x-redlock-auth: " . $apiKey . "\r\n", 'content' => json_encode($requestBody), 'ignore_errors' => true ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); if ($result === FALSE) { die("Error fetching data"); } var_dump(json_decode($result, true)); ?> ``` -------------------------------- ### Fetch Affected Packages by Licenses - PHP Example Source: https://pan.dev/prisma-cloud/api/code/get-affected-resources-by-packages A PHP example demonstrating how to make an API request to fetch packages affected by licenses using cURL. It shows setting up the request URL, headers, and the JSON payload. ```php '; // Replace with your actual authorization token $data = array( 'packages' => array('string') ); $payload = json_encode($data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Accept: application/json', 'authorization: ' . $authorization )); $response = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } else { echo $response; } certify_close($ch); ?> ``` -------------------------------- ### Get Collections cURL Request Example (Simplified) Source: https://pan.dev/prisma-cloud/api/cwpp/get-collections This cURL command provides a simplified example for retrieving collections. It uses a GET request to the API endpoint and includes the Accept header for JSON responses. This is a basic example of how to fetch the collection data. ```cURL curl -L 'PATH_TO_CONSOLE/api/v34.03/collections' \ -H 'Accept: application/json' ``` -------------------------------- ### Get Top Vulnerable Repositories (Go) Source: https://pan.dev/prisma-cloud/api/code/get-dashboard-top-vulnerable-repositories-data This Go program demonstrates how to fetch top vulnerable repositories using the Prisma Cloud API. It constructs the necessary HTTP request with headers and a JSON body. You'll need to replace placeholders like `` with your actual credentials. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://api.prismacloud.io/code/api/v2/dashboard/top-vulnerable-repositories" token := "" payload := map[string]interface{}{ "codeCategories": []string{"iac"}, "repositories": []string{"string"}, "severities": []string{"INFO"}, "size": 0, } payloadBytes, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshaling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") req.Header.Set("authorization", token) client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { var result map[string]interface{} if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { fmt.Println("Error decoding response:", err) } else { fmt.Println(result) } } else { fmt.Printf("Error: %d %s\n", resp.StatusCode, resp.Status) } } ``` -------------------------------- ### API Request Example (Go) Source: https://pan.dev/prisma-cloud/api/code/get-repository A Go code example for making a GET request to retrieve a single repository. It demonstrates setting headers and query parameters using the 'net/http' package. ```go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { url := "https://pan.dev/code/code/api/v1/repositories/repository" req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println(err) return } req.Header.Set("Accept", "application/json") req.Header.Set("authorization", "") q := req.URL.Query() q.Add("repositoryId", "") req.URL.RawQuery = q.Encode() client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Get Account Status Request Examples Source: https://pan.dev/prisma-cloud/api/cspm/list-cloud-account-status-details Provides examples of how to make a request to the Get Account Status API endpoint using different programming languages and tools. These examples demonstrate how to set the necessary headers, including the authorization token. ```curl curl -L 'https://api.prismacloud.io/account/:accountId/config/status' \ -H 'Accept: application/json; charset=UTF-8' \ -H 'x-redlock-auth: ' ``` ```python # Python example would go here ``` ```go // Go example would go here ``` ```nodejs // Node.js example would go here ``` ```csharp // C# example would go here ``` ```php // PHP example would go here ``` -------------------------------- ### Prisma Cloud API: Authorization Header Example (Go) Source: https://pan.dev/prisma-cloud/api/code/get-affected-resources-by-licenses Example of setting the authorization header in a Go request to the Prisma Cloud API. ```go package main import ( "fmt" "net/http" ) func main() { client := &http.Client{} req, err := http.NewRequest("GET", "https://api.prismacloud.io/code/api/v1/packagesAlerts/affectedByLicenses", nil) if err != nil { fmt.Println(err) return } req.Header.Add("Content-Type", "application/json") req.Header.Add("Accept", "application/json") req.Header.Add("authorization", "") res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() fmt.Println(res.StatusCode) } ``` -------------------------------- ### Get All Permission Groups - Example Requests Source: https://pan.dev/prisma-cloud/api/cspm/get-all Examples of how to call the 'Get All Permission Groups' API endpoint using cURL, Python, Go, Node.js, C#, and PHP. These examples demonstrate how to include the necessary authorization header and optional query parameters. ```curl curl -L 'https://api.prismacloud.io/authz/v1/permission_group' \ -H 'Accept: application/json' \ -H 'x-redlock-auth: ' ``` ```python # Python example would go here, demonstrating API call with requests library ``` ```go // Go example would go here, demonstrating API call with net/http ``` ```nodejs // Node.js example would go here, demonstrating API call with axios or fetch ``` ```csharp // C# example would go here, demonstrating API call with HttpClient ``` ```php // PHP example would go here, demonstrating API call with cURL or Guzzle ``` -------------------------------- ### Get Integration By ID - C# Example Source: https://pan.dev/prisma-cloud/api/cspm/get-integration-by-id Shows a C# code snippet for fetching integration details. This example uses the 'HttpClient' class to perform the GET request. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class IntegrationClient { public static async Task GetIntegrationAsync(string id, string authToken) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://api.prismacloud.io"); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("x-redlock-auth", authToken); HttpResponseMessage response = await client.GetAsync($"integration/{id}"); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Error: {response.StatusCode}"); } } } public static async Task Main(string[] args) { string integrationId = ":id"; // Replace with actual ID string auth = ""; // Replace with actual token await GetIntegrationAsync(integrationId, auth); } } ``` -------------------------------- ### Download Application Details Request Examples Source: https://pan.dev/prisma-cloud/api/cspm/app-details-csv-download Examples of how to call the 'Download Application Details' endpoint using cURL, Python, Go, Node.js, C#, and PHP. These examples demonstrate how to include the necessary headers and parameters for authentication and request execution. ```curl curl -L 'https://api.prismacloud.io/appid/api/v1/download/app/:id' \ -H 'Accept: application/octet-stream' \ -H 'x-redlock-auth: ' ``` ```python # Python example not provided in the source text. ``` ```go // Go example not provided in the source text. ``` ```nodejs // Node.js example not provided in the source text. ``` ```csharp // C# example not provided in the source text. ``` ```php // PHP example not provided in the source text. ``` -------------------------------- ### Get Convertible Assets API - C# Example Source: https://pan.dev/prisma-cloud/api/cspm/list-assets Example of how to call the Get Convertible Assets API using C#. This shows how to construct an HttpClient request with the required headers. ```csharp // Placeholder for C# code example ``` -------------------------------- ### Download SBOM VMs API Request Examples (curl, python, go, nodejs, csharp, php) Source: https://pan.dev/prisma-cloud/api/cwpp/get-sbom-download-vms Provides example code snippets for downloading SBOM files for VMs using various programming languages and tools. These examples demonstrate how to construct the API request with different query parameters. ```curl curl -L 'PATH_TO_CONSOLE/api/v34.03/sbom/download/vms' ``` ```python # Python example for downloading SBOM VMs # Requires 'requests' library import requests url = "PATH_TO_CONSOLE/api/v34.03/sbom/download/vms" headers = { "x-prisma-cloud-target-env": '{"permission":"monitorImages"}' } params = { "offset": 0, "limit": 100, "sbomFormat": "json" } response = requests.get(url, headers=headers, params=params) if response.status_code == 200: with open("sbom.json", "wb") as f: f.write(response.content) print("SBOM downloaded successfully.") else: print(f"Error downloading SBOM: {response.status_code}") ``` ```go // Go example for downloading SBOM VMs package main import ( "fmt" "io" "net/http" "os" ) func main() { url := "PATH_TO_CONSOLE/api/v34.03/sbom/download/vms" client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Add("x-prisma-cloud-target-env", `{"permission":"monitorImages"}`) q := req.URL.Query() q.Add("offset", "0") q.Add("limit", "100") q.Add("sbomFormat", "json") req.URL.RawQuery = q.Encode() res, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %s\n", err) return } defer res.Body.Close() if res.StatusCode == http.StatusOK { file, err := os.Create("sbom.json") if err != nil { fmt.Printf("Error creating file: %s\n", err) return } defer file.Close() _, err = io.Copy(file, res.Body) if err != nil { fmt.Printf("Error writing to file: %s\n", err) return } fmt.Println("SBOM downloaded successfully.") } else { fmt.Printf("Error downloading SBOM: %d\n", res.StatusCode) } } ``` ```nodejs // Node.js example for downloading SBOM VMs const axios = require('axios'); const fs = require('fs'); const url = 'PATH_TO_CONSOLE/api/v34.03/sbom/download/vms'; const headers = { 'x-prisma-cloud-target-env': JSON.stringify({ permission: 'monitorImages' }) }; const params = { offset: 0, limit: 100, sbomFormat: 'json' }; axios({ method: 'get', url: url, headers: headers, params: params, responseType: 'stream' }) .then(response => { const writer = fs.createWriteStream('sbom.json'); response.data.pipe(writer); writer.on('finish', () => console.log('SBOM downloaded successfully.')); writer.on('error', (err) => console.error('Error writing to file:', err)); }) .catch(error => { console.error('Error downloading SBOM:', error.response ? error.response.status : error.message); }); ``` ```csharp // C# example for downloading SBOM VMs using System; using System.IO; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; public class SbomDownloader { public static async Task DownloadSbomAsync() { using (var httpClient = new HttpClient()) { var url = "PATH_TO_CONSOLE/api/v34.03/sbom/download/vms"; var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Add("x-prisma-cloud-target-env", JsonSerializer.Serialize(new { permission = "monitorImages" })); var queryParams = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query); queryParams.Add("offset", "0"); queryParams.Add("limit", "100"); queryParams.Add("sbomFormat", "json"); request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Split('?')[0] + "?" + queryParams.ToString()); try { var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStreamAsync(); using (var fileStream = new FileStream("sbom.json", FileMode.Create, FileAccess.Write, FileShare.None)) { await content.CopyToAsync(fileStream); } Console.WriteLine("SBOM downloaded successfully."); } else { Console.WriteLine($"Error downloading SBOM: {response.StatusCode}"); } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } } } ``` ```php // PHP example for downloading SBOM VMs 0, 'limit' => 100, 'sbomFormat' => 'json' ]; $queryString = http_build_query($queryParams); $fullUrl = $url . '?' . $queryString; $ch = curl_init($fullUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); if (curl_errno($ch)) { echo 'Curl error: ' . curl_error($ch); } else { if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) { file_put_contents('sbom.json', $response); echo 'SBOM downloaded successfully.'; } else { echo 'Error downloading SBOM: HTTP code ' . curl_getinfo($ch, CURLINFO_HTTP_CODE); } } curl_close($ch); ?> ```