Integration Examples
This guide provides complete code examples for integrating with the CyberSecFeed API in popular programming languages. All examples include proper authentication, error handling, and best practices.
Python
Basic Integration
import requests
import json
from typing import Optional, Dict, List
class CyberSecFeedClient:
"""Simple Python client for CyberSecFeed API"""
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.cybersecfeed.com/api/v1"
self.session = requests.Session()
self.session.headers.update({
"X-API-Key": api_key,
"Content-Type": "application/json"
})
def get_cve(self, cve_id: str, include_acsc: bool = False) -> Optional[Dict]:
"""Retrieve details for a specific CVE"""
params = {}
if include_acsc:
params['include'] = 'acsc'
try:
response = self.session.get(f"{self.base_url}/cve/{cve_id}", params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching CVE {cve_id}: {e}")
return None
def search_cves(self, **params) -> Optional[Dict]:
"""Search CVEs with filters"""
try:
response = self.session.get(f"{self.base_url}/cves", params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error searching CVEs: {e}")
return None
def get_kev(self, limit: int = 20) -> Optional[Dict]:
"""Get Known Exploited Vulnerabilities"""
try:
response = self.session.get(
f"{self.base_url}/kev",
params={"limit": limit}
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching KEV: {e}")
return None
# Usage example
if __name__ == "__main__":
client = CyberSecFeedClient("your-api-key-here")
# Get specific CVE with ACSC data
cve_data = client.get_cve("CVE-2024-0001", include_acsc=True)
if cve_data:
cve = cve_data["data"]["cve"]
print(f"CVE: {cve['id']}")
print(f"Severity: {cve.get('cvss', {}).get('baseSeverity', 'Unknown')}")
# Check if actively exploited
if "kev" in cve:
print("⚠️ ACTIVELY EXPLOITED!")
# Check for ACSC notices
if "acsc" in cve:
print(f"🇦🇺 {len(cve['acsc'])} ACSC notice(s) available")
# Search for critical vulnerabilities with ACSC data
results = client.search_cves(
severity_min=9.0,
published_after="2024-01-01",
include="acsc",
limit=10
)
if results:
for cve in results["data"]["cves"]:
print(f"{cve['id']} - Score: {cve['cvss']['baseScore']}")
Advanced Example with Async
import asyncio
import aiohttp
from typing import List, Dict
import json
class AsyncCyberSecFeedClient:
"""Asynchronous client for high-performance operations"""
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.cybersecfeed.com/api/v1"
self.headers = {"X-API-Key": api_key}
async def fetch_cve(self, session: aiohttp.ClientSession, cve_id: str, include_acsc: bool = False) -> Dict:
"""Fetch single CVE asynchronously"""
params = {'include': 'acsc'} if include_acsc else {}
url = f"{self.base_url}/cve/{cve_id}"
async with session.get(url, params=params) as response:
return await response.json()
async def batch_fetch_cves(self, cve_ids: List[str]) -> List[Dict]:
"""Fetch multiple CVEs concurrently"""
async with aiohttp.ClientSession(headers=self.headers) as session:
tasks = [self.fetch_cve(session, cve_id) for cve_id in cve_ids]
return await asyncio.gather(*tasks, return_exceptions=True)
async def monitor_high_risk_cves(self):
"""Monitor for high-risk CVEs"""
async with aiohttp.ClientSession(headers=self.headers) as session:
params = {
"severity_min": 8.0,
"kev": "true",
"include": "acsc",
"limit": 50
}
url = f"{self.base_url}/cves"
async with session.get(url, params=params) as response:
data = await response.json()
high_risk = []
for cve in data["data"]["cves"]:
if cve.get("epss", {}).get("score", 0) > 0.7:
high_risk.append(cve)
return high_risk
# Usage
async def main():
client = AsyncCyberSecFeedClient("your-api-key-here")
# Batch fetch
cve_ids = ["CVE-2024-0001", "CVE-2024-0002", "CVE-2024-0003"]
results = await client.batch_fetch_cves(cve_ids)
# Monitor high risk
high_risk = await client.monitor_high_risk_cves()
print(f"Found {len(high_risk)} high-risk CVEs")
if __name__ == "__main__":
asyncio.run(main())
JavaScript/Node.js
Basic Integration
const axios = require('axios');
class CyberSecFeedClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseURL = 'https://api.cybersecfeed.com/api/v1';
// Create axios instance with default config
this.client = axios.create({
baseURL: this.baseURL,
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
},
timeout: 30000, // 30 seconds
});
}
async getCVE(cveId) {
try {
const response = await this.client.get(`/cve/${cveId}`);
return response.data;
} catch (error) {
console.error(`Error fetching CVE ${cveId}:`, error.message);
throw error;
}
}
async searchCVEs(params = {}) {
try {
const response = await this.client.get('/cves', { params });
return response.data;
} catch (error) {
console.error('Error searching CVEs:', error.message);
throw error;
}
}
async getKEV(limit = 20) {
try {
const response = await this.client.get('/kev', {
params: { limit },
});
return response.data;
} catch (error) {
console.error('Error fetching KEV:', error.message);
throw error;
}
}
async getStats() {
try {
const response = await this.client.get('/stats');
return response.data;
} catch (error) {
console.error('Error fetching stats:', error.message);
throw error;
}
}
}
// Usage example
async function main() {
const client = new CyberSecFeedClient('your-api-key-here');
try {
// Get specific CVE
const cveData = await client.getCVE('CVE-2024-0001');
const cve = cveData.data.cve;
console.log(`CVE: ${cve.id}`);
console.log(`Severity: ${cve.cvss?.baseSeverity || 'Unknown'}`);
if (cve.kev) {
console.log('⚠️ ACTIVELY EXPLOITED!');
console.log(`Added to KEV: ${cve.kev.dateAdded}`);
}
// Search for recent critical vulnerabilities
const searchResults = await client.searchCVEs({
severity_min: 9.0,
published_after: '2024-01-01',
limit: 10,
});
console.log(`\nFound ${searchResults.data.cves.length} critical CVEs:`);
searchResults.data.cves.forEach((cve) => {
console.log(`- ${cve.id}: ${cve.cvss.baseScore}`);
});
} catch (error) {
console.error('Error:', error.message);
}
}
main();
Browser-Based Example
// Browser-based integration (modern browsers with fetch API)
class CyberSecFeedBrowserClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseURL = 'https://api.cybersecfeed.com/api/v1';
}
async request(endpoint, params = {}) {
const url = new URL(`${this.baseURL}${endpoint}`);
// Add query parameters
Object.keys(params).forEach((key) => {
if (params[key] !== undefined) {
url.searchParams.append(key, params[key]);
}
});
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'X-API-Key': this.apiKey,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
getCVE(cveId, options = {}) {
const params = {};
if (options.includeACSC) {
params.include = 'acsc';
}
return this.request(`/cve/${cveId}`, params);
}
searchCVEs(params) {
return this.request('/cves', params);
}
getKEV(params) {
return this.request('/kev', params);
}
}
// Usage in browser
const client = new CyberSecFeedBrowserClient('your-api-key-here');
// Example: Display high-risk CVEs in a table
async function displayHighRiskCVEs() {
try {
const response = await client.searchCVEs({
severity_min: 8.0,
epss_min: 0.5,
include: 'acsc',
limit: 20,
});
const tableBody = document.getElementById('cve-table-body');
tableBody.innerHTML = '';
response.data.cves.forEach((cve) => {
const row = tableBody.insertRow();
row.insertCell(0).textContent = cve.id;
row.insertCell(1).textContent = cve.cvss.baseScore;
row.insertCell(2).textContent = cve.epss?.score || 'N/A';
row.insertCell(3).textContent = cve.kev ? 'YES' : 'NO';
});
} catch (error) {
console.error('Failed to load CVEs:', error);
}
}
Go
Basic Integration
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
// CyberSecFeedClient represents the API client
type CyberSecFeedClient struct {
APIKey string
BaseURL string
HTTPClient *http.Client
}
// CVEResponse represents the API response structure
type CVEResponse struct {
Data struct {
CVE struct {
ID string `json:"id"`
Published time.Time `json:"published"`
LastModified time.Time `json:"lastModified"`
Description string `json:"description"`
CVSS struct {
BaseScore float64 `json:"baseScore"`
BaseSeverity string `json:"baseSeverity"`
} `json:"cvss"`
KEV *struct {
DateAdded string `json:"dateAdded"`
KnownRansomware bool `json:"knownRansomware"`
} `json:"kev,omitempty"`
EPSS *struct {
Score float64 `json:"score"`
Percentile float64 `json:"percentile"`
} `json:"epss,omitempty"`
} `json:"cve"`
} `json:"data"`
Meta struct {
Timestamp time.Time `json:"timestamp"`
Version string `json:"version"`
CorrelationID string `json:"correlationId"`
} `json:"meta"`
}
// NewClient creates a new CyberSecFeed API client
func NewClient(apiKey string) *CyberSecFeedClient {
return &CyberSecFeedClient{
APIKey: apiKey,
BaseURL: "https://api.cybersecfeed.com/api/v1",
HTTPClient: &http.Client{
Timeout: 30 * time.Second,
},
}
}
// GetCVE retrieves a specific CVE
func (c *CyberSecFeedClient) GetCVE(cveID string) (*CVEResponse, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/cve/%s", c.BaseURL, cveID), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-Key", c.APIKey)
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("API error: %d - %s", resp.StatusCode, string(body))
}
var cveResp CVEResponse
if err := json.NewDecoder(resp.Body).Decode(&cveResp); err != nil {
return nil, err
}
return &cveResp, nil
}
// SearchCVEs searches for CVEs with filters
func (c *CyberSecFeedClient) SearchCVEs(params map[string]string) (interface{}, error) {
u, err := url.Parse(fmt.Sprintf("%s/cves", c.BaseURL))
if err != nil {
return nil, err
}
q := u.Query()
for key, value := range params {
q.Set(key, value)
}
u.RawQuery = q.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-Key", c.APIKey)
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
func main() {
client := NewClient("your-api-key-here")
// Get specific CVE
cveResp, err := client.GetCVE("CVE-2024-0001")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
cve := cveResp.Data.CVE
fmt.Printf("CVE: %s\n", cve.ID)
fmt.Printf("Severity: %s (%.1f)\n", cve.CVSS.BaseSeverity, cve.CVSS.BaseScore)
if cve.KEV != nil {
fmt.Println("⚠️ ACTIVELY EXPLOITED!")
fmt.Printf("Added to KEV: %s\n", cve.KEV.DateAdded)
}
// Search for critical CVEs
params := map[string]string{
"severity_min": "9.0",
"published_after": "2024-01-01",
"limit": "10",
}
results, err := client.SearchCVEs(params)
if err != nil {
fmt.Printf("Search error: %v\n", err)
return
}
fmt.Printf("\nSearch results: %v\n", results)
}
PowerShell
Basic Integration
# CyberSecFeed PowerShell Module
function Initialize-CyberSecFeedClient {
param(
[Parameter(Mandatory=$true)]
[string]$ApiKey
)
$script:CyberSecFeedApiKey = $ApiKey
$script:CyberSecFeedBaseUrl = "https://api.cybersecfeed.com/api/v1"
}
function Get-CyberSecFeedCVE {
param(
[Parameter(Mandatory=$true)]
[string]$CVEId,
[switch]$IncludeACSC
)
$headers = @{
"X-API-Key" = $script:CyberSecFeedApiKey
"Content-Type" = "application/json"
}
$params = @{}
if ($IncludeACSC) {
$params.include = 'acsc'
}
try {
$response = Invoke-RestMethod `
-Uri "$script:CyberSecFeedBaseUrl/cve/$CVEId" `
-Headers $headers `
-Method Get `
-Body $params
return $response.data.cve
}
catch {
Write-Error "Failed to fetch CVE: $_"
return $null
}
}
function Search-CyberSecFeedCVEs {
param(
[decimal]$SeverityMin,
[decimal]$SeverityMax,
[string]$PublishedAfter,
[string]$PublishedBefore,
[bool]$KEV,
[decimal]$EPSSMin,
[switch]$IncludeACSC,
[int]$Limit = 20
)
$headers = @{
"X-API-Key" = $script:CyberSecFeedApiKey
"Content-Type" = "application/json"
}
$params = @{}
if ($SeverityMin) { $params.severity_min = $SeverityMin }
if ($SeverityMax) { $params.severity_max = $SeverityMax }
if ($PublishedAfter) { $params.published_after = $PublishedAfter }
if ($PublishedBefore) { $params.published_before = $PublishedBefore }
if ($PSBoundParameters.ContainsKey('KEV')) { $params.kev = $KEV.ToString().ToLower() }
if ($EPSSMin) { $params.epss_min = $EPSSMin }
if ($IncludeACSC) { $params.include = 'acsc' }
$params.limit = $Limit
try {
$response = Invoke-RestMethod `
-Uri "$script:CyberSecFeedBaseUrl/cves" `
-Headers $headers `
-Method Get `
-Body $params
return $response.data.cves
}
catch {
Write-Error "Failed to search CVEs: $_"
return @()
}
}
function Get-CyberSecFeedKEV {
param(
[int]$Limit = 20,
[bool]$Ransomware
)
$headers = @{
"X-API-Key" = $script:CyberSecFeedApiKey
"Content-Type" = "application/json"
}
$params = @{ limit = $Limit }
if ($PSBoundParameters.ContainsKey('Ransomware')) {
$params.ransomware = $Ransomware.ToString().ToLower()
}
try {
$response = Invoke-RestMethod `
-Uri "$script:CyberSecFeedBaseUrl/kev" `
-Headers $headers `
-Method Get `
-Body $params
return $response.data.vulnerabilities
}
catch {
Write-Error "Failed to fetch KEV: $_"
return @()
}
}
# Usage examples
Initialize-CyberSecFeedClient -ApiKey "your-api-key-here"
# Get specific CVE with ACSC data
$cve = Get-CyberSecFeedCVE -CVEId "CVE-2024-0001" -IncludeACSC
if ($cve) {
Write-Host "CVE: $($cve.id)"
Write-Host "Severity: $($cve.cvss.baseSeverity) ($($cve.cvss.baseScore))"
if ($cve.kev) {
Write-Host "⚠️ ACTIVELY EXPLOITED!" -ForegroundColor Red
Write-Host "Added to KEV: $($cve.kev.dateAdded)"
}
if ($cve.acsc) {
Write-Host "🇦🇺 $($cve.acsc.Count) ACSC notice(s) available" -ForegroundColor Blue
}
}
# Search for critical CVEs with ACSC data
$criticalCVEs = Search-CyberSecFeedCVEs `
-SeverityMin 9.0 `
-PublishedAfter "2024-01-01" `
-IncludeACSC `
-Limit 10
Write-Host "`nCritical CVEs:"
$criticalCVEs | ForEach-Object {
Write-Host "- $($_.id): Score $($_.cvss.baseScore)"
}
# Get ransomware-related KEVs
$ransomwareKEVs = Get-CyberSecFeedKEV -Ransomware $true -Limit 5
Write-Host "`nRansomware-related KEVs: $($ransomwareKEVs.Count)"
Advanced PowerShell Script
# Advanced vulnerability assessment script
function Get-VulnerabilityRiskReport {
param(
[string[]]$CVEIds
)
$results = @()
foreach ($cveId in $CVEIds) {
$cve = Get-CyberSecFeedCVE -CVEId $cveId -IncludeACSC
if ($cve) {
$riskLevel = "Low"
$riskFactors = @()
# Assess risk based on multiple factors
if ($cve.cvss.baseScore -ge 9.0) {
$riskLevel = "High"
$riskFactors += "Critical CVSS score"
}
elseif ($cve.cvss.baseScore -ge 7.0) {
$riskLevel = "Medium"
$riskFactors += "High CVSS score"
}
if ($cve.kev) {
$riskLevel = "Critical"
$riskFactors += "Known exploited vulnerability"
}
if ($cve.epss -and $cve.epss.score -gt 0.5) {
if ($riskLevel -eq "Low") { $riskLevel = "Medium" }
if ($riskLevel -eq "Medium") { $riskLevel = "High" }
$riskFactors += "High EPSS score"
}
if ($cve.acsc) {
if ($riskLevel -eq "Low") { $riskLevel = "Medium" }
$riskFactors += "ACSC advisory available"
}
$results += [PSCustomObject]@{
CVE = $cveId
RiskLevel = $riskLevel
CVSSScore = $cve.cvss.baseScore
EPSSScore = $cve.epss.score
KEV = [bool]$cve.kev
ACSCNotices = if ($cve.acsc) { $cve.acsc.Count } else { 0 }
RiskFactors = ($riskFactors -join ", ")
}
}
}
return $results | Sort-Object @{Expression={
switch($_.RiskLevel) {
"Critical" { 0 }
"High" { 1 }
"Medium" { 2 }
"Low" { 3 }
}
}}
}
# Generate report
$cvesToCheck = @("CVE-2024-0001", "CVE-2024-0002", "CVE-2024-0003")
$report = Get-VulnerabilityRiskReport -CVEIds $cvesToCheck
# Display report
$report | Format-Table -AutoSize
cURL Examples
Basic Commands
# Get specific CVE
curl -H "X-API-Key: your-api-key-here" \
https://api.cybersecfeed.com/api/v1/cve/CVE-2024-0001
# Get CVE with ACSC data
curl -H "X-API-Key: your-api-key-here" \
"https://api.cybersecfeed.com/api/v1/cve/CVE-2024-0001?include=acsc"
# Search for critical vulnerabilities
curl -H "X-API-Key: your-api-key-here" \
"https://api.cybersecfeed.com/api/v1/cves?severity_min=9.0&limit=10"
# Search with ACSC data included
curl -H "X-API-Key: your-api-key-here" \
"https://api.cybersecfeed.com/api/v1/cves?severity_min=9.0&include=acsc&limit=10"
# Get KEV catalog
curl -H "X-API-Key: your-api-key-here" \
https://api.cybersecfeed.com/api/v1/kev
# Check platform stats
curl -H "X-API-Key: your-api-key-here" \
https://api.cybersecfeed.com/api/v1/stats
# Batch CVE lookup
curl -H "X-API-Key: your-api-key-here" \
"https://api.cybersecfeed.com/api/v1/cves?ids=CVE-2024-0001,CVE-2024-0002"
# Field projection
curl -H "X-API-Key: your-api-key-here" \
"https://api.cybersecfeed.com/api/v1/cve/CVE-2024-0001?fields=id,cvss.baseScore,kev"
# Field projection with ACSC data
curl -H "X-API-Key: your-api-key-here" \
"https://api.cybersecfeed.com/api/v1/cve/CVE-2024-0001?fields=id,cvss,acsc&include=acsc"
# ETag caching example
# First request - save headers
curl -H "X-API-Key: your-api-key-here" \
-D headers.txt \
https://api.cybersecfeed.com/api/v1/cve/CVE-2024-0001
# Extract ETag
etag=$(grep -i etag headers.txt | cut -d' ' -f2 | tr -d '\r')
# Subsequent request with ETag
curl -H "X-API-Key: your-api-key-here" \
-H "If-None-Match: $etag" \
-w "%{http_code}" \
https://api.cybersecfeed.com/api/v1/cve/CVE-2024-0001
Advanced Shell Script
#!/bin/bash
# CyberSecFeed vulnerability assessment script
API_KEY="your-api-key-here"
BASE_URL="https://api.cybersecfeed.com/api/v1"
# Function to make API calls
api_call() {
local endpoint=$1
curl -s -H "X-API-Key: $API_KEY" "$BASE_URL$endpoint"
}
# Check for critical vulnerabilities published today
check_critical_today() {
local today=$(date -u +%Y-%m-%d)
echo "Checking for critical CVEs published today ($today)..."
response=$(api_call "/cves?severity_min=9.0&published_after=$today&include=acsc")
count=$(echo "$response" | jq '.data.cves | length')
if [ "$count" -gt 0 ]; then
echo "⚠️ Found $count critical CVEs published today:"
echo "$response" | jq -r '.data.cves[] | "- \(.id): \(.cvss.baseScore)"'
else
echo "✅ No critical CVEs published today"
fi
}
# Check if specific CVEs are exploited or have ACSC notices
check_exploitation() {
local cve_ids=("$@")
for cve_id in "${cve_ids[@]}"; do
response=$(api_call "/cve/$cve_id?include=acsc")
has_kev=$(echo "$response" | jq -r '.data.cve.kev // empty')
has_acsc=$(echo "$response" | jq -r '.data.cve.acsc // empty')
if [ -n "$has_kev" ]; then
echo "⚠️ $cve_id is ACTIVELY EXPLOITED"
echo "$response" | jq -r '.data.cve.kev'
else
echo "✅ $cve_id is not in KEV catalog"
fi
if [ -n "$has_acsc" ] && [ "$has_acsc" != "null" ]; then
acsc_count=$(echo "$response" | jq '.data.cve.acsc | length')
echo "🇦🇺 $cve_id has $acsc_count ACSC notice(s)"
fi
done
}
# Main execution
check_critical_today
echo ""
check_exploitation "CVE-2024-0001" "CVE-2024-0002"
Summary
These examples demonstrate:
- Authentication: All requests include the required API key
- Error Handling: Proper exception handling and error messages
- Best Practices: Connection reuse, timeouts, and efficient data processing
- Real Use Cases: Risk assessment, monitoring, and batch operations
- Language Idioms: Following conventions for each programming language
Choose the language that best fits your environment and adapt these examples to your specific security workflows.