Code Samples LibraryΒΆ
Complete, production-ready code samples in multiple programming languages. All examples include error handling, best practices, and are ready to use in your applications.
PythonΒΆ
Complete Client LibraryΒΆ
Full-featured Python client with all endpoints:
"""
ReputeAPI Python Client Library
Complete implementation with all features
"""
import requests
from typing import Dict, List, Optional
from datetime import datetime
import time
from functools import wraps
class ReputeAPIError(Exception):
"""Base exception for ReputeAPI errors"""
pass
class AuthenticationError(ReputeAPIError):
"""Authentication failed"""
pass
class RateLimitError(ReputeAPIError):
"""Rate limit exceeded"""
def __init__(self, message: str, retry_after: int = 60):
super().__init__(message)
self.retry_after = retry_after
class ValidationError(ReputeAPIError):
"""Invalid request parameters"""
pass
def retry_on_rate_limit(max_retries: int = 3):
"""Decorator to retry on rate limit"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
retries = 0
while retries < max_retries:
try:
return func(*args, **kwargs)
except RateLimitError as e:
retries += 1
if retries >= max_retries:
raise
print(f"Rate limited. Waiting {e.retry_after}s... (attempt {retries}/{max_retries})")
time.sleep(e.retry_after)
raise RateLimitError(f"Max retries ({max_retries}) exceeded")
return wrapper
return decorator
class ReputeAPIClient:
"""
Complete Python client for ReputeAPI
Usage:
client = ReputeAPIClient(api_key="your-key")
result = client.check_domain("example.com")
print(f"Score: {result['score']}/100")
"""
def __init__(
self,
api_key: str,
base_url: str = "https://api.reputeapi.com",
timeout: int = 10
):
"""
Initialize client
Args:
api_key: Your API key
base_url: API base URL
timeout: Request timeout in seconds
"""
self.api_key = api_key
self.base_url = base_url
self.timeout = timeout
self.session = requests.Session()
self.session.headers.update({
"X-API-Key": api_key,
"User-Agent": "ReputeAPI-Python-Client/1.0"
})
def _handle_response(self, response: requests.Response) -> Dict:
"""Handle API response with error checking"""
if response.status_code == 401:
raise AuthenticationError("Invalid or missing API key")
elif response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 60))
raise RateLimitError("Rate limit exceeded", retry_after=retry_after)
elif response.status_code == 400:
error_data = response.json()
raise ValidationError(error_data.get('message', 'Invalid request'))
elif response.status_code >= 500:
raise ReputeAPIError(f"Server error: {response.status_code}")
response.raise_for_status()
return response.json()
@retry_on_rate_limit(max_retries=3)
def check_domain(
self,
domain: str,
selectors: Optional[List[str]] = None,
verbose: bool = False,
refresh: bool = False
) -> Dict:
"""
Run complete mailflow security check
Args:
domain: Domain to check (e.g., "example.com")
selectors: DKIM selectors to check
verbose: Include verbose DNS details
refresh: Bypass cache and fetch fresh data
Returns:
Full validation results with score and issues
Raises:
AuthenticationError: Invalid API key
RateLimitError: Rate limit exceeded
ValidationError: Invalid request
ReputeAPIError: Other API errors
"""
params = {
"domain": domain,
"verbose": verbose,
"refresh": refresh
}
if selectors:
params["selectors"] = ",".join(selectors)
response = self.session.get(
f"{self.base_url}/api/v1/check",
params=params,
timeout=self.timeout
)
return self._handle_response(response)
@retry_on_rate_limit(max_retries=3)
def get_score(self, domain: str, refresh: bool = False) -> Dict:
"""
Get quick score check (faster than full check)
Args:
domain: Domain to check
refresh: Bypass cache
Returns:
Score and top issues
"""
response = self.session.get(
f"{self.base_url}/api/v1/score",
params={"domain": domain, "refresh": refresh},
timeout=self.timeout
)
return self._handle_response(response)
@retry_on_rate_limit(max_retries=3)
def get_recommendations(
self,
domain: str,
severity: Optional[str] = None
) -> Dict:
"""
Get prioritized recommendations
Args:
domain: Domain to get recommendations for
severity: Filter by severity (critical, high, medium, low)
Returns:
Prioritized list of fixes
"""
data = {"domain": domain}
if severity:
data["severity"] = severity
response = self.session.post(
f"{self.base_url}/api/v1/recommendations",
json=data,
timeout=self.timeout
)
return self._handle_response(response)
@retry_on_rate_limit(max_retries=3)
def get_history(
self,
domain: str,
days: int = 30,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None
) -> Dict:
"""
Get historical validation data
Args:
domain: Domain to get history for
days: Number of days to retrieve (if dates not specified)
start_date: Start date for history
end_date: End date for history
Returns:
Historical snapshots
"""
params = {"domain": domain}
if start_date and end_date:
params["start_date"] = start_date.isoformat()
params["end_date"] = end_date.isoformat()
else:
params["days"] = days
response = self.session.get(
f"{self.base_url}/api/v1/history",
params=params,
timeout=self.timeout
)
return self._handle_response(response)
def get_usage(self) -> Dict:
"""
Get API usage statistics
Returns:
Usage stats for current billing period
"""
response = self.session.get(
f"{self.base_url}/api/v1/usage",
timeout=self.timeout
)
return self._handle_response(response)
@retry_on_rate_limit(max_retries=3)
def bulk_validate(self, domains: List[str]) -> Dict:
"""
Validate multiple domains (legacy endpoint)
Args:
domains: List of domains to validate (max 100)
Returns:
Results for all domains
"""
response = self.session.post(
f"{self.base_url}/v1/bulk-validate",
json={
"domains": [{"domain": d} for d in domains],
"options": {"include_score": True}
},
timeout=30
)
return self._handle_response(response)
def close(self):
"""Close the session"""
self.session.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
# Usage Example
if __name__ == "__main__":
# Initialize client
with ReputeAPIClient(api_key="your-api-key") as client:
# Check domain
try:
result = client.check_domain("example.com")
print(f"Domain: {result['domain']}")
print(f"Score: {result['score']}/100")
print(f"Grade: {result['grade']}")
# Get recommendations
recs = client.get_recommendations("example.com", severity="high")
print(f"\nHigh Priority Recommendations:")
for rec in recs['recommendations']:
print(f" - {rec['message']}")
except AuthenticationError as e:
print(f"Authentication error: {e}")
except RateLimitError as e:
print(f"Rate limit exceeded. Retry after {e.retry_after}s")
except ValidationError as e:
print(f"Validation error: {e}")
except ReputeAPIError as e:
print(f"API error: {e}")
JavaScript/Node.jsΒΆ
Complete Node.js ClientΒΆ
/**
* ReputeAPI Node.js Client Library
* Complete implementation with TypeScript support
*/
const axios = require('axios');
class ReputeAPIError extends Error {
constructor(message) {
super(message);
this.name = 'ReputeAPIError';
}
}
class AuthenticationError extends ReputeAPIError {
constructor(message = 'Invalid or missing API key') {
super(message);
this.name = 'AuthenticationError';
}
}
class RateLimitError extends ReputeAPIError {
constructor(message, retryAfter = 60) {
super(message);
this.name = 'RateLimitError';
this.retryAfter = retryAfter;
}
}
class ValidationError extends ReputeAPIError {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
class ReputeAPIClient {
/**
* Complete Node.js client for ReputeAPI
*
* @param {string} apiKey - Your API key
* @param {string} baseUrl - API base URL
* @param {number} timeout - Request timeout in milliseconds
*/
constructor(apiKey, baseUrl = 'https://api.reputeapi.com', timeout = 10000) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.timeout = timeout;
this.client = axios.create({
baseURL: baseUrl,
timeout: timeout,
headers: {
'X-API-Key': apiKey,
'User-Agent': 'ReputeAPI-NodeJS-Client/1.0'
}
});
// Add response interceptor for error handling
this.client.interceptors.response.use(
response => response,
error => this._handleError(error)
);
}
_handleError(error) {
if (error.response) {
const { status, data, headers } = error.response;
if (status === 401) {
throw new AuthenticationError();
} else if (status === 429) {
const retryAfter = parseInt(headers['retry-after'] || 60);
throw new RateLimitError('Rate limit exceeded', retryAfter);
} else if (status === 400) {
throw new ValidationError(data.message || 'Invalid request');
} else if (status >= 500) {
throw new ReputeAPIError(`Server error: ${status}`);
}
} else if (error.request) {
throw new ReputeAPIError('No response from server');
} else {
throw new ReputeAPIError(error.message);
}
throw error;
}
async _retryOnRateLimit(fn, maxRetries = 3) {
let retries = 0;
while (retries < maxRetries) {
try {
return await fn();
} catch (error) {
if (error instanceof RateLimitError && retries < maxRetries - 1) {
retries++;
console.log(`Rate limited. Waiting ${error.retryAfter}s... (attempt ${retries}/${maxRetries})`);
await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000));
} else {
throw error;
}
}
}
}
/**
* Run complete mailflow security check
*
* @param {string} domain - Domain to check
* @param {Object} options - Check options
* @param {string[]} options.selectors - DKIM selectors
* @param {boolean} options.verbose - Include verbose details
* @param {boolean} options.refresh - Bypass cache
* @returns {Promise<Object>} Validation results
*/
async checkDomain(domain, options = {}) {
return this._retryOnRateLimit(async () => {
const params = {
domain,
verbose: options.verbose || false,
refresh: options.refresh || false
};
if (options.selectors && options.selectors.length > 0) {
params.selectors = options.selectors.join(',');
}
const response = await this.client.get('/api/v1/check', { params });
return response.data;
});
}
/**
* Get quick score check
*
* @param {string} domain - Domain to check
* @param {boolean} refresh - Bypass cache
* @returns {Promise<Object>} Score and top issues
*/
async getScore(domain, refresh = false) {
return this._retryOnRateLimit(async () => {
const response = await this.client.get('/api/v1/score', {
params: { domain, refresh }
});
return response.data;
});
}
/**
* Get prioritized recommendations
*
* @param {string} domain - Domain to check
* @param {string} severity - Filter by severity
* @returns {Promise<Object>} Recommendations
*/
async getRecommendations(domain, severity = null) {
return this._retryOnRateLimit(async () => {
const data = { domain };
if (severity) {
data.severity = severity;
}
const response = await this.client.post('/api/v1/recommendations', data);
return response.data;
});
}
/**
* Get historical validation data
*
* @param {string} domain - Domain to check
* @param {Object} options - History options
* @param {number} options.days - Number of days
* @param {Date} options.startDate - Start date
* @param {Date} options.endDate - End date
* @returns {Promise<Object>} Historical data
*/
async getHistory(domain, options = {}) {
return this._retryOnRateLimit(async () => {
const params = { domain };
if (options.startDate && options.endDate) {
params.start_date = options.startDate.toISOString();
params.end_date = options.endDate.toISOString();
} else {
params.days = options.days || 30;
}
const response = await this.client.get('/api/v1/history', { params });
return response.data;
});
}
/**
* Get API usage statistics
*
* @returns {Promise<Object>} Usage stats
*/
async getUsage() {
const response = await this.client.get('/api/v1/usage');
return response.data;
}
/**
* Validate multiple domains
*
* @param {string[]} domains - List of domains (max 100)
* @returns {Promise<Object>} Results for all domains
*/
async bulkValidate(domains) {
return this._retryOnRateLimit(async () => {
const response = await this.client.post('/v1/bulk-validate', {
domains: domains.map(d => ({ domain: d })),
options: { include_score: true }
});
return response.data;
});
}
}
// Usage Example
async function main() {
const client = new ReputeAPIClient('your-api-key');
try {
// Check domain
const result = await client.checkDomain('example.com');
console.log(`Domain: ${result.domain}`);
console.log(`Score: ${result.score}/100`);
console.log(`Grade: ${result.grade}`);
// Get recommendations
const recs = await client.getRecommendations('example.com', 'high');
console.log('\nHigh Priority Recommendations:');
recs.recommendations.forEach(rec => {
console.log(` - ${rec.message}`);
});
// Check usage
const usage = await client.getUsage();
console.log(`\nAPI Usage: ${usage.requests_used}/${usage.requests_limit}`);
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication error:', error.message);
} else if (error instanceof RateLimitError) {
console.error(`Rate limit exceeded. Retry after ${error.retryAfter}s`);
} else if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
} else {
console.error('Error:', error.message);
}
}
}
if (require.main === module) {
main();
}
module.exports = {
ReputeAPIClient,
ReputeAPIError,
AuthenticationError,
RateLimitError,
ValidationError
};
Installation:
PHPΒΆ
PHP Client LibraryΒΆ
<?php
/**
* ReputeAPI PHP Client Library
* Complete implementation with error handling
*/
class ReputeAPIException extends Exception {}
class AuthenticationException extends ReputeAPIException {}
class RateLimitException extends ReputeAPIException {
public $retryAfter;
public function __construct($message, $retryAfter = 60) {
parent::__construct($message);
$this->retryAfter = $retryAfter;
}
}
class ValidationException extends ReputeAPIException {}
class ReputeAPIClient {
private $apiKey;
private $baseUrl;
private $timeout;
/**
* Initialize client
*
* @param string $apiKey Your API key
* @param string $baseUrl API base URL
* @param int $timeout Request timeout in seconds
*/
public function __construct($apiKey, $baseUrl = 'https://api.reputeapi.com', $timeout = 10) {
$this->apiKey = $apiKey;
$this->baseUrl = $baseUrl;
$this->timeout = $timeout;
}
/**
* Make HTTP request
*/
private function request($method, $endpoint, $params = [], $data = null) {
$url = $this->baseUrl . $endpoint;
if ($method === 'GET' && !empty($params)) {
$url .= '?' . http_build_query($params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $this->apiKey,
'User-Agent: ReputeAPI-PHP-Client/1.0',
'Content-Type: application/json'
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if ($data !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headers = curl_getinfo($ch);
curl_close($ch);
return $this->handleResponse($response, $httpCode, $headers);
}
/**
* Handle API response
*/
private function handleResponse($response, $httpCode, $headers) {
$data = json_decode($response, true);
if ($httpCode === 401) {
throw new AuthenticationException('Invalid or missing API key');
} elseif ($httpCode === 429) {
$retryAfter = isset($headers['retry-after']) ? (int)$headers['retry-after'] : 60;
throw new RateLimitException('Rate limit exceeded', $retryAfter);
} elseif ($httpCode === 400) {
$message = isset($data['message']) ? $data['message'] : 'Invalid request';
throw new ValidationException($message);
} elseif ($httpCode >= 500) {
throw new ReputeAPIException("Server error: $httpCode");
} elseif ($httpCode !== 200) {
throw new ReputeAPIException("HTTP error: $httpCode");
}
return $data;
}
/**
* Check domain
*
* @param string $domain Domain to check
* @param array $options Check options
* @return array Validation results
*/
public function checkDomain($domain, $options = []) {
$params = [
'domain' => $domain,
'verbose' => isset($options['verbose']) ? $options['verbose'] : false,
'refresh' => isset($options['refresh']) ? $options['refresh'] : false
];
if (isset($options['selectors']) && is_array($options['selectors'])) {
$params['selectors'] = implode(',', $options['selectors']);
}
return $this->request('GET', '/api/v1/check', $params);
}
/**
* Get score
*
* @param string $domain Domain to check
* @param bool $refresh Bypass cache
* @return array Score and top issues
*/
public function getScore($domain, $refresh = false) {
$params = [
'domain' => $domain,
'refresh' => $refresh
];
return $this->request('GET', '/api/v1/score', $params);
}
/**
* Get recommendations
*
* @param string $domain Domain to check
* @param string $severity Filter by severity
* @return array Recommendations
*/
public function getRecommendations($domain, $severity = null) {
$data = ['domain' => $domain];
if ($severity !== null) {
$data['severity'] = $severity;
}
return $this->request('POST', '/api/v1/recommendations', [], $data);
}
/**
* Get usage statistics
*
* @return array Usage stats
*/
public function getUsage() {
return $this->request('GET', '/api/v1/usage');
}
/**
* Bulk validate domains
*
* @param array $domains List of domains
* @return array Results for all domains
*/
public function bulkValidate($domains) {
$data = [
'domains' => array_map(function($d) {
return ['domain' => $d];
}, $domains),
'options' => ['include_score' => true]
];
return $this->request('POST', '/v1/bulk-validate', [], $data);
}
}
// Usage Example
$client = new ReputeAPIClient('your-api-key');
try {
// Check domain
$result = $client->checkDomain('example.com');
echo "Domain: {$result['domain']}\n";
echo "Score: {$result['score']}/100\n";
echo "Grade: {$result['grade']}\n";
// Get recommendations
$recs = $client->getRecommendations('example.com', 'high');
echo "\nHigh Priority Recommendations:\n";
foreach ($recs['recommendations'] as $rec) {
echo " - {$rec['message']}\n";
}
} catch (AuthenticationException $e) {
echo "Authentication error: {$e->getMessage()}\n";
} catch (RateLimitException $e) {
echo "Rate limit exceeded. Retry after {$e->retryAfter}s\n";
} catch (ValidationException $e) {
echo "Validation error: {$e->getMessage()}\n";
} catch (ReputeAPIException $e) {
echo "API error: {$e->getMessage()}\n";
}
?>
RubyΒΆ
Ruby ClientΒΆ
# repute_api_client.rb
require 'net/http'
require 'json'
require 'uri'
class ReputeAPIError < StandardError; end
class AuthenticationError < ReputeAPIError; end
class RateLimitError < ReputeAPIError
attr_reader :retry_after
def initialize(message, retry_after = 60)
super(message)
@retry_after = retry_after
end
end
class ValidationError < ReputeAPIError; end
class ReputeAPIClient
attr_reader :api_key, :base_url, :timeout
def initialize(api_key, base_url = 'https://api.reputeapi.com', timeout = 10)
@api_key = api_key
@base_url = base_url
@timeout = timeout
end
def check_domain(domain, options = {})
params = {
domain: domain,
verbose: options[:verbose] || false,
refresh: options[:refresh] || false
}
params[:selectors] = options[:selectors].join(',') if options[:selectors]
request(:get, '/api/v1/check', params)
end
def get_score(domain, refresh = false)
params = { domain: domain, refresh: refresh }
request(:get, '/api/v1/score', params)
end
def get_recommendations(domain, severity = nil)
data = { domain: domain }
data[:severity] = severity if severity
request(:post, '/api/v1/recommendations', nil, data)
end
def get_usage
request(:get, '/api/v1/usage')
end
def bulk_validate(domains)
data = {
domains: domains.map { |d| { domain: d } },
options: { include_score: true }
}
request(:post, '/v1/bulk-validate', nil, data)
end
private
def request(method, endpoint, params = nil, data = nil)
uri = URI.parse("#{@base_url}#{endpoint}")
uri.query = URI.encode_www_form(params) if params && method == :get
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.read_timeout = @timeout
request = case method
when :get
Net::HTTP::Get.new(uri)
when :post
Net::HTTP::Post.new(uri)
end
request['X-API-Key'] = @api_key
request['User-Agent'] = 'ReputeAPI-Ruby-Client/1.0'
request['Content-Type'] = 'application/json'
request.body = data.to_json if data
response = http.request(request)
handle_response(response)
end
def handle_response(response)
case response.code.to_i
when 200
JSON.parse(response.body)
when 401
raise AuthenticationError, 'Invalid or missing API key'
when 429
retry_after = response['Retry-After'].to_i || 60
raise RateLimitError.new('Rate limit exceeded', retry_after)
when 400
data = JSON.parse(response.body)
raise ValidationError, data['message'] || 'Invalid request'
when 500..599
raise ReputeAPIError, "Server error: #{response.code}"
else
raise ReputeAPIError, "HTTP error: #{response.code}"
end
end
end
# Usage Example
client = ReputeAPIClient.new('your-api-key')
begin
# Check domain
result = client.check_domain('example.com')
puts "Domain: #{result['domain']}"
puts "Score: #{result['score']}/100"
puts "Grade: #{result['grade']}"
# Get recommendations
recs = client.get_recommendations('example.com', 'high')
puts "\nHigh Priority Recommendations:"
recs['recommendations'].each do |rec|
puts " - #{rec['message']}"
end
rescue AuthenticationError => e
puts "Authentication error: #{e.message}"
rescue RateLimitError => e
puts "Rate limit exceeded. Retry after #{e.retry_after}s"
rescue ValidationError => e
puts "Validation error: #{e.message}"
rescue ReputeAPIError => e
puts "API error: #{e.message}"
end
GoΒΆ
Go ClientΒΆ
// repute_api_client.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
type ReputeAPIClient struct {
APIKey string
BaseURL string
HTTPClient *http.Client
}
type CheckResult struct {
Domain string `json:"domain"`
Score int `json:"score"`
Grade string `json:"grade"`
SPF SPFData `json:"spf"`
DKIM DKIMData `json:"dkim"`
DMARC DMARCData `json:"dmarc"`
Issues []Issue `json:"issues"`
}
type SPFData struct {
Present bool `json:"present"`
Valid bool `json:"valid"`
Record string `json:"record"`
}
type DKIMData struct {
DiscoveredSelectors []string `json:"discovered_selectors"`
ValidatedKeys []DKIMKey `json:"validated_keys"`
}
type DKIMKey struct {
Selector string `json:"selector"`
Valid bool `json:"valid"`
KeySize int `json:"key_size"`
}
type DMARCData struct {
Present bool `json:"present"`
Valid bool `json:"valid"`
Record string `json:"record"`
Policy string `json:"policy"`
}
type Issue struct {
Code string `json:"code"`
Severity string `json:"severity"`
Message string `json:"message"`
Remediation string `json:"remediation"`
}
type APIError struct {
StatusCode int
Message string
RetryAfter int
}
func (e *APIError) Error() string {
return fmt.Sprintf("API error %d: %s", e.StatusCode, e.Message)
}
func NewClient(apiKey string) *ReputeAPIClient {
return &ReputeAPIClient{
APIKey: apiKey,
BaseURL: "https://api.reputeapi.com",
HTTPClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (c *ReputeAPIClient) request(method, endpoint string, params map[string]string, data interface{}) ([]byte, error) {
url := c.BaseURL + endpoint
// Add query parameters for GET requests
if method == "GET" && len(params) > 0 {
values := make([]string, 0, len(params))
for k, v := range params {
values = append(values, fmt.Sprintf("%s=%s", k, v))
}
url += "?" + strings.Join(values, "&")
}
var reqBody []byte
var err error
if data != nil {
reqBody, err = json.Marshal(data)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(reqBody))
if err != nil {
return nil, err
}
req.Header.Set("X-API-Key", c.APIKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "ReputeAPI-Go-Client/1.0")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, c.handleError(resp, body)
}
return body, nil
}
func (c *ReputeAPIClient) handleError(resp *http.Response, body []byte) error {
var errorData map[string]interface{}
json.Unmarshal(body, &errorData)
message := "Unknown error"
if msg, ok := errorData["message"].(string); ok {
message = msg
}
apiErr := &APIError{
StatusCode: resp.StatusCode,
Message: message,
}
if resp.StatusCode == http.StatusTooManyRequests {
retryAfter := resp.Header.Get("Retry-After")
if retryAfter != "" {
if val, err := strconv.Atoi(retryAfter); err == nil {
apiErr.RetryAfter = val
}
}
}
return apiErr
}
func (c *ReputeAPIClient) CheckDomain(domain string, selectors []string) (*CheckResult, error) {
params := map[string]string{
"domain": domain,
}
if len(selectors) > 0 {
params["selectors"] = strings.Join(selectors, ",")
}
body, err := c.request("GET", "/api/v1/check", params, nil)
if err != nil {
return nil, err
}
var result CheckResult
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
client := NewClient("your-api-key")
result, err := client.CheckDomain("example.com", nil)
if err != nil {
if apiErr, ok := err.(*APIError); ok {
if apiErr.StatusCode == http.StatusTooManyRequests {
fmt.Printf("Rate limited. Retry after %d seconds\n", apiErr.RetryAfter)
} else {
fmt.Printf("API error: %s\n", apiErr.Message)
}
} else {
fmt.Printf("Error: %v\n", err)
}
return
}
fmt.Printf("Domain: %s\n", result.Domain)
fmt.Printf("Score: %d/100\n", result.Score)
fmt.Printf("Grade: %s\n", result.Grade)
if len(result.Issues) > 0 {
fmt.Printf("\nIssues Found:\n")
for _, issue := range result.Issues {
fmt.Printf(" [%s] %s\n", strings.ToUpper(issue.Severity), issue.Message)
}
}
}
Bash ScriptsΒΆ
Simple Bash ScriptΒΆ
#!/bin/bash
# check_domain.sh - Simple domain checker
API_KEY="${REPUTE_API_KEY}"
BASE_URL="https://api.reputeapi.com"
if [ -z "$API_KEY" ]; then
echo "Error: REPUTE_API_KEY environment variable not set"
exit 1
fi
check_domain() {
local domain=$1
response=$(curl -s -w "\n%{http_code}" \
-H "X-API-Key: $API_KEY" \
"$BASE_URL/api/v1/check?domain=$domain")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [ "$http_code" -eq 200 ]; then
echo "β
Success!"
echo "$body" | jq -r '
"Domain: \(.domain)",
"Score: \(.score)/100",
"Grade: \(.grade)",
"",
"SPF: \(if .spf.present then "β" else "β" end)",
"DKIM: \(if .dkim.validated_keys | length > 0 then "β" else "β" end)",
"DMARC: \(if .dmarc.present then "β" else "β" end)"
'
issues=$(echo "$body" | jq '.issues | length')
if [ "$issues" -gt 0 ]; then
echo ""
echo "Issues Found: $issues"
echo "$body" | jq -r '.issues[] | " [\(.severity | ascii_upcase)] \(.message)"'
fi
else
echo "β Error: HTTP $http_code"
echo "$body" | jq '.'
exit 1
fi
}
# Main
if [ $# -eq 0 ]; then
echo "Usage: $0 <domain>"
exit 1
fi
check_domain "$1"
Usage:
Next StepsΒΆ
- Basic Examples: See Basic Validation
- Bulk Processing: Check Bulk Validation
- Real-World Use Cases: Browse Common Scenarios
- Troubleshooting: Read Troubleshooting Guide