The official Ruby library for Moderation API. Use it to moderate text, images, video and audio, manage authors, review queues, actions and wordlists, and verify webhooks. It includes Sorbet type signatures.
- 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 can be installed using RubyGems:
gem install moderation_apirequire "moderation_api"
Models = ::ModerationApi::Models
s = ::ModerationApi::ModerationApi.new(
secret_key: "<YOUR_BEARER_TOKEN_HERE>"
)
res = s.content.submit(
body: Models::Operations::SubmitContentRequestBody.new(
content: Models::Operations::TextRequest.new(
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"
}
)
)
unless res.object.nil?
# handle response
endUse content.submit to moderate text, images, video, audio, or objects with several fields. All parameters except content are optional.
Pass your API key as secret_key. The examples read it from the MODAPI_SECRET_KEY environment variable.
require "moderation_api"
Operations = ModerationApi::Models::Operations
client = ModerationApi::ModerationApi.new(secret_key: ENV.fetch("MODAPI_SECRET_KEY"))
# Text
client.content.submit(body: Operations::SubmitContentRequestBody.new(
content: Operations::TextRequest.new(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(body: Operations::SubmitContentRequestBody.new(
content: Operations::ImageRequest.new(url: "https://example.com/image.jpg")
))
client.content.submit(body: Operations::SubmitContentRequestBody.new(
content: Operations::VideoRequest.new(url: "https://example.com/video.mp4")
))
client.content.submit(body: Operations::SubmitContentRequestBody.new(
content: Operations::AudioRequest.new(url: "https://example.com/audio.mp3")
))
# An object with several fields, moderated together
client.content.submit(body: Operations::SubmitContentRequestBody.new(
content: Operations::Object.new(data: {
title: Operations::DataText.new(text: "Post title"),
body: Operations::DataText.new(text: "Post content"),
thumbnail: Operations::DataImage.new(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 = client.content.submit(body: Operations::SubmitContentRequestBody.new(
content: Operations::TextRequest.new(text: "Some content")
))
result = response.object
puts "A policy flagged the content" if result.evaluation.flagged
case result.recommendation.action.serialize
when "reject"
# Block the content
when "review"
# Publish or hold it, and send it to a review queue
when "allow"
# Publish the content
end
result.policies.each do |policy|
puts "#{policy.id}: flagged=#{policy.flagged}"
endModeration 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 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.
ModerationApi::WebhookSignature.construct_event checks the signature against the raw body and returns the event as a Hash. It reads the secret from MODAPI_WEBHOOK_SECRET; to set it in code, pass it as the third argument. It raises ModerationApi::WebhookSignature::VerificationError if the signature does not match.
require "moderation_api/webhook_signature"
# For example, in a Rails controller
def moderation_webhook
event = ModerationApi::WebhookSignature.construct_event(
request.raw_post, # the raw body, not parsed JSON
request.headers["modapi-signature"]
)
Rails.logger.info(event["type"])
head :ok
rescue ModerationApi::WebhookSignature::VerificationError
head :bad_request
endThis SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
secret_key |
http | HTTP Bearer |
To authenticate with the API the secret_key parameter must be set when initializing the SDK client instance. For example:
require "moderation_api"
Models = ::ModerationApi::Models
s = ::ModerationApi::ModerationApi.new(
secret_key: "<YOUR_BEARER_TOKEN_HERE>"
)
res = s.analytics.summary(range: Models::Operations::GetAnalyticsSummaryQueryParamRange::THIRTYD)
unless res.object.nil?
# handle response
endModeration 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:
require "moderation_api"
# Project key
client = ModerationApi::ModerationApi.new(secret_key: ENV.fetch("MODAPI_SECRET_KEY"))
# Organization key
management = ModerationApi::ModerationApi.new(secret_key: ENV.fetch("MODAPI_ORGANIZATION_KEY"))
management.projects.list.each do |page|
page.object.data.each { |project| puts "#{project.id} #{project.name}" }
endCreate 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
- resolve_many - 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
- get_embedding_status - Get embedding status
Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an error.
By default an API error will raise a Errors::APIError, which has the following properties:
| Property | Type | Description |
|---|---|---|
message |
string | The error message |
status_code |
int | The HTTP status code |
raw_response |
Faraday::Response | 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 |
|---|---|---|
| Models::Errors::BadRequestError | 400 | application/json |
| Models::Errors::AuthenticationError | 401 | application/json |
| Models::Errors::PermissionDeniedError | 403 | application/json |
| Models::Errors::NotFoundError | 404 | application/json |
| Models::Errors::RateLimitError | 429 | application/json |
| Models::Errors::InternalServerError | 500 | application/json |
| Errors::APIError | 4XX, 5XX | */* |
require "moderation_api"
Models = ::ModerationApi::Models
s = ::ModerationApi::ModerationApi.new(
secret_key: "<YOUR_BEARER_TOKEN_HERE>"
)
begin
res = s.analytics.summary(range: Models::Operations::GetAnalyticsSummaryQueryParamRange::THIRTYD)
unless res.object.nil?
# handle response
end
rescue Models::Errors::BadRequestError => e
# handle e.container data
raise e
rescue Models::Errors::AuthenticationError => e
# handle e.container data
raise e
rescue Models::Errors::PermissionDeniedError => e
# handle e.container data
raise e
rescue Models::Errors::NotFoundError => e
# handle e.container data
raise e
rescue Models::Errors::RateLimitError => e
# handle e.container data
raise e
rescue Models::Errors::InternalServerError => e
# handle e.container data
raise e
rescue Errors::APIError => e
# handle default exception
raise e
endThe default server can be overridden globally by passing a URL to the server_url (String) optional parameter when initializing the SDK client instance. For example:
require "moderation_api"
Models = ::ModerationApi::Models
s = ::ModerationApi::ModerationApi.new(
server_url: "https://api.moderationapi.com/v1",
secret_key: "<YOUR_BEARER_TOKEN_HERE>"
)
res = s.analytics.summary(range: Models::Operations::GetAnalyticsSummaryQueryParamRange::THIRTYD)
unless res.object.nil?
# handle response
endSet a timeout in milliseconds for all requests on the client, or for one request:
client = ModerationApi::ModerationApi.new(
secret_key: ENV.fetch("MODAPI_SECRET_KEY"),
timeout_ms: 10_000
)
client.content.submit(
body: Operations::SubmitContentRequestBody.new(content: Operations::TextRequest.new(text: "Hello")),
timeout_ms: 5_000
)Ruby 3.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.