Basic Validation ExamplesΒΆ
Get started with ReputeAPI using these simple, beginner-friendly examples. Each example is complete and ready to run.
PrerequisitesΒΆ
Before running these examples, you'll need:
- API Key: Sign up at reputeapi.com to get your free API key
- API Endpoint:
https://api.reputeapi.com - Rate Limits: Free tier includes 10 requests/minute, 1,000 requests/month
Testing Without an API Key
During development, you can test with the public demo endpoint (limited functionality):
Python Quick StartΒΆ
Single Domain CheckΒΆ
The simplest way to validate a domain in Python:
import requests
# Configuration
API_KEY = "your-api-key-here"
BASE_URL = "https://api.reputeapi.com"
def check_domain(domain):
"""Check a single domain's email security configuration"""
response = requests.get(
f"{BASE_URL}/api/v1/check",
params={"domain": domain},
headers={"X-API-Key": API_KEY}
)
# Raise exception if request failed
response.raise_for_status()
return response.json()
# Usage
if __name__ == "__main__":
result = check_domain("google.com")
print(f"Domain: {result['domain']}")
print(f"Score: {result['score']}/100")
print(f"Grade: {result['grade']}")
print(f"\nSPF: {'β' if result['spf']['present'] else 'β'}")
print(f"DKIM: {'β' if result['dkim']['validated_keys'] else 'β'}")
print(f"DMARC: {'β' if result['dmarc']['present'] else 'β'}")
if result.get('issues'):
print(f"\nβ Issues Found: {len(result['issues'])}")
for issue in result['issues'][:3]: # Show top 3
print(f" [{issue['severity'].upper()}] {issue['message']}")
Expected Output:
Domain: google.com
Score: 95/100
Grade: Excellent
SPF: β
DKIM: β
DMARC: β
β Issues Found: 1
[MEDIUM] DMARC policy set to 'quarantine' instead of 'reject'
Step-by-Step ExplanationΒΆ
- Import the requests library: Used for making HTTP requests
- Set up configuration: Store your API key and base URL
- Create check function: Wraps the API call in a reusable function
- Make the request: GET request to
/api/v1/checkendpoint - Handle errors:
raise_for_status()throws exception on HTTP errors - Parse response: Convert JSON response to Python dictionary
- Display results: Print key metrics in a readable format
With Error HandlingΒΆ
Add proper error handling for production use:
import requests
from requests.exceptions import RequestException, Timeout, HTTPError
API_KEY = "your-api-key-here"
BASE_URL = "https://api.reputeapi.com"
def check_domain_safe(domain):
"""
Check domain with comprehensive error handling
Returns:
dict: Validation results or None if error occurred
"""
try:
response = requests.get(
f"{BASE_URL}/api/v1/check",
params={"domain": domain},
headers={"X-API-Key": API_KEY},
timeout=10 # 10 second timeout
)
# Handle specific HTTP errors
if response.status_code == 401:
print("β Error: Invalid API key")
return None
elif response.status_code == 429:
retry_after = response.headers.get("Retry-After", "unknown")
print(f"β Error: Rate limit exceeded. Retry after {retry_after} seconds")
return None
elif response.status_code == 400:
error_data = response.json()
print(f"β Error: {error_data.get('message', 'Invalid request')}")
return None
response.raise_for_status()
return response.json()
except Timeout:
print(f"β Error: Request timed out for domain: {domain}")
return None
except ConnectionError:
print("β Error: Connection failed. Check your internet connection.")
return None
except HTTPError as e:
print(f"β HTTP Error: {e}")
return None
except RequestException as e:
print(f"β Request Error: {e}")
return None
except Exception as e:
print(f"β Unexpected Error: {e}")
return None
# Usage
result = check_domain_safe("google.com")
if result:
print(f"β
Success! Score: {result['score']}/100")
else:
print("Failed to check domain. See error above.")
JavaScript Quick StartΒΆ
Node.js with fetchΒΆ
Modern Node.js (v18+) with built-in fetch:
// Configuration
const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://api.reputeapi.com';
/**
* Check a single domain's email security
* @param {string} domain - Domain to check (e.g., 'google.com')
* @returns {Promise<Object>} Validation results
*/
async function checkDomain(domain) {
const response = await fetch(
`${BASE_URL}/api/v1/check?domain=${domain}`,
{
headers: {
'X-API-Key': API_KEY
}
}
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
}
// Usage
async function main() {
try {
const result = await checkDomain('google.com');
console.log(`Domain: ${result.domain}`);
console.log(`Score: ${result.score}/100`);
console.log(`Grade: ${result.grade}`);
console.log();
console.log(`SPF: ${result.spf.present ? 'β' : 'β'}`);
console.log(`DKIM: ${result.dkim.validated_keys.length > 0 ? 'β' : 'β'}`);
console.log(`DMARC: ${result.dmarc.present ? 'β' : 'β'}`);
if (result.issues && result.issues.length > 0) {
console.log(`\nβ Issues Found: ${result.issues.length}`);
result.issues.slice(0, 3).forEach(issue => {
console.log(` [${issue.severity.toUpperCase()}] ${issue.message}`);
});
}
} catch (error) {
console.error('Error:', error.message);
}
}
main();
Node.js with axiosΒΆ
Using the popular axios library:
const axios = require('axios');
const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://api.reputeapi.com';
async function checkDomain(domain) {
try {
const response = await axios.get(`${BASE_URL}/api/v1/check`, {
params: { domain },
headers: { 'X-API-Key': API_KEY },
timeout: 10000 // 10 second timeout
});
return response.data;
} catch (error) {
if (error.response) {
// Server responded with error status
const status = error.response.status;
if (status === 401) {
throw new Error('Invalid API key');
} else if (status === 429) {
const retryAfter = error.response.headers['retry-after'];
throw new Error(`Rate limit exceeded. Retry after ${retryAfter} seconds`);
} else if (status === 400) {
throw new Error(`Bad request: ${error.response.data.message}`);
} else {
throw new Error(`HTTP ${status}: ${error.response.statusText}`);
}
} else if (error.request) {
// Request made but no response received
throw new Error('No response from server. Check your connection.');
} else {
// Error setting up request
throw new Error(`Request error: ${error.message}`);
}
}
}
// Usage
async function main() {
try {
const result = await checkDomain('google.com');
console.log(`Score: ${result.score}/100 (${result.grade})`);
} catch (error) {
console.error('Error:', error.message);
process.exit(1);
}
}
main();
Installation:
Browser JavaScriptΒΆ
Use in web applications:
<!DOCTYPE html>
<html>
<head>
<title>Domain Checker</title>
<style>
body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; }
.result { margin-top: 20px; padding: 20px; background: #f5f5f5; border-radius: 5px; }
.score { font-size: 48px; font-weight: bold; color: #2c3e50; }
.status { margin: 10px 0; }
.issue { margin: 5px 0; padding: 5px; background: #fff3cd; border-left: 3px solid #ffc107; }
</style>
</head>
<body>
<h1>Email Security Checker</h1>
<input type="text" id="domain" placeholder="Enter domain (e.g., google.com)" style="width: 100%; padding: 10px;">
<button onclick="checkDomain()" style="margin-top: 10px; padding: 10px 20px;">Check Domain</button>
<div id="result" class="result" style="display: none;"></div>
<script>
const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://api.reputeapi.com';
async function checkDomain() {
const domain = document.getElementById('domain').value;
const resultDiv = document.getElementById('result');
if (!domain) {
alert('Please enter a domain');
return;
}
resultDiv.innerHTML = 'Checking...';
resultDiv.style.display = 'block';
try {
const response = await fetch(
`${BASE_URL}/api/v1/check?domain=${domain}`,
{
headers: { 'X-API-Key': API_KEY }
}
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const result = await response.json();
displayResult(result);
} catch (error) {
resultDiv.innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
}
}
function displayResult(result) {
const resultDiv = document.getElementById('result');
let html = `
<h2>${result.domain}</h2>
<div class="score">${result.score}/100</div>
<p><strong>Grade:</strong> ${result.grade}</p>
<div class="status">
<p>SPF: ${result.spf.present ? 'β Present' : 'β Missing'}</p>
<p>DKIM: ${result.dkim.validated_keys.length > 0 ? 'β Configured' : 'β Not Found'}</p>
<p>DMARC: ${result.dmarc.present ? 'β Present' : 'β Missing'}</p>
</div>
`;
if (result.issues && result.issues.length > 0) {
html += '<h3>Issues Found:</h3>';
result.issues.forEach(issue => {
html += `
<div class="issue">
<strong>[${issue.severity.toUpperCase()}]</strong> ${issue.message}
</div>
`;
});
}
resultDiv.innerHTML = html;
}
</script>
</body>
</html>
cURL Quick StartΒΆ
Basic CheckΒΆ
Test the API from command line:
curl -X GET "https://api.reputeapi.com/api/v1/check?domain=google.com" \
-H "X-API-Key: your-api-key-here"
Pretty-Printed OutputΒΆ
Use jq for formatted JSON output:
curl -X GET "https://api.reputeapi.com/api/v1/check?domain=google.com" \
-H "X-API-Key: your-api-key-here" \
| jq '.'
Extract Specific FieldsΒΆ
Get just the score:
curl -s -X GET "https://api.reputeapi.com/api/v1/check?domain=google.com" \
-H "X-API-Key: your-api-key-here" \
| jq -r '.score'
Output:
Check Multiple DomainsΒΆ
Simple bash loop:
#!/bin/bash
API_KEY="your-api-key-here"
BASE_URL="https://api.reputeapi.com"
# List of domains to check
domains=("google.com" "github.com" "stackoverflow.com")
for domain in "${domains[@]}"; do
echo "Checking $domain..."
score=$(curl -s -X GET "$BASE_URL/api/v1/check?domain=$domain" \
-H "X-API-Key: $API_KEY" \
| jq -r '.score')
echo "Score: $score/100"
echo "---"
done
Expected Output:
Checking google.com...
Score: 95/100
---
Checking github.com...
Score: 88/100
---
Checking stackoverflow.com...
Score: 92/100
---
Save Results to FileΒΆ
curl -X GET "https://api.reputeapi.com/api/v1/check?domain=google.com" \
-H "X-API-Key: your-api-key-here" \
-o google-results.json
echo "Results saved to google-results.json"
Common PatternsΒΆ
Environment VariablesΒΆ
Store your API key securely:
Python:
import os
from dotenv import load_dotenv
# Load from .env file
load_dotenv()
API_KEY = os.getenv("REPUTE_API_KEY")
if not API_KEY:
raise ValueError("REPUTE_API_KEY not set in environment")
.env file:
Node.js:
require('dotenv').config();
const API_KEY = process.env.REPUTE_API_KEY;
if (!API_KEY) {
throw new Error('REPUTE_API_KEY not set in environment');
}
.env file:
Bash:
# Load from .env file
if [ -f .env ]; then
export $(cat .env | xargs)
fi
if [ -z "$REPUTE_API_KEY" ]; then
echo "Error: REPUTE_API_KEY not set"
exit 1
fi
Quick Score CheckΒΆ
For faster checks when you only need the score:
Python:
def get_quick_score(domain):
"""Get just the score (faster than full check)"""
response = requests.get(
f"{BASE_URL}/api/v1/score",
params={"domain": domain},
headers={"X-API-Key": API_KEY}
)
response.raise_for_status()
return response.json()
result = get_quick_score("google.com")
print(f"Score: {result['score']}/100")
JavaScript:
async function getQuickScore(domain) {
const response = await fetch(
`${BASE_URL}/api/v1/score?domain=${domain}`,
{ headers: { 'X-API-Key': API_KEY } }
);
return response.json();
}
const result = await getQuickScore('google.com');
console.log(`Score: ${result.score}/100`);
cURL:
curl -s "https://api.reputeapi.com/api/v1/score?domain=google.com" \
-H "X-API-Key: your-api-key" \
| jq -r '.score'
With DKIM SelectorsΒΆ
Specify DKIM selectors for better results:
Python:
result = requests.get(
f"{BASE_URL}/api/v1/check",
params={
"domain": "google.com",
"selectors": "google,default,selector1"
},
headers={"X-API-Key": API_KEY}
).json()
JavaScript:
const params = new URLSearchParams({
domain: 'google.com',
selectors: 'google,default,selector1'
});
const response = await fetch(
`${BASE_URL}/api/v1/check?${params}`,
{ headers: { 'X-API-Key': API_KEY } }
);
cURL:
curl "https://api.reputeapi.com/api/v1/check?domain=google.com&selectors=google,default" \
-H "X-API-Key: your-api-key"
Common PitfallsΒΆ
1. Missing API KeyΒΆ
Problem:
response = requests.get(f"{BASE_URL}/api/v1/check?domain=google.com")
# β Returns 401 Unauthorized
Solution:
response = requests.get(
f"{BASE_URL}/api/v1/check?domain=google.com",
headers={"X-API-Key": API_KEY} # β
Include API key
)
2. Not Handling ErrorsΒΆ
Problem:
Solution:
response = requests.get(url, headers=headers)
response.raise_for_status() # β
Raises exception on error
result = response.json()
3. Invalid Domain FormatΒΆ
Problem:
check_domain("http://example.com") # β Don't include protocol
check_domain("example.com/path") # β Don't include path
Solution:
4. Ignoring Rate LimitsΒΆ
Problem:
Solution:
import time
for domain in large_list:
check_domain(domain)
time.sleep(1) # β
Add delay between requests
Better: Use the bulk endpoint for multiple domains.
5. Hardcoding API KeysΒΆ
Problem:
Solution:
Testing Your IntegrationΒΆ
Test DomainsΒΆ
Use these domains for testing:
| Domain | Expected Score | Purpose |
|---|---|---|
google.com |
90+ | Well-configured domain |
github.com |
85+ | Good configuration |
example.com |
Varies | RFC example domain |
your-domain.com |
Varies | Test your own domain |
Verify OutputΒΆ
Check that your code correctly handles:
- β Successful responses (200 OK)
- β Missing API key (401 Unauthorized)
- β Rate limits (429 Too Many Requests)
- β Invalid domains (400 Bad Request)
- β Network timeouts
- β Server errors (500+)
Next StepsΒΆ
Now that you've mastered basic validation:
- Process Multiple Domains: Learn Bulk Validation
- Handle Common Scenarios: See Real-World Examples
- Debug Issues: Check Troubleshooting Guide
- Get Complete Code: Browse Code Samples Library
- Deep Dive: Read Full Integration Guides
Additional ResourcesΒΆ
- API Reference - Complete endpoint documentation
- Authentication Guide - API key management
- Rate Limits - Understand quotas
- Error Codes - All error responses
- Best Practices - Optimization tips