Overview
This guide provides integration examples for popular frameworks, platforms, and languages to help you get started with Fraudiant quickly.Node.js / Express
Basic Integration
Copy
const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.use(express.json());
const FRAUDIANT_API_KEY = process.env.FRAUDIANT_API_KEY;
// Middleware to validate email
async function validateEmail(req, res, next) {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
try {
const response = await fetch(
`https://api.fraudiant.com/email/${encodeURIComponent(email)}`,
{
headers: { 'Authorization': `Bearer ${FRAUDIANT_API_KEY}` }
}
);
const validation = await response.json();
if (validation.disposable || validation.spam) {
return res.status(400).json({
error: 'Please provide a valid, non-disposable email address'
});
}
// Attach validation data to request
req.emailValidation = validation;
next();
} catch (error) {
console.error('Email validation error:', error);
// Fail open - allow signup if validation service is down
next();
}
}
// Registration endpoint
app.post('/api/register', validateEmail, async (req, res) => {
const { email, password } = req.body;
// Email is validated, proceed with registration
// Access validation data via req.emailValidation
res.json({ success: true, message: 'User registered' });
});
app.listen(3000);
With Caching
Copy
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 86400 }); // Cache for 24 hours
async function validateEmailWithCache(email) {
// Check cache first
const cached = cache.get(email);
if (cached) {
return cached;
}
// Call API
const response = await fetch(
`https://api.fraudiant.com/email/${email}`,
{
headers: { 'Authorization': `Bearer ${process.env.FRAUDIANT_API_KEY}` }
}
);
const validation = await response.json();
// Store in cache
cache.set(email, validation);
return validation;
}
Next.js
API Route
Copy
// pages/api/validate-email.ts
import type { NextApiRequest, NextApiResponse } from 'next';
type ValidationResponse = {
valid: boolean;
message?: string;
suggestion?: string;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<ValidationResponse>
) {
if (req.method !== 'POST') {
return res.status(405).json({ valid: false, message: 'Method not allowed' });
}
const { email } = req.body;
if (!email) {
return res.status(400).json({ valid: false, message: 'Email is required' });
}
try {
const response = await fetch(
`https://api.fraudiant.com/email/${encodeURIComponent(email)}`,
{
headers: {
'Authorization': `Bearer ${process.env.FRAUDIANT_API_KEY}`
}
}
);
const validation = await response.json();
// Check for typos
if (validation.did_you_mean) {
return res.json({
valid: true,
suggestion: validation.did_you_mean,
message: `Did you mean ${validation.did_you_mean}?`
});
}
// Validate email quality
if (validation.disposable || validation.spam || !validation.mx) {
return res.status(400).json({
valid: false,
message: 'Please provide a valid, non-disposable email address'
});
}
res.json({ valid: true });
} catch (error) {
console.error('Validation error:', error);
res.status(500).json({ valid: false, message: 'Validation service unavailable' });
}
}
Client Component
Copy
// components/SignupForm.tsx
'use client';
import { useState } from 'react';
export default function SignupForm() {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
const [suggestion, setSuggestion] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setSuggestion('');
const response = await fetch('/api/validate-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email })
});
const data = await response.json();
if (data.suggestion) {
setSuggestion(data.message);
return;
}
if (!data.valid) {
setError(data.message);
return;
}
// Proceed with registration
console.log('Email is valid, proceeding...');
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
required
/>
{error && <p className="error">{error}</p>}
{suggestion && <p className="suggestion">{suggestion}</p>}
<button type="submit">Sign Up</button>
</form>
);
}
Python / Django
Middleware
Copy
# middleware/email_validation.py
import requests
from django.conf import settings
from django.http import JsonResponse
class EmailValidationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_view(self, request, view_func, view_args, view_kwargs):
# Only validate on registration endpoints
if request.path == '/api/register/' and request.method == 'POST':
email = request.POST.get('email')
if not email:
return JsonResponse({'error': 'Email is required'}, status=400)
validation = self.validate_email(email)
if not validation['valid']:
return JsonResponse(
{'error': validation['message']},
status=400
)
# Attach validation to request
request.email_validation = validation['data']
return None
def validate_email(self, email):
try:
headers = {'Authorization': f'Bearer {settings.FRAUDIANT_API_KEY}'}
response = requests.get(
f'https://api.fraudiant.com/email/{email}',
headers=headers,
timeout=5
)
data = response.json()
if data.get('disposable') or data.get('spam'):
return {
'valid': False,
'message': 'Please provide a valid, non-disposable email address'
}
return {'valid': True, 'data': data}
except Exception as e:
print(f'Email validation error: {e}')
# Fail open
return {'valid': True, 'data': {}}
View Function
Copy
# views.py
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import requests
from django.conf import settings
@require_http_methods(["POST"])
def register_user(request):
email = request.POST.get('email')
password = request.POST.get('password')
# Validate with Fraudiant
validation = validate_email(email)
if not validation['valid']:
return JsonResponse({'error': validation['message']}, status=400)
# Proceed with registration
# ... your registration logic ...
return JsonResponse({'success': True})
def validate_email(email):
headers = {'Authorization': f'Bearer {settings.FRAUDIANT_API_KEY}'}
try:
response = requests.get(
f'https://api.fraudiant.com/email/{email}',
headers=headers,
timeout=5
)
data = response.json()
if data.get('disposable') or data.get('spam') or not data.get('mx'):
return {
'valid': False,
'message': 'Invalid or disposable email address'
}
return {'valid': True, 'data': data}
except requests.exceptions.RequestException as e:
print(f'Validation error: {e}')
# Fail open in case of service issues
return {'valid': True, 'data': {}}
PHP / Laravel
Service Class
Copy
<?php
// app/Services/EmailValidationService.php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
class EmailValidationService
{
private $apiKey;
private $baseUrl = 'https://api.fraudiant.com';
public function __construct()
{
$this->apiKey = config('services.fraudiant.api_key');
}
public function validate(string $email): array
{
// Check cache first
$cacheKey = 'email_validation_' . md5($email);
$cached = Cache::get($cacheKey);
if ($cached) {
return $cached;
}
try {
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $this->apiKey
])->get("{$this->baseUrl}/email/{$email}");
$data = $response->json();
$result = [
'valid' => !($data['disposable'] ?? false) &&
!($data['spam'] ?? false) &&
($data['mx'] ?? false),
'data' => $data,
'message' => $this->getValidationMessage($data)
];
// Cache for 24 hours
Cache::put($cacheKey, $result, now()->addDay());
return $result;
} catch (\Exception $e) {
\Log::error('Email validation error: ' . $e->getMessage());
// Fail open
return ['valid' => true, 'data' => [], 'message' => null];
}
}
private function getValidationMessage(array $data): ?string
{
if ($data['disposable'] ?? false) {
return 'Disposable email addresses are not allowed';
}
if ($data['spam'] ?? false) {
return 'This email domain is associated with spam';
}
if (!($data['mx'] ?? false)) {
return 'Email domain cannot receive emails';
}
if ($data['did_you_mean'] ?? null) {
return "Did you mean {$data['did_you_mean']}?";
}
return null;
}
}
Controller
Copy
<?php
// app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;
use App\Services\EmailValidationService;
use Illuminate\Http\Request;
class AuthController extends Controller
{
private $emailValidator;
public function __construct(EmailValidationService $emailValidator)
{
$this->emailValidator = $emailValidator;
}
public function register(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required|min:8'
]);
// Validate email with Fraudiant
$validation = $this->emailValidator->validate($request->email);
if (!$validation['valid']) {
return response()->json([
'error' => $validation['message']
], 400);
}
// Proceed with registration
// ... your registration logic ...
return response()->json(['success' => true]);
}
}
Configuration
Copy
<?php
// config/services.php
return [
// ... other services ...
'fraudiant' => [
'api_key' => env('FRAUDIANT_API_KEY'),
],
];
Ruby on Rails
Service Class
Copy
# app/services/email_validation_service.rb
class EmailValidationService
BASE_URL = 'https://api.fraudiant.com'
def initialize
@api_key = ENV['FRAUDIANT_API_KEY']
end
def validate(email)
# Check cache
cache_key = "email_validation_#{Digest::MD5.hexdigest(email)}"
cached = Rails.cache.read(cache_key)
return cached if cached
begin
response = HTTParty.get(
"#{BASE_URL}/email/#{URI.encode_www_form_component(email)}",
headers: { 'Authorization' => "Bearer #{@api_key}" },
timeout: 5
)
data = JSON.parse(response.body)
result = {
valid: !data['disposable'] && !data['spam'] && data['mx'],
data: data,
message: validation_message(data)
}
# Cache for 24 hours
Rails.cache.write(cache_key, result, expires_in: 24.hours)
result
rescue => e
Rails.logger.error("Email validation error: #{e.message}")
# Fail open
{ valid: true, data: {}, message: nil }
end
end
private
def validation_message(data)
return 'Disposable email addresses are not allowed' if data['disposable']
return 'This email domain is associated with spam' if data['spam']
return 'Email domain cannot receive emails' unless data['mx']
return "Did you mean #{data['did_you_mean']}?" if data['did_you_mean']
nil
end
end
Controller
Copy
# app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController
def create
email = params[:email]
validator = EmailValidationService.new
validation = validator.validate(email)
unless validation[:valid]
render json: { error: validation[:message] }, status: :bad_request
return
end
# Proceed with registration
# ... your registration logic ...
render json: { success: true }
end
end
Go
Copy
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
type ValidationResponse struct {
Status int `json:"status"`
Email string `json:"email"`
Disposable bool `json:"disposable"`
Spam bool `json:"spam"`
MX bool `json:"mx"`
}
type EmailValidator struct {
apiKey string
baseURL string
client *http.Client
}
func NewEmailValidator() *EmailValidator {
return &EmailValidator{
apiKey: os.Getenv("FRAUDIANT_API_KEY"),
baseURL: "https://api.fraudiant.com",
client: &http.Client{Timeout: 5 * time.Second},
}
}
func (v *EmailValidator) Validate(email string) (*ValidationResponse, error) {
url := fmt.Sprintf("%s/email/%s", v.baseURL, email)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+v.apiKey)
resp, err := v.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var validation ValidationResponse
if err := json.Unmarshal(body, &validation); err != nil {
return nil, err
}
return &validation, nil
}
func (v *EmailValidator) IsValid(email string) (bool, error) {
validation, err := v.Validate(email)
if err != nil {
return false, err
}
return !validation.Disposable && !validation.Spam && validation.MX, nil
}
// Usage in HTTP handler
func registerHandler(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
validator := NewEmailValidator()
valid, err := validator.IsValid(email)
if err != nil {
http.Error(w, "Validation service unavailable", http.StatusServiceUnavailable)
return
}
if !valid {
http.Error(w, "Invalid or disposable email address", http.StatusBadRequest)
return
}
// Proceed with registration
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]bool{"success": true})
}
Best Practices
Always implement caching
Always implement caching
Cache validation results for 24-48 hours to reduce API calls and improve performance.
Fail open on errors
Fail open on errors
If the Fraudiant API is unavailable, allow users to proceed rather than blocking them completely.
Use environment variables
Use environment variables
Never hardcode API keys. Use environment variables or secret management systems.
Implement rate limit handling
Implement rate limit handling
Handle 429 responses gracefully with exponential backoff.
Validate server-side
Validate server-side
Always validate on the server, never trust client-side validation alone.