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.
- Get an API key in the dashboard.
- Read the documentation and the API reference.
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
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"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
}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'),
]),
));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";
}Moderation API signs every webhook delivery with your project's webhook signing secret. The signature is in the modapi-signature header.
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.
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);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();
$response = $sdk->analytics->summary(
range: Operations\GetAnalyticsSummaryQueryParamRange::Thirtyd
);
if ($response->object !== null) {
// handle response
}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:
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 methods
- retrieve - Get account details
- list - List moderation actions
- create - Create an action
- retrieve - Get an action
- update - Update an action
- delete - Delete an action
- execute - Execute moderation action
- 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
- list - List authors
- create - Create a new author
- retrieve - Get author details
- update - Update author details
- delete - Delete an author
- list - List channels
- create - Create a channel
- retrieve - Get a channel
- update - Update a channel
- delete - Delete a channel
- duplicate - Duplicate a channel
- submit - Submit content
- create - Send feedback
- list - List projects
- create - Create a project
- retrieve - Get a project
- update - Update a project
- delete - Delete a project
- duplicate - Duplicate a project
- create - Create a project API key
- list - List queue items
- resolve - Resolve a queue item
- resolveMany - Resolve queue items
- unresolve - Unresolve a queue item
- list - List webhooks
- create - Create a webhook
- retrieve - Get a webhook
- update - Update a webhook
- delete - Delete a webhook
- retrieve - Get the webhook signing secret
- list - List wordlists
- create - Create wordlist
- retrieve - Get wordlist
- update - Update wordlist
- getEmbeddingStatus - Get embedding status
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
}
}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 summary 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 | */* |
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 {
$response = $sdk->analytics->summary(
range: Operations\GetAnalyticsSummaryQueryParamRange::Thirtyd
);
if ($response->object !== null) {
// 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;
}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();
$response = $sdk->analytics->summary(
range: Operations\GetAnalyticsSummaryQueryParamRange::Thirtyd
);
if ($response->object !== null) {
// handle response
}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();PHP 8.2 or later.
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.
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.
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.