Search by

Package info

github.com/moderation-api/sdk-php

pkg:composer/moderation-api/sdk-php

Statistics

Installs: 44

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 1

v1.1.1 2026-10-22 13:36 UTC

README

Moderation API PHP SDK

Packagist

The official PHP library for Moderation API. Use it to moderate text, images, video and audio, manage authors, review queues, actions and wordlists, and verify webhooks.

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 relies on Composer to manage its dependencies.

To install the SDK and add it as a dependency to an existing composer.json file:

composer require "moderation-api/sdk-php"

SDK Example Usage

Example

declare(strict_types=1);

require 'vendor/autoload.php';

use ModerationApi;
use ModerationApi\Models\Operations;

$sdk = ModerationApi\ModerationApi::builder()
    ->setSecurity(
        '<YOUR_BEARER_TOKEN_HERE>'
    )
    ->build();

$body = new Operations\SubmitContentRequestBody(
    content: new Operations\TextRequest(
        text: 'Hey, check out my profile for a deal!',
    ),
    contentId: 'message-48213',
    authorId: 'user-1092',
    conversationId: 'room-general',
    metadata: [
        'platform' => 'ios',
    ],
);

$response = $sdk->content->submit(
    body: $body
);

if ($response->object !== null) {
    // handle response
}

Moderating content

Use content->submit to moderate text, images, video, audio, or objects with several fields. All parameters except content are optional.

Pass your API key to setSecurity. The examples read it from the MODAPI_SECRET_KEY environment variable.

declare(strict_types=1);

require 'vendor/autoload.php';

use ModerationApi\ModerationApi;
use ModerationApi\Models\Operations;

$sdk = ModerationApi::builder()
    ->setSecurity(getenv('MODAPI_SECRET_KEY'))
    ->build();

// Text
$sdk->content->submit(new Operations\SubmitContentRequestBody(
    content: new Operations\TextRequest(text: 'Your text here'),
    contentId: 'message-123', // your ID for the content
    authorId: 'user-123', // your ID for the user who wrote it
    conversationId: 'room-123', // groups related content
    metadata: ['platform' => 'ios'],
));

// Image, video and audio: send a URL
$sdk->content->submit(new Operations\SubmitContentRequestBody(
    content: new Operations\ImageRequest(url: 'https://example.com/image.jpg'),
));
$sdk->content->submit(new Operations\SubmitContentRequestBody(
    content: new Operations\VideoRequest(url: 'https://example.com/video.mp4'),
));
$sdk->content->submit(new Operations\SubmitContentRequestBody(
    content: new Operations\AudioRequest(url: 'https://example.com/audio.mp3'),
));

// An object with several fields, moderated together
$sdk->content->submit(new Operations\SubmitContentRequestBody(
    content: new Operations\ObjectT(data: [
        'title' => new Operations\DataText(text: 'Post title'),
        'body' => new Operations\DataText(text: 'Post content'),
        'thumbnail' => new Operations\DataImage(url: 'https://example.com/thumb.jpg'),
    ]),
));

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.

$response = $sdk->content->submit(new Operations\SubmitContentRequestBody(
    content: new Operations\TextRequest(text: 'Some content'),
));
$result = $response->object;

if ($result->evaluation->flagged) {
    echo "A policy flagged the content\n";
}

switch ($result->recommendation->action) {
    case Operations\SubmitContentRecommendationAction::Reject:
        // Block the content
        break;
    case Operations\SubmitContentRecommendationAction::Review:
        // Publish or hold it, and send it to a review queue
        break;
    case Operations\SubmitContentRecommendationAction::Allow:
        // Publish the content
        break;
}

foreach ($result->policies as $policy) {
    echo "{$policy->id}: flagged=" . var_export($policy->flagged, true) . "\n";
}

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 $sdk->webhookSecret->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

WebhookSignature::constructEvent checks the signature against the raw body and returns the event as an array. It reads the secret from MODAPI_WEBHOOK_SECRET; to set it in code, pass it as the third argument. It throws WebhookSignatureException if the signature does not match.

use ModerationApi\WebhookSignature;
use ModerationApi\WebhookSignatureException;

$payload = file_get_contents('php://input'); // the raw body, not parsed JSON
$signature = $_SERVER['HTTP_MODAPI_SIGNATURE'] ?? null;

try {
    $event = WebhookSignature::constructEvent($payload, $signature);
} catch (WebhookSignatureException $e) {
    http_response_code(400);
    exit;
}

error_log($event['type']);
http_response_code(200);

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
secretKey http HTTP Bearer

To authenticate with the API the secretKey parameter must be set when initializing the SDK. For example:

declare(strict_types=1);

require 'vendor/autoload.php';

use ModerationApi;
use ModerationApi\Models\Operations;

$sdk = ModerationApi\ModerationApi::builder()
    ->setSecurity(
        '<YOUR_BEARER_TOKEN_HERE>'
    )
    ->build();

$request = new Operations\ListAuthorsRequest();

$responses = $sdk->authors->list(
    request: $request
);


foreach ($responses as $response) {
    if ($response->statusCode === 200) {
        // handle response
    }
}

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. The management API is available on Enterprise plans.

Each key works only with its own endpoints. With the wrong key the API returns 403 with the code project_key_required or organization_key_required. If you use both, create one client for each key:

use ModerationApi\ModerationApi;

// Project key
$sdk = ModerationApi::builder()
    ->setSecurity(getenv('MODAPI_SECRET_KEY'))
    ->build();

// Organization key
$management = ModerationApi::builder()
    ->setSecurity(getenv('MODAPI_ORGANIZATION_KEY'))
    ->build();

foreach ($management->projects->list() as $response) {
    foreach ($response->object->data as $project) {
        echo $project->id, ' ', $project->name, "\n";
    }
}

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

Actions

Authors

Channels

Content

Projects

Queue

Queue.Items

Webhooks

WebhookSecret

  • retrieve - Get the webhook signing secret

Wordlist

Wordlist.Words

  • 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 object will be a Generator instead of an individual response.

Working with generators is as simple as iterating over the responses in a foreach loop, and you can see an example below:

declare(strict_types=1);

require 'vendor/autoload.php';

use ModerationApi;
use ModerationApi\Models\Operations;

$sdk = ModerationApi\ModerationApi::builder()
    ->setSecurity(
        '<YOUR_BEARER_TOKEN_HERE>'
    )
    ->build();

$request = new Operations\ListAuthorsRequest();

$responses = $sdk->authors->list(
    request: $request
);


foreach ($responses as $response) {
    if ($response->statusCode === 200) {
        // handle response
    }
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or throw an exception.

By default an API error will raise a Errors\APIException exception, which has the following properties:

Property Type Description
$message string The error message
$statusCode int The HTTP status code
$rawResponse ?\Psr\Http\Message\ResponseInterface The raw HTTP response
$body string The response content

When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the list method throws the following exceptions:

Error Type Status Code Content Type
Errors\BadRequestError 400 application/json
Errors\AuthenticationError 401 application/json
Errors\PermissionDeniedError 403 application/json
Errors\NotFoundError 404 application/json
Errors\RateLimitError 429 application/json
Errors\InternalServerError 500 application/json
Errors\APIException 4XX, 5XX */*

Example

declare(strict_types=1);

require 'vendor/autoload.php';

use ModerationApi;
use ModerationApi\Models\Errors;
use ModerationApi\Models\Operations;

$sdk = ModerationApi\ModerationApi::builder()
    ->setSecurity(
        '<YOUR_BEARER_TOKEN_HERE>'
    )
    ->build();

try {
    $request = new Operations\ListAuthorsRequest();

    $responses = $sdk->authors->list(
        request: $request
    );

    foreach ($responses as $response) {
        if ($response->statusCode === 200) {
            // handle response
        }
    }
} catch (Errors\BadRequestErrorThrowable $e) {
    // handle $e->$container data
    throw $e;
} catch (Errors\AuthenticationErrorThrowable $e) {
    // handle $e->$container data
    throw $e;
} catch (Errors\PermissionDeniedErrorThrowable $e) {
    // handle $e->$container data
    throw $e;
} catch (Errors\NotFoundErrorThrowable $e) {
    // handle $e->$container data
    throw $e;
} catch (Errors\RateLimitErrorThrowable $e) {
    // handle $e->$container data
    throw $e;
} catch (Errors\InternalServerErrorThrowable $e) {
    // handle $e->$container data
    throw $e;
} catch (Errors\APIException $e) {
    // handle default exception
    throw $e;
}

Server Selection

Override Server URL Per-Client

The default server can be overridden globally using the setServerUrl(string $serverUrl) builder method when initializing the SDK client instance. For example:

declare(strict_types=1);

require 'vendor/autoload.php';

use ModerationApi;
use ModerationApi\Models\Operations;

$sdk = ModerationApi\ModerationApi::builder()
    ->setServerURL('https://api.moderationapi.com/v1')
    ->setSecurity(
        '<YOUR_BEARER_TOKEN_HERE>'
    )
    ->build();

$request = new Operations\ListAuthorsRequest();

$responses = $sdk->authors->list(
    request: $request
);


foreach ($responses as $response) {
    if ($response->statusCode === 200) {
        // handle response
    }
}

Timeouts

The SDK sends requests with Guzzle. To set a timeout, give the builder your own client:

$sdk = ModerationApi::builder()
    ->setSecurity(getenv('MODAPI_SECRET_KEY'))
    ->setClient(new \GuzzleHttp\Client(['timeout' => 10]))
    ->build();

Requirements

PHP 8.2 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