Code Examples
Complete, copy-paste ready code examples in Python, Node.js, and cURL. Use these examples to quickly integrate MySSL API into your applications.
Setup
Before using the API, set up your environment with your API key. Never hardcode API keys in your source code.
# Install required package
# pip install requests
import os
import requests
# Load API key from environment variable
API_KEY = os.environ.get('MYSSL_API_KEY')
BASE_URL = 'https://myssl.info/api/v1'
# Common headers for all requests
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
def api_request(method, endpoint, data=None):
"""Make an API request with error handling."""
url = f'{BASE_URL}{endpoint}'
response = requests.request(method, url, headers=headers, json=data)
response.raise_for_status()
return response.json()
Domain Management
GET List All Domains
Retrieve all domains in your account with pagination support.
def list_domains(page=1, per_page=20):
"""List all domains with pagination."""
response = api_request('GET', f'/domains?page={page}&per_page={per_page}')
return response
# Get first page of domains
domains = list_domains()
print(f"Total domains: {domains['pagination']['total']}")
for domain in domains['domains']:
print(f"{domain['hostname']}: {domain['ssl_grade']}")
POST Add a Domain
Add a new domain to monitor. The domain will be scanned immediately after being added.
def add_domain(hostname, port=443):
"""Add a new domain for monitoring."""
data = {
'hostname': hostname,
'port': port
}
response = api_request('POST', '/domains', data)
return response
# Add a new domain
new_domain = add_domain('example.com')
print(f"Added domain: {new_domain['hostname']}")
print(f"Domain ID: {new_domain['id']}")
# Add domain with custom port
custom_port = add_domain('secure.example.com', port=8443)
print(f"Added: {custom_port['hostname']}:{custom_port['port']}")
DELETE Delete a Domain
Remove a domain from monitoring. This action cannot be undone.
def delete_domain(domain_id):
"""Delete a domain by ID."""
response = api_request('DELETE', f'/domains/{domain_id}')
return response
# Delete domain by ID
result = delete_domain(123)
print("Domain deleted successfully")
SSL Scanning
POST Trigger an SSL Scan
Initiate an on-demand SSL scan for a domain. Scans run asynchronously.
import time
def trigger_scan(domain_id):
"""Trigger an SSL scan for a domain."""
response = api_request('POST', f'/domains/{domain_id}/scan')
return response
def get_scan_status(scan_id):
"""Check the status of a scan."""
response = api_request('GET', f'/scans/{scan_id}')
return response
def wait_for_scan(scan_id, timeout=120):
"""Wait for scan to complete with timeout."""
start_time = time.time()
while time.time() - start_time < timeout:
scan = get_scan_status(scan_id)
if scan['status'] == 'completed':
return scan
elif scan['status'] == 'failed':
raise Exception(f"Scan failed: {scan.get('error')}")
time.sleep(5) # Poll every 5 seconds
raise TimeoutError("Scan timed out")
# Trigger scan and wait for results
scan = trigger_scan(123)
print(f"Scan started: {scan['id']}")
result = wait_for_scan(scan['id'])
print(f"SSL Grade: {result['ssl_grade']}")
print(f"SSL Score: {result['ssl_score']}")
GET Get Scan History
Retrieve historical scan results for a domain.
def get_scan_history(domain_id, page=1, per_page=10):
"""Get scan history for a domain."""
response = api_request(
'GET',
f'/domains/{domain_id}/scans?page={page}&per_page={per_page}'
)
return response
# Get last 10 scans for a domain
history = get_scan_history(123)
for scan in history['scans']:
print(f"{scan['created_at']}: {scan['ssl_grade']} ({scan['ssl_score']})")
Certificate Information
GET Get Certificate Details
Retrieve detailed SSL certificate information for a domain.
from datetime import datetime
def get_certificate(domain_id):
"""Get certificate details for a domain."""
response = api_request('GET', f'/domains/{domain_id}/certificate')
return response
def get_certificate_chain(domain_id):
"""Get the full certificate chain."""
response = api_request('GET', f'/domains/{domain_id}/certificate/chain')
return response
# Get certificate info
cert = get_certificate(123)
print(f"Subject: {cert['subject']}")
print(f"Issuer: {cert['issuer']}")
print(f"Expires: {cert['not_after']}")
# Calculate days until expiry
expiry = datetime.fromisoformat(cert['not_after'].replace('Z', '+00:00'))
days_left = (expiry - datetime.now(expiry.tzinfo)).days
print(f"Days until expiry: {days_left}")
# Get full certificate chain
chain = get_certificate_chain(123)
for i, cert in enumerate(chain['certificates']):
print(f"Certificate {i + 1}: {cert['subject']}")
GET Find Expiring Certificates
Find certificates expiring within a specified number of days.
def get_expiring_certificates(days=30):
"""Get certificates expiring within specified days."""
response = api_request('GET', f'/certificates/expiring?days={days}')
return response
# Find certificates expiring in 30 days
expiring = get_expiring_certificates(30)
if expiring['certificates']:
print("Certificates expiring soon:")
for cert in expiring['certificates']:
print(f" - {cert['hostname']}: {cert['days_until_expiry']} days")
else:
print("No certificates expiring soon!")
Uptime Monitoring
POST Create Uptime Monitor
Create a new uptime monitor for an endpoint.
def create_uptime_monitor(name, url, check_interval=60):
"""Create a new uptime monitor."""
data = {
'name': name,
'url': url,
'check_interval': check_interval,
'expected_status_code': 200
}
response = api_request('POST', '/uptime/monitors', data)
return response
def get_uptime_stats(monitor_id, period='7d'):
"""Get uptime statistics for a monitor."""
response = api_request('GET', f'/uptime/monitors/{monitor_id}/stats?period={period}')
return response
# Create a new monitor
monitor = create_uptime_monitor(
name='API Health Check',
url='https://api.example.com/health',
check_interval=60 # Check every 60 seconds
)
print(f"Created monitor: {monitor['id']}")
# Get uptime stats for last 7 days
stats = get_uptime_stats(monitor['id'], '7d')
print(f"Uptime: {stats['uptime_percentage']}%")
print(f"Avg Response Time: {stats['avg_response_time']}ms")
Error Handling
Robust error handling is essential for production applications. Here are examples of how to handle API errors gracefully.
import requests
from requests.exceptions import RequestException, HTTPError
class MySSLAPIError(Exception):
"""Custom exception for MySSL API errors."""
def __init__(self, message, status_code=None, details=None):
self.message = message
self.status_code = status_code
self.details = details
super().__init__(self.message)
def api_request_with_error_handling(method, endpoint, data=None):
"""Make API request with comprehensive error handling."""
url = f'{BASE_URL}{endpoint}'
try:
response = requests.request(
method,
url,
headers=headers,
json=data,
timeout=30 # 30 second timeout
)
response.raise_for_status()
return response.json()
except HTTPError as e:
# Handle specific HTTP errors
status_code = e.response.status_code
try:
error_data = e.response.json()
message = error_data.get('error', str(e))
details = error_data.get('details')
except:
message = str(e)
details = None
if status_code == 401:
raise MySSLAPIError("Invalid or expired API key", status_code)
elif status_code == 403:
raise MySSLAPIError("Permission denied", status_code)
elif status_code == 404:
raise MySSLAPIError("Resource not found", status_code)
elif status_code == 429:
raise MySSLAPIError("Rate limit exceeded", status_code, details)
else:
raise MySSLAPIError(message, status_code, details)
except RequestException as e:
# Handle connection errors, timeouts, etc.
raise MySSLAPIError(f"Network error: {str(e)}")
# Usage example
try:
domains = api_request_with_error_handling('GET', '/domains')
print(f"Found {len(domains['domains'])} domains")
except MySSLAPIError as e:
print(f"API Error ({e.status_code}): {e.message}")
if e.details:
print(f"Details: {e.details}")
Complete Integration Example
A complete example showing how to integrate MySSL API into a monitoring script.
#!/usr/bin/env python3
"""
MySSL API Integration Example
Monitor SSL certificates and send alerts for expiring certs.
"""
import os
import requests
from datetime import datetime
# Configuration
API_KEY = os.environ.get('MYSSL_API_KEY')
BASE_URL = 'https://myssl.info/api/v1'
EXPIRY_WARNING_DAYS = 30
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
def get_all_domains():
"""Fetch all domains with pagination."""
domains = []
page = 1
while True:
response = requests.get(
f'{BASE_URL}/domains?page={page}&per_page=100',
headers=headers
)
response.raise_for_status()
data = response.json()
domains.extend(data['domains'])
if page >= data['pagination']['pages']:
break
page += 1
return domains
def check_certificate_expiry(domains):
"""Check for expiring certificates."""
expiring = []
for domain in domains:
if domain.get('certificate_expiry'):
expiry = datetime.fromisoformat(
domain['certificate_expiry'].replace('Z', '+00:00')
)
days_left = (expiry - datetime.now(expiry.tzinfo)).days
if days_left <= EXPIRY_WARNING_DAYS:
expiring.append({
'hostname': domain['hostname'],
'days_left': days_left,
'expiry': expiry.isoformat()
})
return sorted(expiring, key=lambda x: x['days_left'])
def check_ssl_grades(domains):
"""Find domains with poor SSL grades."""
poor_grades = ['C', 'D', 'E', 'F']
issues = []
for domain in domains:
grade = domain.get('ssl_grade', '')
if grade and grade[0] in poor_grades:
issues.append({
'hostname': domain['hostname'],
'grade': grade,
'score': domain.get('ssl_score')
})
return issues
def main():
print("SSL Certificate Monitor")
print("=" * 40)
# Fetch all domains
print("\nFetching domains...")
domains = get_all_domains()
print(f"Found {len(domains)} domains")
# Check for expiring certificates
print(f"\nChecking for certificates expiring in {EXPIRY_WARNING_DAYS} days...")
expiring = check_certificate_expiry(domains)
if expiring:
print(f"\n⚠️ Found {len(expiring)} expiring certificates:")
for cert in expiring:
print(f" - {cert['hostname']}: {cert['days_left']} days")
else:
print("✅ No certificates expiring soon")
# Check for poor SSL grades
print("\nChecking SSL grades...")
issues = check_ssl_grades(domains)
if issues:
print(f"\n⚠️ Found {len(issues)} domains with poor SSL grades:")
for issue in issues:
print(f" - {issue['hostname']}: Grade {issue['grade']} (Score: {issue['score']})")
else:
print("✅ All domains have good SSL grades")
if __name__ == '__main__':
main()
Need More Help?
Explore our comprehensive API documentation or contact our support team for assistance.