Back to Home

Integration Examples

Real-world examples and code samples for PromptShield integration

Basic Integration
Simple API integration example

Get started with a basic scan using our REST API.

View Example
CI/CD Pipeline
Automated security testing in your pipeline

Integrate security scans into your deployment process.

View Example
Webhook Integration
Real-time notifications and automation

Set up webhooks for automated responses to scan results.

View Example

Basic Integration

Python SDK Example
Complete example of scanning an AI application

Installation

pip install promptshield

Basic Usage

import promptshield
import time

# Initialize the client
client = promptshield.Client(api_key="your_api_key_here")

# Create a new scan
scan = client.scans.create(
    name="My AI App Security Scan",
    endpoint="https://api.openai.com/v1/chat/completions",
    api_key="sk-your-openai-key",
    model="gpt-4",
    test_types=["prompt_injection", "data_leakage", "output_validation"]
)

print(f"Scan created: {scan.id}")
print(f"Status: {scan.status}")

# Wait for completion
print("Waiting for scan to complete...")
scan.wait_for_completion()

# Get results
results = scan.get_results()
print(f"Security Score: {results.security_score}")
print(f"Grade: {results.grade}")
print(f"Vulnerabilities Found: {results.vulnerability_count}")

# Get detailed report
report = scan.get_report()
for vuln in report.vulnerabilities:
    print(f"- {vuln.title} ({vuln.severity})")

CI/CD Pipeline Integration

GitHub Actions Example
Automatically scan your AI applications on every deployment

.github/workflows/security-scan.yml

name: AI Security Scan

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  security-scan:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Setup Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'
    
    - name: Install dependencies
      run: |
        pip install promptshield
    
    - name: Run security scan
      env:
        PROMPTSHIELD_API_KEY: ${{ secrets.PROMPTSHIELD_API_KEY }}
        OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      run: |
        python -c "
        import promptshield
        import os
        
        client = promptshield.Client(api_key=os.getenv('PROMPTSHIELD_API_KEY'))
        
        scan = client.scans.create(
            name='CI/CD Security Scan',
            endpoint='https://api.openai.com/v1/chat/completions',
            api_key=os.getenv('OPENAI_API_KEY'),
            model='gpt-4'
        )
        
        scan.wait_for_completion()
        results = scan.get_results()
        
        if results.security_score < 80:
            print(f'Security score too low: {results.security_score}')
            exit(1)
        else:
            print(f'Security scan passed: {results.security_score}')
        "
    
    - name: Upload scan results
      uses: actions/upload-artifact@v3
      with:
        name: security-scan-results
        path: scan-results.json

Webhook Integration

Express.js Webhook Handler
Handle scan completion notifications in your Node.js application

Webhook Handler

const express = require('express');
const crypto = require('crypto');

const app = express();
app.use(express.json());

// Verify webhook signature
function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}

// Webhook endpoint
app.post('/webhooks/promptshield', (req, res) => {
  const signature = req.headers['x-promptshield-signature'];
  const payload = JSON.stringify(req.body);
  
  // Verify webhook signature
  if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Unauthorized');
  }
  
  const { event, scanId, status, results } = req.body;
  
  switch (event) {
    case 'scan.completed':
      handleScanCompleted(scanId, results);
      break;
    case 'scan.failed':
      handleScanFailed(scanId, req.body.error);
      break;
    default:
      console.log('Unknown event:', event);
  }
  
  res.status(200).send('OK');
});

function handleScanCompleted(scanId, results) {
  console.log(`Scan ${scanId} completed with score: ${results.securityScore}`);
  
  // Send notification to team
  if (results.securityScore < 80) {
    sendSlackNotification(`🚨 Security scan ${scanId} found issues! Score: ${results.securityScore}`);
  }
  
  // Update database
  updateScanResults(scanId, results);
  
  // Trigger additional actions
  if (results.vulnerabilityCount > 0) {
    createSecurityTicket(scanId, results);
  }
}

function handleScanFailed(scanId, error) {
  console.error(`Scan ${scanId} failed:`, error);
  sendSlackNotification(`❌ Security scan ${scanId} failed: ${error.message}`);
}

app.listen(3000, () => {
  console.log('Webhook server running on port 3000');
});