Skip to content
moderation-apiPublic

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Moderation API Ruby SDK

Gem

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.

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 using RubyGems:

gem install moderation_api

SDK Example Usage

Example

require "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
end

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 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")
  })
))

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 = 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}"
end

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

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
end

Authentication

Per-Client Security Schemes

This 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
end

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:

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}" }
end

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

Error Handling

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 */*

Example

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
end

Server Selection

Override Server URL Per-Client

The 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
end

Timeouts

Set 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
)

Requirements

Ruby 3.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

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages