Moderation API Python SDK
The official Python library for Moderation API. Use it to moderate text, images, video and audio, manage authors, review queues, actions and wordlists, and verify webhooks. It supports both synchronous and asyncio code.
- Get an API key in the dashboard.
- Read the documentation and the API reference.
Summary
Moderation API: Moderate text, images, video and audio in real time, manage authors, review queues and actions, and receive webhooks.
More information about the API can be found at https://docs.moderationapi.com
Table of Contents
SDK Installation
The SDK can be installed with uv, pip, or poetry package managers.
uv
uv is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities.
uv add moderation_api
PIP
PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install moderation_api
Poetry
Poetry is a modern tool that simplifies dependency management and package publishing by using a single pyproject.toml file to handle project metadata and dependencies.
poetry add moderation_api
Shell and script usage with uv
You can use this SDK in a Python shell with uv and the uvx command that comes with it like so:
uvx --from moderation_api python
It's also possible to write a standalone Python script without needing to set up a whole project like so:
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "moderation_api",
# ]
# ///
from moderation_api import ModerationAPI
sdk = ModerationAPI(
# SDK arguments
)
# Rest of script here...
Once that is saved to a file, you can run it with uv run script.py where
script.py can be replaced with the actual file name.
IDE Support
PyCharm
Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.
SDK Example Usage
Example
# Synchronous Example
from moderation_api import ModerationAPI
import os
with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = ma_client.content.submit(content={
"type": "text",
"text": "Hey, check out my profile for a deal!",
}, content_id="message-48213", author_id="user-1092", conversation_id="room-general", metadata={
"platform": "ios",
})
# Handle response
print(res)
The same SDK client can also be used to make asynchronous requests by importing asyncio.
# Asynchronous Example
import asyncio
from moderation_api import ModerationAPI
import os
async def main():
async with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = await ma_client.content.submit_async(content={
"type": "text",
"text": "Hey, check out my profile for a deal!",
}, content_id="message-48213", author_id="user-1092", conversation_id="room-general", metadata={
"platform": "ios",
})
# Handle response
print(res)
asyncio.run(main())
Moderating content
Use content.submit to moderate text, images, video, audio, or objects with several fields. All parameters except content are optional.
The client reads your API key from the MODAPI_SECRET_KEY environment variable. To set it in code, pass secret_key.
from moderation_api import ModerationAPI
with ModerationAPI() as client: # reads MODAPI_SECRET_KEY
# Text
client.content.submit(
content={"type": "text", "text": "Your text here"},
content_id="message-123", # your ID for the content
author_id="user-123", # your ID for the user who wrote it
conversation_id="room-123", # groups related content
metadata={"platform": "ios"},
)
# Image, video and audio: send a URL
client.content.submit(content={"type": "image", "url": "https://example.com/image.jpg"})
client.content.submit(content={"type": "video", "url": "https://example.com/video.mp4"})
client.content.submit(content={"type": "audio", "url": "https://example.com/audio.mp3"})
# An object with several fields, moderated together
client.content.submit(
content={
"type": "object",
"data": {
"title": {"type": "text", "text": "Post title"},
"body": {"type": "text", "text": "Post content"},
"thumbnail": {"type": "image", "url": "https://example.com/thumb.jpg"},
},
},
)
Every method has an async version with the suffix _async, for example await client.content.submit_async(...).
Using the result
evaluation.flagged tells you if any policy flagged the content. recommendation.action is the action the API recommends after it applies your thresholds and rules: allow, review or reject.
from moderation_api import ModerationAPI
with ModerationAPI() as client:
result = client.content.submit(content={"type": "text", "text": "Some content"})
if result.evaluation.flagged:
print("A policy flagged the content")
if result.recommendation.action == "reject":
pass # Block the content
elif result.recommendation.action == "review":
pass # Publish or hold it, and send it to a review queue
else:
pass # Publish the content
for policy in result.policies:
print(f"{policy.id}: flagged={policy.flagged}")
Verifying webhooks
Moderation API signs every webhook delivery with your project's webhook signing secret. The signature is in the modapi-signature header.
Webhook signing secret
Find the secret on the API keys page in the dashboard, or get it with client.webhook_secret.retrieve(). Store it in the MODAPI_WEBHOOK_SECRET environment variable. It is not your API key. Get it once, for example in a setup script, and do not call retrieve for each delivery, so verification does not depend on a call to the API. Keep it as secret as your API key: anyone with it can sign webhooks.
Verify a delivery
construct_event checks the signature against the raw body and returns the event as a dictionary. It reads the secret from MODAPI_WEBHOOK_SECRET; to set it in code, pass secret. It raises WebhookSignatureError if the signature does not match.
from flask import Flask, request
from moderation_api.webhook_signature import WebhookSignatureError, construct_event
app = Flask(__name__)
@app.post("/webhooks/moderation")
def moderation_webhook():
try:
event = construct_event(
request.get_data(), # the raw body, not parsed JSON
request.headers.get("modapi-signature", ""),
)
except WebhookSignatureError:
return "Invalid signature", 400
print(event["type"])
return "", 200
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
secret_key |
http | HTTP Bearer | MODAPI_SECRET_KEY |
To authenticate with the API the secret_key parameter must be set when initializing the SDK client instance. For example:
from moderation_api import ModerationAPI
import os
with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = ma_client.analytics.summary(range="30d")
# Handle response
print(res)
Project and organization keys
Moderation API has two kinds of API keys:
- A project key works with one project: content, authors, review queues, actions, wordlists, webhooks and the account. Most integrations need only this key.
- An organization key works with the management API: projects and channels. It can also use any project's endpoints: name the project with
projectId.
A project key can't call the management API: the API returns 403 with the code organization_key_required. If you use both kinds of key, create one client for each:
import os
from moderation_api import ModerationAPI
# Project key, from MODAPI_SECRET_KEY
client = ModerationAPI()
# Organization key
management = ModerationAPI(secret_key=os.environ["MODAPI_ORGANIZATION_KEY"])
res = management.projects.list()
while res is not None:
for project in res.result.data:
print(project.id, project.name)
res = res.next()
Create the organization client only where you manage projects and channels, for example in a setup script, and keep the organization key out of the code that moderates content.
Available Resources and Operations
Available methods
Account
- retrieve - Get account details
Actions
- list - List moderation actions
- create - Create an action
- retrieve - Get an action
- update - Update an action
- delete - Delete an action
- execute - Execute moderation action
Analytics
- summary - Get the analytics summary
- policies - Get the most flagged policies
- authors - Get the most flagged authors
- channels - Get analytics per channel
- volumes - Get volumes over time
- automation - Get the automation breakdown
Authors
- list - List authors
- create - Create a new author
- retrieve - Get author details
- update - Update author details
- delete - Delete an author
Channels
- list - List channels
- create - Create a channel
- retrieve - Get a channel
- update - Update a channel
- delete - Delete a channel
- duplicate - Duplicate a channel
Content
- submit - Submit content
Feedback
- create - Send feedback
Projects
- list - List projects
- create - Create a project
- retrieve - Get a project
- update - Update a project
- delete - Delete a project
- duplicate - Duplicate a project
Projects.ApiKeys
- create - Create a project API key
Queue
Queue.Items
- list - List queue items
- resolve - Resolve a queue item
- resolve_many - Resolve queue items
- unresolve - Unresolve a queue item
Webhooks
- list - List webhooks
- create - Create a webhook
- retrieve - Get a webhook
- update - Update a webhook
- delete - Delete a webhook
WebhookSecret
- retrieve - Get the webhook signing secret
Wordlist
- list - List wordlists
- create - Create wordlist
- retrieve - Get wordlist
- update - Update wordlist
- get_embedding_status - Get embedding status
Wordlist.Words
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the
returned response object will have a Next method that can be called to pull down the next group of results. If the
return value of Next is None, then there are no more pages to be fetched.
Here's an example of one such pagination call:
from moderation_api import ModerationAPI
import os
with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = ma_client.authors.list(request={})
while res is not None:
# Handle items
res = res.next()
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:
from moderation_api import ModerationAPI
from moderation_api.utils import BackoffStrategy, RetryConfig
import os
with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = ma_client.analytics.summary(range="30d",
RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))
# Handle response
print(res)
If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:
from moderation_api import ModerationAPI
from moderation_api.utils import BackoffStrategy, RetryConfig
import os
with ModerationAPI(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = ma_client.analytics.summary(range="30d")
# Handle response
print(res)
Error Handling
ModerationAPIError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
err.message |
str |
Error message |
err.status_code |
int |
HTTP response status code eg 404 |
err.headers |
httpx.Headers |
HTTP response headers |
err.body |
str |
HTTP body. Can be empty string if no body is returned. |
err.raw_response |
httpx.Response |
Raw HTTP response |
err.data |
Optional. Some errors may contain structured data. See Error Classes. |
Example
from moderation_api import ModerationAPI, errors
import os
from typing import Literal
with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = None
try:
res = ma_client.analytics.summary(range="30d")
# Handle response
print(res)
except errors.ModerationAPIError as e:
# The base class for HTTP error responses
print(e.message)
print(e.status_code)
print(e.body)
print(e.headers)
print(e.raw_response)
# Depending on the method different errors may be thrown
if isinstance(e, errors.BadRequestError):
print(e.data.type) # Literal["invalid_request_error"]
print(e.data.code) # models.BadRequestErrorCode
print(e.data.message) # str
print(e.data.issues) # Optional[List[models.ErrorIssue]]
print(e.data.request_id) # str
Error Classes
Primary errors:
ModerationAPIError: The base class for HTTP error responses.AuthenticationError: The API key is missing, invalid or revoked. Status code401.RateLimitError: Too many requests. Retry after the number of seconds in theRetry-Afterheader. Status code429.BadRequestError: The request is malformed or a parameter is invalid. Status code400. *
Less common errors (9)
Network errors:
httpx.RequestError: Base class for request errors.httpx.ConnectError: HTTP client was unable to make a request to a server.httpx.TimeoutException: HTTP request timed out.
Inherit from ModerationAPIError:
NotFoundError: The resource does not exist or the key cannot see it. Status code404. Applicable to 39 of 53 methods.*PermissionDeniedError: The API key cannot do this, or the plan limit for this resource is reached. Status code403. Applicable to 36 of 53 methods.*InternalServerError: Something went wrong on our side. Retry with backoff. Status code500. Applicable to 23 of 53 methods.*ConflictError: The request conflicts with the current state of a resource. Status code409. Applicable to 2 of 53 methods.*ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via thecauseattribute.
* Check the method documentation to see if the error is applicable.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:
from moderation_api import ModerationAPI
import os
with ModerationAPI(
server_url="https://api.moderationapi.com/v1",
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
res = ma_client.analytics.summary(range="30d")
# Handle response
print(res)
Custom HTTP Client
The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance.
Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls.
This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.
For example, you could specify a header for every request that this sdk makes as follows:
from moderation_api import ModerationAPI
import httpx
http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = ModerationAPI(client=http_client)
or you could wrap the client with your own custom logic:
from moderation_api import ModerationAPI
from moderation_api.httpclient import AsyncHttpClient
import httpx
class CustomClient(AsyncHttpClient):
client: AsyncHttpClient
def __init__(self, client: AsyncHttpClient):
self.client = client
async def send(
self,
request: httpx.Request,
*,
stream: bool = False,
auth: Union[
httpx._types.AuthTypes, httpx._client.UseClientDefault, None
] = httpx.USE_CLIENT_DEFAULT,
follow_redirects: Union[
bool, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
) -> httpx.Response:
request.headers["Client-Level-Header"] = "added by client"
return await self.client.send(
request, stream=stream, auth=auth, follow_redirects=follow_redirects
)
def build_request(
self,
method: str,
url: httpx._types.URLTypes,
*,
content: Optional[httpx._types.RequestContent] = None,
data: Optional[httpx._types.RequestData] = None,
files: Optional[httpx._types.RequestFiles] = None,
json: Optional[Any] = None,
params: Optional[httpx._types.QueryParamTypes] = None,
headers: Optional[httpx._types.HeaderTypes] = None,
cookies: Optional[httpx._types.CookieTypes] = None,
timeout: Union[
httpx._types.TimeoutTypes, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
extensions: Optional[httpx._types.RequestExtensions] = None,
) -> httpx.Request:
return self.client.build_request(
method,
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
s = ModerationAPI(async_client=CustomClient(httpx.AsyncClient()))
httpx2 (Pydantic's httpx fork)
httpx2 is Pydantic's maintained fork of httpx. To run this SDK on httpx2, call alias_httpx() at your program's entry point, before importing the SDK, so every import httpx — including the ones inside the SDK — resolves to httpx2:
import httpx2
httpx2.alias_httpx()
from moderation_api import ModerationAPI
s = ModerationAPI()
An SDK can also be generated against httpx2 directly, so it depends on the fork instead of httpx, by setting python.httpClientLibrary: httpx2 in gen.yaml.
Resource Management
The ModerationAPI class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.
from moderation_api import ModerationAPI
import os
def main():
with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
# Rest of application here...
# Or when using async:
async def amain():
async with ModerationAPI(
secret_key=os.getenv("MODAPI_SECRET_KEY", ""),
) as ma_client:
# Rest of application here...
Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass your own logger class directly into your SDK.
from moderation_api import ModerationAPI
import logging
logging.basicConfig(level=logging.DEBUG)
s = ModerationAPI(debug_logger=logging.getLogger("moderation_api"))
You can also enable a default debug logger by setting an environment variable MODAPI_DEBUG to true.
Timeouts
Set a timeout in milliseconds for all requests on the client, or for one request:
from moderation_api import ModerationAPI
with ModerationAPI(timeout_ms=10_000) as client:
client.content.submit(content={"type": "text", "text": "Hello"}, timeout_ms=5_000)
Requirements
Python 3.10 or later.
Support
Found a bug? Open an issue in this repository. This package is generated from the Moderation API OpenAPI spec, so pull requests to the generated code can't be merged as they are, but we use them to fix the generator.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
SDK Created by Speakeasy
Metadata
Release files for moderation_api 2.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| moderation_api-2.2.0.tar.gz | 152.6 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| moderation_api-2.2.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 371.0 kB
Release files / moderation_api-2.2.0.tar.gz
| Download URL | moderation_api-2.2.0.tar.gz |
|---|---|
| Size | 152.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0d0df306508adfd9b2429506c775eae3c279365237f62d3d5de10fb010200f48
|
|
BLAKE2b-256 checksum How to use checksums |
5c3f42d49b9b292c48f8a5fba6425ed68f894f2b0a754e09d673fd3c5e6cc25d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / moderation_api-2.2.0-py3-none-any.whl
| Download URL | moderation_api-2.2.0-py3-none-any.whl |
|---|---|
| Size | 218.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
caa35c992476cb23dd7d4a2bb60e99c05332a6b5fccbc2a6b730c7ceb63440f6
|
|
BLAKE2b-256 checksum How to use checksums |
044257900b51650c69e0d24cfeeddb607b44c24590c31f5abec16bc67ac571bb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for moderation_api 2.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.