Profanity Filter API: Filtering User Text With Working Code

Why a Profanity Filter Is Harder Than a List of Words
Your product has user text going live. A chat message, a comment under an article, a marketplace review, a player name in a game lobby. The text reaches the screen or the database and nothing between the input field and the render checks whether it is something you actually want to publish. Every day it is not filtered is a day you are relying on users not to abuse the feature.
The first instinct is a blocklist. Keep an array of banned words, lowercase the incoming message, check whether any banned word appears, and reject the message if it does. It takes twenty minutes to write, and it works in the demo.
Then production happens:
- Character substitutions.
@fora,1fori,$fors. A plain list of words does not match a word that has been deliberately rewritten. - Spacing and repetition. Insert a space between every letter, or double one letter, and naive matching walks straight past it.
- Innocent text that looks guilty. Many implementations match substrings, so a place name, a job title, a musical term, a medical phrase or an ordinary word contains the banned sequence. This is the classic substring problem, and it produces support tickets from users who did nothing wrong.
- Language collisions. A word that is profane in one language is unremarkable in another, and a list built for one language does not protect a product with users in many.
- Maintenance. Slang moves. New evasions appear weekly. Someone has to own the list, review the reports and ship the updates, forever.
Meanwhile the filter has to respect a hard constraint: a message is posted in milliseconds. Users notice a lag between pressing send and seeing their message appear. So whatever decides whether the text is acceptable has to be fast enough to sit in the write path, and it has to return something your application can act on. Not a number you have to interpret, but a decision you can branch on.
This article covers the two general approaches to that problem, shows honest working code for a local filter along with the cases where it fails, and explains where a hosted moderation API fits and what to look for when you compare one.
Two General Approaches to Filtering Profanity
Approach 1: a local blocklist or regex filter
You own everything: the word list, the normalization step, the matching rules and the response. Text never leaves your infrastructure, there is no per-request cost and there is no network round trip, so latency is whatever your matching code costs. On a warm process that is microseconds.
The trade-offs are the ones above. Coverage is exactly as good as your list and your normalization, false positives are yours to debug, and every new language, surface or evasion is a new task on your backlog. Local filters tend to grow in layers: first a set of words, then a leet-speak translation table, then word-boundary matching, then an allowlist of legitimate words that keep tripping the filter, then per-language lists. Each addition fixes one class of error and often widens another.
To be fair to the approach, it is the right answer for some products: a small internal tool, a single-language community with a narrow vocabulary, or a cheap pre-filter in front of a second layer.
Approach 2: a classification or moderation API
Instead of a list, you send the text to a model and get a decision back. There is no list to maintain and no normalization to write, and a model can be trained on the kind of variation that defeats substring matching — the substitutions, the spacing, the creative misspellings.
The costs are real too. You are adding a network call to the request path, unless the model can be self-hosted, in which case the call stays on your own network. You are sending user text to a third party if you use a hosted service, which matters for regulated data, enterprise customers and privacy commitments in your own terms of service. And you are adding a dependency: if the provider is slow or unavailable, you need to have decided in advance what your application does.
How to compare the options
Judge each option on the same criteria, and check the vendor's current documentation, because features, limits and terms change:
- Categories covered. Does the tool answer only the profanity question, or does it also report categories such as hate, harassment, self-harm, adult content, violence, drugs, weapons, PII, spam and minor safety? One call that answers several questions is less code than three separate checks.
- Decision versus score. Does the response return a boolean you can branch on, or a score you must compare against a threshold you own? A score gives you a dial, but the dial becomes your problem: you have to pick the number, justify it to your team and revisit it every time the data shifts. A boolean is a branch in your code.
- Latency. What does a call add to your write path, at the median and at the tail, and what happens under load?
- Language coverage. Which languages does the tool handle well, and does it cope with the code-switching, transliteration and mixed-script text real users produce?
- Deployment options. Hosted only, or can the model run inside your own infrastructure when text cannot leave it?
- How the vendor handles your text. Stored, logged, used for training, retained for how long? Find this in the vendor's own documentation and terms rather than assuming, and match it against the promises you have made to your own users.
- Pricing model. Per request, per character, per seat or a flat license? Character-based pricing makes long messages more expensive than short ones, which matters for a product where some users paste essays and others type three words.
The last two points are the ones teams skip and then revisit. Read the pricing page and the terms of service for any tool you are considering, and read them again before you scale.
Working Code: A Blocklist Profanity Filter in Python
Here is a small, honest blocklist filter. It is deliberately simple so you can see exactly where it succeeds and where it fails. It is not a call to any vendor's API.
A minimal implementation
import re
import unicodedata
# Illustrative list. A real deployment needs a much longer list,
# per-language lists, and an owner for updates.
BANNED = {"ass", "damn", "hell"}
LEET = str.maketrans({
"0": "o", "1": "i", "3": "e", "4": "a", "5": "s",
"@": "a", "$": "s", "!": "i",
})
def normalize(text: str) -> str:
text = unicodedata.normalize("NFKC", text).lower()
text = text.translate(LEET)
text = re.sub(r"[^a-z0-9\s]", "", text) # strip punctuation
text = re.sub(r"\s+", " ", text).strip()
return text
def contains_profanity(text: str) -> bool:
normalized = normalize(text)
return any(word in normalized for word in BANNED)Run it against a handful of strings:
samples = [
"Great class today, everyone.", # innocent
"The bass section sounded fantastic.", # innocent
"She plays the assassin in act two.", # innocent
'He said "damn" in the interview.', # quoted speech
"That was a d4mn shame.", # character substitution
"d a m n", # spaced out
"hello everyone", # innocent
]
for s in samples:
print(contains_profanity(s), s)The results tell the whole story. Most of the innocent lines come back True, because the list is matched as a substring: ass lives inside class, bass and assassin, and hell lives inside hello. The quoted line is flagged too, even though the text is reporting someone else's words. The substituted line is caught, because normalization was written to catch it. The spaced-out line is missed, because the spaces break the sequence before matching runs.
Where this breaks in production
- False positives are visible and embarrassing. A user discussing music theory, sports or local geography gets blocked, and you have handed them a reason to complain publicly.
- False negatives are endless. Spaces, repeated letters, homoglyphs borrowed from other scripts, and words split across punctuation all evade a fixed list.
- Word-boundary matching fixes one side and breaks the other. Switching from substring matching to token matching removes the class and hello errors, but then a substitution only works if normalization produces the exact token, and spacing evasion walks straight through.
- A boolean tells you whether, not where.
contains_profanityreturnsTrue; it does not tell you which word, so masking one word needs separate logic that reproduces the match position — harder once normalization has changed the string's length. - The list never stops growing. Someone has to review reports and ship updates, release after release.
What a caller can do with the boolean is already useful, though: reject the message, hold it for review, or replace the offending text with a placeholder. The decision itself is a branch in your code, which is exactly what you want in a write path.
How CautionLabs Does the Same Job
CautionLabs is an AI text moderation service with two deployment options. Only this section and the closing note describe it; everything above applies whichever tool you choose.
The profanity flag
The cloud API is a single call: POST /moderation at https://api.cautionlabs.com with a JSON body of {"text": "..."}, authenticated with a cloud API key sent as a bearer token. A private on-premises key does not work with the cloud API, so make sure the key you send belongs to the hosted service.
The response contains a categories object with twelve boolean flags — profanity among them — plus an overall flagged value that is true when any category is flagged. There are no scores, probabilities or confidence values, and no thresholds to tune. Your application makes a branch, not a policy decision about where to draw a line.
Text is accepted up to 10,000 characters, and each started 3,000-character piece counts as one request. There is no batch endpoint and no webhooks, so the check runs inline in your write path or in a queue worker you own.
Python example
import requests
CLOUD_API_KEY = "your_cloud_api_key_here"
def moderate(text: str) -> dict:
response = requests.post(
"https://api.cautionlabs.com/moderation",
headers={
"Authorization": f"Bearer {CLOUD_API_KEY}",
"Content-Type": "application/json",
},
json={"text": text},
timeout=10,
)
response.raise_for_status()
return response.json()
result = moderate("You are an idiot and I hate you")
print(result["categories"]["profanity"]) # True or False
print(result["categories"]["harassment"]) # True or False
print(result["flagged"]) # True when any category is flaggedA chat message handler example
def handle_message(text: str) -> str:
result = moderate(text)
categories = result["categories"]
if categories["profanity"]:
return "reject"
if result["flagged"]:
return "review"
return "allow"
action = handle_message(user_text)
# "allow" -> persist and publish
# "review" -> write to your moderation queue, hold publication
# "reject" -> return an error to the client, do not storeThe same shape works for a comment form or a product review: call moderate, read the flag that matters for that surface, then map it to an action. If you want the full request and response walkthrough, the content moderation API Python tutorial covers it end to end, and the Node.js tutorial covers the same ground for a JavaScript backend.
Running the model on your own infrastructure
If user text cannot leave your environment, the second option is the Argus 1 model (model id argus_1), which runs on your own infrastructure and exposes a local POST /moderate endpoint. The container makes no outbound requests and has no telemetry. You can deploy the model on-premises with Docker — that guide covers the registry login, the image and the endpoint details. One thing to keep straight: the on-premises container serves the local endpoint, not the cloud one.
What to Do When a Message Is Flagged
A flag is not a policy. The flag is an input to the policy you have already written down, and the policy should say what happens next. The common options:
- Hard reject. Return an error to the client and do not store the text. Good for display names, game lobbies and any surface where the text has no value to anyone if it is abusive.
- Hold for human review. Store it, do not publish it, and put it in a queue. Good for comments on a news site, marketplace listings and support inboxes, where context decides.
- Downrank or hide. Publish but collapse behind a "show anyway" control, or de-emphasize in a feed.
- Warn the user. Allow the message but nudge the author, which is often enough for a first offense in chat.
- Log and allow. For a low-risk surface, keep the record and let the message through.
Match the action to the category and the surface. A profanity hit in a game lobby and a harassment hit in a support inbox are different calls, even if the same API returns both.
Because a boolean API returns no location in the text, masking one word requires your own logic. In practice most teams either reject the whole message or queue it, and leave word-level rewriting alone.
Keep an audit record: the text, the flags, the action taken, a timestamp and the user id. Give users a way to appeal, because every filter has false positives and the appeal is how you find them.
There is one more decision hiding in here, and it is a latency decision. Does the check block the post before it is stored, or does it run just after? Blocking means nothing profane is ever stored or broadcast, at the cost of adding the check's latency to the user's send action — and you must decide whether a failed check fails open or closed. Running after means the user sees an instant send, but you need an edit or delete path, and there is a brief window where the text is visible to others.
Testing a Profanity Filter Before You Ship
Build a test set from your own product's messages rather than from a generic list:
- Benign text that looks risky. Place names, quoted speech, song lyrics discussed in a review, medical and support conversations, non-English words that share letters with English profanity, and usernames that happen to contain banned sequences.
- Obvious evasions. Substitutions, spacing, repeated characters, mixed case and punctuation inserted mid-word.
- Borderline cases where your team disagrees. These are the ones that define your policy, so write down the expected outcome.
Test the whole path, not just the check: the filter, the policy branch and the exact message the user sees. Label each case with the expected action, not with a yes/no flag, because the action is what your users experience.
One practical note: a boolean API has no thresholds, so there is nothing to tune. A test set measures the tool, not your configuration. Re-run the set whenever you change your policy, add a new surface, or change provider, and keep a portion of the cases out of your day-to-day tuning so you still have an honest measure.
Common Questions About Profanity Filtering
Should the check block the post or run after it? For chat and comments, most teams run the check inline before storing, because a published-then-deleted message has already been read. For high-volume feeds or batch imports, a queue worker that checks after the write and updates the record is often the better trade, as long as the content is not visible until the check completes.
How do I mask a single word when the filter returns only a boolean? You cannot, from the boolean alone. A decision-level API tells you that the text is problematic, not which characters caused it. If masking matters to your product, keep a local word-level check alongside the API call for the reminder step, or replace the whole message with a placeholder.
What changes at high chat volume? Three things. First, cost scales with message count and length, so understand the billing unit before you commit — cost per 1,000 requests is usually per started chunk of characters rather than per message, which matters if users paste long text. Second, throughput planning matters: without a batch endpoint, you either call inline or run your own worker pool, and you should know which before launch day. Third, your review queue becomes the bottleneck, so sample flagged messages instead of reviewing every one, and track which categories dominate so your policy follows the data.
How do I handle a provider outage? Decide now whether your write path fails open, fails closed or retries through a queue, and make sure the answer is written down rather than discovered at 3am.
Try the profanity flag on your own text in the CautionLabs playground, then get a cloud API key and drop the check into your message write path, or run the Argus 1 model on your own servers if user text cannot leave your infrastructure.