Python
Installation
Section titled “Installation”For Flask and Django:
pip install requestsFor FastAPI:
pip install fastapi httpx uvicornBasic Example
Section titled “Basic Example”import osimport 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()
# Usageresult = 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')Flask Integration
Section titled “Flask Integration”from flask import Flask, request, jsonifyimport osimport 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})Django Integration
Section titled “Django Integration”import jsonimport osimport requestsfrom django.http import JsonResponsefrom django.views.decorators.csrf import csrf_exemptfrom django.views.decorators.http import require_POST
@csrf_exempt@require_POSTdef 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})FastAPI Integration
Section titled “FastAPI Integration”from fastapi import FastAPIfrom pydantic import BaseModelimport osimport 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.
Error Handling
Section titled “Error Handling”import osimport timeimport 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.