Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Moderation API Python SDK

PyPI

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.

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

Note

Python version upgrade policy

Once a Python version reaches its official end of life date, a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.

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
  • create - Create a project API key
  • retrieve - Get the webhook signing secret
  • add - Add words to wordlist
  • remove - Remove words from wordlist

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 code 401.
    • RateLimitError: Too many requests. Retry after the number of seconds in the Retry-After header. Status code 429.
    • BadRequestError: The request is malformed or a parameter is invalid. Status code 400. *
Less common errors (9)

Network errors:

Inherit from ModerationAPIError:

  • NotFoundError: The resource does not exist or the key cannot see it. Status code 404. Applicable to 39 of 53 methods.*
  • PermissionDeniedError: The API key cannot do this, or the plan limit for this resource is reached. Status code 403. Applicable to 36 of 53 methods.*
  • InternalServerError: Something went wrong on our side. Retry with backoff. Status code 500. Applicable to 23 of 53 methods.*
  • ConflictError: The request conflicts with the current state of a resource. Status code 409. 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 the cause attribute.

* 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

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages