Guide
Content Moderation in Python: FastAPI and Django Examples
If your backend is Python, moderation should happen there: after the request arrives, before the row is written. Client-side checks are easy to bypass, and moderating content after it's already visible means somebody saw it.
This guide covers the vettly Python SDK (0.1.9 on PyPI). It works through a FastAPI endpoint that checks content before saving, a Django form-validation pattern, timeouts and retries, the fail-open vs fail-closed decision, batch checks, and a plain requests version for when you can't add a dependency.
Install and first check
pip install vettly
The package needs Python 3.8 or later and pulls in httpx and pydantic 2. It exports two clients: ModerationClient for sync code and AsyncModerationClient for asyncio. api_key is required, and the SDK doesn't read environment variables itself, so pass the key explicitly:
import osfrom vettly import ModerationClientclient = ModerationClient(api_key=os.environ["VETTLY_API_KEY"])result = client.check(content="Is this still available? Can pick up Saturday.",policy_id="moderate",)print(result.action.value) # "allow", "flag" or "block"print(result.safe, result.flagged)for cat in result.categories:if cat.triggered:print(cat.category, cat.score)
policy_id is either a built-in policy (lenient, moderate, strict) or the ID of a policy you created. The policy guide covers writing your own. check() also accepts content_type (text, image or video; for images and video, content is a URL), metadata (a dict stored with the decision) and request_id, an idempotency key. check_image(image_url, policy_id) is shorthand for an image check.
Both clients support context managers (with / async with) and have close(). Create one client per process and reuse it. Creating a client per request throws away the connection pool. In a web app that means one client at startup, not one per view or per handler call.
FastAPI: check before saving
In FastAPI, use AsyncModerationClient so the check doesn't block the event loop. Create the client in the lifespan handler, check the comment, and decide what to store based on action:
import asyncioimport loggingimport osfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, HTTPException, Requestfrom pydantic import BaseModel, ValidationErrorfrom vettly import AsyncModerationClient, VettlyAuthError, VettlyErrorfrom app.db import save_comment # your persistence layerlog = logging.getLogger(__name__)POLICY_ID = "community-comments"CHECK_BUDGET_SECONDS = 4.0@asynccontextmanagerasync def lifespan(app: FastAPI):app.state.vettly = AsyncModerationClient(api_key=os.environ["VETTLY_API_KEY"],timeout=3.0, # per attemptmax_retries=1, # one retry on 429 / 5xx / network errorsretry_delay=0.25,)yieldawait app.state.vettly.close()app = FastAPI(lifespan=lifespan)class CommentIn(BaseModel):post_id: intbody: str@app.post("/comments", status_code=201)async def create_comment(comment: CommentIn, request: Request):client: AsyncModerationClient = request.app.state.vettlytry:result = await asyncio.wait_for(client.check(content=comment.body, policy_id=POLICY_ID),timeout=CHECK_BUDGET_SECONDS,)except VettlyAuthError:# Misconfiguration, not an outage. Don't paper over it.log.exception("Vettly rejected the API key")raise HTTPException(status_code=503, detail="Comments are temporarily unavailable")except (VettlyError, ValidationError, asyncio.TimeoutError):log.warning("Moderation unavailable, holding comment for review", exc_info=True)row = await save_comment(comment, status="pending_review", decision_id=None)return {"id": row.id, "status": "pending_review"}action = result.action.valueif action == "block":reasons = [c.category for c in result.categories if c.triggered]raise HTTPException(status_code=422,detail={"error": "Comment violates community guidelines", "categories": reasons},)status = "published" if action == "allow" else "pending_review"row = await save_comment(comment, status=status, decision_id=result.id)return {"id": row.id, "status": status}
A few details worth explaining:
- The decision ID goes on the row.
result.idis the decision ID. Storing it on the comment lets you trace each row back to the decision that let it through or held it, which you'll want when a user appeals or a reviewer asks why something was blocked. Even if you never look the decision up, keeping the ID costs one column. See audit trails. flagmeans "save but don't show". Flagged content gets written withpending_review. It stays hidden until a reviewer approves it, and the user isn't told they were rejected.asyncio.wait_forsets a hard deadline. The SDK'stimeoutapplies to each attempt, and retries add more. Wrapping the call gives the endpoint one end-to-end budget.ValidationErroris caught alongsideVettlyError. The SDK parses responses into pydantic models (CheckResponse,CategoryResult). If a response doesn't match the model, pydantic raisesValidationError, which is not aVettlyErrorsubclass. A moderation wrapper on the request path should handle both, or a parsing problem becomes a 500 for your users.- Auth errors aren't treated as outages. A revoked or missing key fails every request. Failing open on
VettlyAuthErrorwould silently turn moderation off.
Django: validate in the form
The tempting place for moderation in Django is a pre_save signal or an overridden Model.save(). Both work, but both run in the middle of persistence. The network call holds any open transaction, and the only way to reject content is to raise an exception from inside save(). That's awkward to turn into a field error on a form.
Form validation is the better fit. clean_<field> runs before anything is written, and raising forms.ValidationError gives the user a normal error message. Put the API call in a small service module so forms, DRF serializers and management commands share one path:
import loggingfrom dataclasses import dataclassfrom functools import lru_cachefrom typing import List, Optionalfrom django.conf import settingsfrom pydantic import ValidationErrorfrom vettly import ModerationClient, VettlyAuthError, VettlyErrorlog = logging.getLogger(__name__)@dataclassclass Verdict:action: str # "allow" | "flag" | "block" | "unavailable"decision_id: Optional[str]categories: List[str]@lru_cache(maxsize=1)def get_client() -> ModerationClient:return ModerationClient(api_key=settings.VETTLY_API_KEY, # your own setting, loaded from envtimeout=3.0,max_retries=1,retry_delay=0.25,)def moderate_text(text: str, policy_id: str = "community-comments") -> Verdict:try:result = get_client().check(content=text, policy_id=policy_id)except VettlyAuthError:raise # misconfiguration: surface itexcept (VettlyError, ValidationError):log.warning("Moderation unavailable", exc_info=True)return Verdict(action="unavailable", decision_id=None, categories=[])return Verdict(action=result.action.value,decision_id=result.id,categories=[c.category for c in result.categories if c.triggered],)
The form calls it during validation and keeps the verdict for the view:
from django import formsfrom .models import Commentfrom .moderation import moderate_textclass CommentForm(forms.ModelForm):class Meta:model = Commentfields = ["body"]def clean_body(self):body = self.cleaned_data["body"]verdict = moderate_text(body)if verdict.action == "block":raise forms.ValidationError("This comment goes against our community guidelines.")self.verdict = verdictreturn body
from django.shortcuts import get_object_or_404, redirect, renderfrom .forms import CommentFormfrom .models import Comment, Postdef add_comment(request, post_id):post = get_object_or_404(Post, pk=post_id)form = CommentForm(request.POST or None)if request.method == "POST" and form.is_valid():comment = form.save(commit=False)comment.post = postcomment.author = request.usercomment.moderation_decision_id = form.verdict.decision_idcomment.status = (Comment.Status.PUBLISHEDif form.verdict.action == "allow"else Comment.Status.PENDING_REVIEW # flag, or moderation unavailable)comment.save()return redirect(post)return render(request, "comments/add.html", {"form": form, "post": post})
The model needs two fields: a status with choices and a nullable moderation_decision_id CharField. For Django REST Framework, the same moderate_text call goes in the serializer's validate_body, raising serializers.ValidationError on block.
The sync client fits Django's default WSGI setup. If you're on async views, use AsyncModerationClient the same way as the FastAPI example. Don't call the sync client from an async view: its retry backoff uses time.sleep, which would block the event loop.
Images and uploads
Images work through the same call. Pass a URL the API can fetch, or a base64 data URI, to check_image:
result = client.check_image(image_url=upload.public_url, # or "data:image/jpeg;base64,..."policy_id="profile-images",)if result.action.value != "allow":mark_avatar_hidden(upload)
There are two common mistakes here. The first is passing a URL that only your network can reach, such as a presigned URL that has already expired, a localhost URL or a private bucket. The API has to fetch the image, so the URL must be reachable from the internet when the check runs. The second is moderating an image before it's stored, then serving a different object later. Check the exact object you're going to serve. If you resize or transcode the image after upload, check the version users will see. Image checks take longer than text checks, so for profile photos and listings it's often better to store the upload as hidden, check it in a background task, and publish on allow. Then the upload request doesn't wait on the check. The image moderation guide covers policy choices for visual content.
Testing your handlers
Don't call the real API in unit tests for your views. Wrap the client the way moderate_text does, and patch that one function. Then you can test each branch: allow publishes, flag saves as pending, block returns a form error or a 422, and an unavailable verdict holds the content. With Django, unittest.mock.patch("comments.forms.moderate_text") returning a Verdict is all it takes. In FastAPI, swap app.state.vettly for a stub with an async check method. Keep one integration test that hits the API with a test key and a known-safe string, so a broken key or a renamed policy shows up in CI instead of production.
Timeouts and retries
The defaults are built for scripts and batch jobs, not request handlers:
timeout(default 30.0): seconds per attempt.max_retries(default 3): retries after the first attempt.retry_delay(default 1.0): base for exponential backoff, giving 1s, 2s, 4s.
Retries happen on 429 rate limits (respecting Retry-After when present), 5xx responses, timeouts and network errors. Quota errors and other 4xx responses aren't retried. With the defaults, a struggling network can hold a request for four 30-second attempts plus 7 seconds of backoff, a little over two minutes. Your load balancer will time the request out long before then.
For checks on the request path, timeout=3.0, max_retries=1, retry_delay=0.25 caps the worst case at roughly six seconds, and asyncio.wait_for can tighten it further. Keep the defaults for backfills and cron jobs, where finishing matters more than speed.
When the SDK gives up, it raises a typed exception. All of them inherit from VettlyError:
VettlyAuthError: 401, invalid or missing key.VettlyRateLimitError: 429 after retries; hasretry_after.VettlyQuotaError: 429 withQUOTA_EXCEEDED; hasquota.VettlyValidationError: 422, bad request body; haserrors.VettlyServerError: 5xx after retries.VettlyAPIError: Other failures, including exhausted network retries (code="NETWORK_ERROR").
Fail open or fail closed
Every moderation integration has to decide what happens when the check can't run. There's no universal answer, but there is a sensible default for each surface:
- Fail open (publish anyway) when the content is low-risk and the cost of blocking legitimate users is high. Examples: comments in an adult community with active human moderation, or internal tools.
- Fail closed when a miss is expensive. Examples: anything shown to minors, public images, DMs from strangers, and marketplace listings, where scams cost real money.
- Hold for review is usually the best version of fail closed, and it's what both examples above do. The content is saved but not shown, the user gets a normal "posted" response, and a reviewer or a re-check job picks it up later. Users don't get punished for your outage, and nothing harmful goes live unchecked.
If you hold content, run a job that re-checks pending_review rows with no decision ID once the API is reachable again. Otherwise the review queue fills with items nobody needs to look at. The error-handling guide has more patterns, including circuit breakers.
One more case: the REST docs list a fourth action, warn, which policies can return through confidence bands. The 0.1.9 SDK's Action enum has allow, flag and block. If your policy uses warn, test a warn-range message through the typed client before you rely on it, or use the raw HTTP path below. The handlers above treat anything that isn't allow as needing review.
Batch checks
For backfills, imports or re-moderating old content after a policy change, batch_check sends many items in one request:
import osfrom vettly import BatchItem, ModerationClientclient = ModerationClient(api_key=os.environ["VETTLY_API_KEY"]) # defaults are fine hereitems = [BatchItem(id=str(c.id), content=c.body) for c in comments_page]batch = client.batch_check(policy_id="community-comments", items=items)for r in batch.results or []:print(r.id, r.action.value)
Each BatchItem takes an id, content, and optionally content_type and metadata. Use your own primary key as the id so you can map results back to rows. For jobs too large to wait on, the sync client also has batch_check_async(policy_id, items, webhook_url), which returns a batch ID and delivers results to your webhook. Verify those deliveries with verify_webhook_signature, which is covered in the webhooks docs. AsyncModerationClient has batch_check but not the webhook variant.
Test policy logic without provider calls
The sync client's dry_run(policy_id, mock_scores=...) calls POST /v1/check/dry-run. That endpoint evaluates a policy against category scores you supply, without calling a moderation provider, which makes it useful for checking threshold logic in CI:
import osfrom vettly import ModerationClientclient = ModerationClient(api_key=os.environ["VETTLY_API_KEY"])for score in (0.4, 0.6, 0.9):result = client.dry_run("community-comments", mock_scores={"harassment": score})print(score, result)
dry_run returns a plain dict, not a typed model. Print it once and see what your policy returns before you write assertions against it. If you'd rather iterate on policies interactively, the Vettly MCP server runs the same kind of loop from Claude or Cursor.
Without the SDK: plain requests
If you can't add a dependency, or you want full control over parsing, the REST call is small. Send POST https://api.vettly.dev/v1/check with a Bearer key:
import osimport requestsVETTLY_CHECK_URL = "https://api.vettly.dev/v1/check"_session = requests.Session()_session.headers["Authorization"] = f"Bearer {os.environ['VETTLY_API_KEY']}"def check_text(text, policy_id="moderate", timeout=3.0):resp = _session.post(VETTLY_CHECK_URL,json={"content": text, "policyId": policy_id, "contentType": "text"},timeout=timeout,)resp.raise_for_status()data = resp.json()return {"action": data["action"], # allow | warn | flag | block"decision_id": data.get("decisionId"),"safe": data.get("safe"),"triggered": [c["category"] for c in data.get("categories", []) if c.get("triggered")],}
The request body takes content and policyId (both required), plus optional contentType, language (an ISO 639-1 code), metadata and requestId. A response looks like this:
{"safe": true,"flagged": false,"action": "allow","categories": [{ "category": "violence", "score": 0.05, "threshold": 0.7, "triggered": false }],"decisionId": "dec_abc123xyz","provider": "openai_gpt","latency": 234,"cost": 0.001}
The function reads only action, decisionId, safe and the category name and triggered flag. That keeps it working if fields are added later. You also own retries and error handling: raise_for_status() raises requests.HTTPError for 401, 404 (unknown policy), 422 and 429, and requests.Timeout covers the timeout. Wrap the call in the same fail-open or hold-for-review logic as the SDK examples. The REST reference and error codes list the full request schema and status codes.
Checklist
- Moderate on the server, before the write, and store the decision ID on the row.
- Create one client per process. Use
AsyncModerationClientin async frameworks. - Lower
timeoutandmax_retriesfor request-path checks, and set an end-to-end deadline. - Catch
VettlyErrorand pydantic'sValidationError, and treatVettlyAuthErroras a configuration bug. - Choose fail-open, fail-closed or hold-for-review per surface, not per app.
- Use
batch_checkfor backfills anddry_runfor threshold logic.
The full SDK reference is in the Python integration docs. For other content types, see the image moderation guide. Plan limits and pricing are on the pricing page, and the content moderation API overview covers what the API checks.
Frequently asked questions
How do I install the Vettly Python SDK?
Run pip install vettly. It supports Python 3.8 and later and depends on httpx and pydantic 2. Import ModerationClient for sync code or AsyncModerationClient for asyncio frameworks like FastAPI.
Does the SDK read VETTLY_API_KEY automatically?
No. api_key is a required argument. Read it from your environment or settings yourself, for example ModerationClient(api_key=os.environ['VETTLY_API_KEY']).
What are the default timeouts and retries?
A 30-second request timeout and 3 retries with exponential backoff (1s, 2s, 4s) on 429s, 5xx responses, timeouts and network errors. That can add up to about two minutes in the worst case, so lower timeout and max_retries for request-path checks.
Should moderation fail open or fail closed?
It depends on the surface. Low-risk text in an adult community can fail open. Content shown to minors, public images and DMs from strangers should fail closed, ideally by holding content for review rather than rejecting the user.
Can I call the API without the SDK?
Yes. POST https://api.vettly.dev/v1/check with an Authorization: Bearer header and a JSON body containing content and policyId. The response includes decisionId, safe, flagged, action and categories.