Skip to content

Python

For Flask and Django:

Terminal window
pip install requests

For FastAPI:

Terminal window
pip install fastapi httpx uvicorn
import os
import requests
def verify_submission(form_data):
response = requests.post(
'https://api.formsentry.ai/v1/verify',
json={
'apiKey': os.environ['FORMSENTRY_API_KEY'],
'formId': os.environ['FORMSENTRY_FORM_ID'],
'payload': form_data
},
timeout=5
)
response.raise_for_status()
return response.json()
# Usage
result = verify_submission({
'name': 'John Doe',
'email': 'john@example.com',
'message': 'I would like to learn more about your services.'
})
if result['status'] == 'spam':
print(f"Spam detected: {result['reasoning']}")
else:
print('Legitimate submission')
from flask import Flask, request, jsonify
import os
import requests
app = Flask(__name__)
@app.route('/contact', methods=['POST'])
def contact():
form_data = request.get_json()
if not form_data:
return jsonify({'error': 'Invalid submission'}), 400
try:
verification = requests.post(
'https://api.formsentry.ai/v1/verify',
json={
'apiKey': os.environ['FORMSENTRY_API_KEY'],
'formId': os.environ['FORMSENTRY_FORM_ID'],
'payload': form_data
},
timeout=5
)
verification.raise_for_status()
result = verification.json()
except Exception as e:
# Fail open — if FormSentry is unreachable, allow the submission
print("FormSentry error:", str(e))
result = {"status": "legitimate", "confidence": 0.0}
if result.get('status') == 'spam':
# Silently accept to avoid tipping off spammers
return jsonify({'success': True})
# TODO: Process the legitimate submission
return jsonify({'success': True})
views.py
import json
import os
import requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
@csrf_exempt
@require_POST
def contact(request):
try:
form_data = json.loads(request.body)
except (json.JSONDecodeError, ValueError):
return JsonResponse({'error': 'Invalid JSON'}, status=400)
try:
verification = requests.post(
'https://api.formsentry.ai/v1/verify',
json={
'apiKey': os.environ['FORMSENTRY_API_KEY'],
'formId': os.environ['FORMSENTRY_FORM_ID'],
'payload': form_data
},
timeout=5
)
verification.raise_for_status()
result = verification.json()
except Exception as e:
# Fail open — if FormSentry is unreachable, allow the submission
print("FormSentry error:", str(e))
result = {"status": "legitimate", "confidence": 0.0}
if result.get('status') == 'spam':
return JsonResponse({'success': True})
# TODO: Process the legitimate submission
return JsonResponse({'success': True})
from fastapi import FastAPI
from pydantic import BaseModel
import os
import httpx
app = FastAPI()
class ContactForm(BaseModel):
name: str
email: str
message: str
@app.post('/contact')
async def contact(form: ContactForm):
try:
async with httpx.AsyncClient() as client:
verification = await client.post(
'https://api.formsentry.ai/v1/verify',
json={
'apiKey': os.environ['FORMSENTRY_API_KEY'],
'formId': os.environ['FORMSENTRY_FORM_ID'],
'payload': form.model_dump()
},
timeout=5.0
)
verification.raise_for_status()
result = verification.json()
except Exception as e:
# Fail open — if FormSentry is unreachable, allow the submission
print("FormSentry error:", str(e))
result = {"status": "legitimate", "confidence": 0.0}
if result.get('status') == 'spam':
return {'success': True}
# TODO: Process the legitimate submission
return {'success': True}

FastAPI handles input validation automatically via the Pydantic model — invalid requests return a 422 error before reaching your endpoint.

import os
import time
import requests
def verify_with_retry(payload, max_retries=3):
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
'https://api.formsentry.ai/v1/verify',
json={
'apiKey': os.environ['FORMSENTRY_API_KEY'],
'formId': os.environ['FORMSENTRY_FORM_ID'],
'payload': payload
},
timeout=5
)
if response.ok:
return response.json()
if response.status_code in (429, 500, 502, 503):
delay = min(2 ** (attempt - 1), 5)
time.sleep(delay)
continue
response.raise_for_status()
except requests.exceptions.Timeout:
if attempt == max_retries:
raise
raise Exception('Max retries exceeded')

See Errors for all error codes and retry strategies.