MODERATION API · HTTP REFERENCE
Moderate content
from your backend.
Send text, an image, or both to one HTTPS endpoint. Selkay applies the selected workspace policy and returns a verdict for your application to enforce. There is no Selkay SDK; these examples use standard HTTP libraries.
https://api.selkay.com/v1/moderateHTTPS · JSON request and response · server-to-server
The HTTP request
Send a POST with a bearer key and a JSON object. The minimum text request looks like this:
curl --silent --show-error --request POST \
--url https://api.selkay.com/v1/moderate \
--header "Authorization: Bearer $SELKAY_API_KEY" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data-binary '{"text":"Hello from my app"}' \
--write-out '\nHTTP %{http_code}\n'Call this route from a trusted server only. Selkay rejects requests with an Origin or Sec-Fetch-Mode header, and rejects OPTIONS. Browser and mobile code must call your own backend; never send a Selkay key to a client.
Examples by language and framework
Every snippet calls the same endpoint directly with a native or framework HTTP client. Choose a language below; image encoding examples follow the text requests. Node.js and Bun read process.env, while Deno requires permission to read the key.
JavaScriptNode.js and Bun
Save this top-level await example as .mjs. Node.js 20.6+ can load an ignored local env file with node --env-file=.env moderate.mjs; Bun loads .env automatically. Replace the publish, edit, and reject functions with your application’s own flow.
const apiKey = process.env.SELKAY_API_KEY;
if (!apiKey) throw new Error("SELKAY_API_KEY is not configured");
const response = await fetch("https://api.selkay.com/v1/moderate", {
method: "POST",
headers: {
Authorization: "Bearer " + apiKey,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ text: "A comment from my app" }),
signal: AbortSignal.timeout(20_000), // Set this to your application's latency budget.
});
const result = await response.json().catch(() => null);
if (!response.ok) {
const code = result?.error?.code ?? "unknown_error";
const retryAfter = response.headers.get("Retry-After");
throw new Error("Selkay HTTP " + response.status + " (" + code + "); Retry-After=" + (retryAfter ?? "not set"));
}
if (!result) throw new Error("Selkay returned an unreadable response");
// Check for any non-null error before treating Block as a policy decision.
if (result.error != null) {
console.error("Moderation failed closed", { requestId: result.request_id });
throw new Error("Moderation is temporarily unavailable; keep the submission on hold.");
}
switch (result.verdict) {
case "Pass":
publishText("A comment from my app"); // Continue your normal publish flow.
break;
case "Warn":
askUserToEdit(); // Supply warning copy in your product.
break;
case "Redact":
if (typeof result.cleaned_text !== "string") throw new Error("No cleaned text returned; keep the submission on hold.");
if (result.truncated) throw new Error("Redaction covered only the first 10,000 code units; keep the submission on hold.");
publishText(result.cleaned_text);
break;
case "Block":
rejectSubmission();
break;
default:
throw new Error("Unexpected Selkay verdict");
}JavaScriptDeno
Allow only the key and network host this script needs. Run it with deno run --allow-env=SELKAY_API_KEY --allow-net=api.selkay.com moderate.ts.
const apiKey = Deno.env.get("SELKAY_API_KEY");
if (!apiKey) throw new Error("SELKAY_API_KEY is not configured");
const response = await fetch("https://api.selkay.com/v1/moderate", {
method: "POST",
headers: {
Authorization: "Bearer " + apiKey,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ text: "A comment from my app" }),
signal: AbortSignal.timeout(20_000), // Adjust to your application's latency budget.
});
const result = await response.json().catch(() => null);
if (!response.ok) {
const code = result?.error?.code ?? "unknown_error";
const retryAfter = response.headers.get("Retry-After");
throw new Error("Selkay HTTP " + response.status + " (" + code + "); Retry-After=" + (retryAfter ?? "not set"));
}
if (!result) throw new Error("Selkay returned an unreadable response");
if (result.error != null) {
console.error("Moderation failed closed", { requestId: result.request_id });
throw new Error("Moderation is temporarily unavailable; keep the submission on hold.");
}
// Handle Pass, Warn, Redact, and Block using the same verdict rules below.PythonStandard library
This uses urllib, which ships with Python. An HTTPError includes the non-2xx response body and headers.
import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
api_key = os.environ.get("SELKAY_API_KEY")
if not api_key:
raise RuntimeError("SELKAY_API_KEY is not configured")
request = Request(
"https://api.selkay.com/v1/moderate",
data=json.dumps({"text": "A comment from my app"}).encode("utf-8"),
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json",
},
method="POST",
)
try:
with urlopen(request, timeout=20) as response:
result = json.load(response)
except HTTPError as exc:
try:
error_body = json.loads(exc.read())
except json.JSONDecodeError:
error_body = {}
error = error_body.get("error") or {}
reason = (error.get("details") or {}).get("reason")
retry_after = exc.headers.get("Retry-After")
if exc.code == 429 and reason == "quota_exceeded":
print("Monthly allowance reached; do not retry until usage or plan changes.")
elif exc.code == 429 and retry_after:
print("Rate limited; wait", retry_after, "seconds before a bounded retry.")
raise RuntimeError(f"Selkay HTTP {exc.code}: {error.get('code', 'unknown_error')}") from exc
except URLError as exc:
raise RuntimeError("Could not reach Selkay; handle as an uncertain request outcome.") from exc
if not isinstance(result, dict):
raise RuntimeError("Selkay returned an unreadable decision")
if result.get("error") is not None:
raise RuntimeError("Selkay failed closed; keep the submission on hold.")
verdict = result.get("verdict")
# Replace these calls with your app's publish, review, and reject flow.
if verdict == "Pass":
publish_comment("A comment from my app")
elif verdict == "Warn":
queue_for_review("A comment from my app")
elif verdict == "Redact":
cleaned_text = result.get("cleaned_text")
if not isinstance(cleaned_text, str):
raise RuntimeError("No cleaned text returned; keep the submission on hold.")
if result.get("truncated") is True:
raise RuntimeError("Redaction covered only the first 10,000 code units; keep the submission on hold.")
publish_comment(cleaned_text)
elif verdict == "Block":
reject_comment()
else:
raise RuntimeError("Unexpected Selkay verdict")
print(verdict, result["request_id"])GoStandard library
The example uses a request context timeout, checks the HTTP status, then checks the API’s fail-closed response field.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
func main() {
apiKey := os.Getenv("SELKAY_API_KEY")
if apiKey == "" {
panic("SELKAY_API_KEY is not configured")
}
body, _ := json.Marshal(map[string]string{"text": "A comment from my app"})
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.selkay.com/v1/moderate", bytes.NewReader(body))
if err != nil { panic(err) }
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil { panic(fmt.Errorf("Selkay request failed; outcome may be unknown: %w", err)) }
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil { panic(err) }
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var apiError struct {
Error struct {
Code string `json:"code"`
Details struct { Reason string `json:"reason"` } `json:"details"`
} `json:"error"`
}
_ = json.Unmarshal(responseBody, &apiError)
if resp.StatusCode == http.StatusTooManyRequests {
fmt.Println("Retry-After:", resp.Header.Get("Retry-After"), "reason:", apiError.Error.Details.Reason)
}
panic(fmt.Errorf("Selkay HTTP %d: %s", resp.StatusCode, apiError.Error.Code))
}
var result struct {
RequestID string `json:"request_id"`
Verdict string `json:"verdict"`
CleanedText *string `json:"cleaned_text"`
Truncated bool `json:"truncated"`
Error *string `json:"error"`
}
if err := json.Unmarshal(responseBody, &result); err != nil { panic(err) }
if result.Error != nil { panic("Selkay failed closed; keep the submission on hold") }
switch result.Verdict {
case "Pass":
// Publish the original text.
case "Warn":
// Hold for review or prompt for edits.
case "Redact":
if result.CleanedText == nil { panic("No cleaned text; keep the submission on hold") }
if result.Truncated { panic("Redaction covered only the first 10,000 code units; keep the submission on hold") }
// Publish *result.CleanedText instead of the submitted text.
case "Block":
// Reject or quarantine the submission.
default:
panic("Unexpected Selkay verdict")
}
fmt.Println(result.Verdict, result.RequestID)
}JavaScriptExpress 5
Install express and use Node.js 18 or later for built-in fetch. This route validates text and only publishes after a usable verdict; replace the publish, review, and reject functions with your own application logic. See the Express error handling guide.
import express from "express";
const app = express();
app.use(express.json({ limit: "1mb" }));
const apiKey = process.env.SELKAY_API_KEY;
if (!apiKey) throw new Error("SELKAY_API_KEY is not configured");
app.post("/comments", async (req, res) => {
const text = req.body?.text;
if (typeof text !== "string" || !text.trim()) {
return res.status(400).json({ error: "text_required" });
}
let upstream;
let result;
try {
upstream = await fetch("https://api.selkay.com/v1/moderate", {
method: "POST",
headers: {
Authorization: "Bearer " + apiKey,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ text }),
signal: AbortSignal.timeout(20_000),
});
result = await upstream.json().catch(() => null);
} catch {
return res.status(503).json({ error: "moderation_unavailable" });
}
if (!upstream.ok || !result || result.error != null) {
const requestId = result?.request_id ?? upstream.headers.get("X-Request-Id");
const retryAfter = upstream.headers.get("Retry-After");
const apiError = result?.error && typeof result.error === "object" ? result.error : {};
const code = apiError.code ?? "unknown_error";
const reason = apiError.details?.reason ?? "unknown";
console.warn("Selkay moderation error", {
status: upstream.status,
code,
reason,
requestId,
}); // Do not log the key or submitted content.
if (upstream.status === 429 && retryAfter) res.set("Retry-After", retryAfter);
const status = upstream.status === 400 ? 400 : 503;
return res.status(status).json({ error: "moderation_unavailable", requestId });
}
switch (result.verdict) {
case "Pass":
await publishComment(text); // Your persistence function.
return res.status(201).json({ status: "published" });
case "Warn":
await queueForReview(text); // Do not publish while it is under review.
return res.status(202).json({ status: "review" });
case "Redact":
if (typeof result.cleaned_text !== "string") {
return res.status(503).json({ error: "moderation_unavailable" });
}
if (result.truncated === true) {
await queueForReview(text); // The tail was not redacted.
return res.status(202).json({ status: "review" });
}
await publishComment(result.cleaned_text);
return res.status(201).json({ status: "published_redacted" });
case "Block":
return res.status(422).json({ status: "rejected" });
default:
return res.status(503).json({ error: "moderation_unavailable" });
}
});PythonFastAPI + HTTPX
Install fastapi, httpx, and uvicorn; run with uvicorn app:app. Keep one asynchronous HTTPX client in the FastAPI lifespan so connections are reused, then close it when the app shuts down. See FastAPI lifespan and HTTPX async clients.
from contextlib import asynccontextmanager
import os
import httpx
import logging
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
api_key = os.environ.get("SELKAY_API_KEY")
if not api_key:
raise RuntimeError("SELKAY_API_KEY is not configured")
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.selkay_client = httpx.AsyncClient(timeout=httpx.Timeout(20.0))
yield
await app.state.selkay_client.aclose()
app = FastAPI(lifespan=lifespan)
class Comment(BaseModel):
text: str
@app.post("/comments")
async def moderate_comment(body: Comment, request: Request):
if not body.text.strip():
raise HTTPException(status_code=400, detail="text_required")
try:
upstream = await request.app.state.selkay_client.post(
"https://api.selkay.com/v1/moderate",
headers={
"Authorization": "Bearer " + api_key,
"Accept": "application/json",
},
json={"text": body.text},
)
except httpx.RequestError as exc:
raise HTTPException(status_code=503, detail="moderation_unavailable") from exc
try:
result = upstream.json()
except ValueError as exc:
raise HTTPException(status_code=503, detail="moderation_unavailable") from exc
if not upstream.is_success:
api_error = result.get("error") if isinstance(result, dict) else None
if not isinstance(api_error, dict):
api_error = {}
details = api_error.get("details")
if not isinstance(details, dict):
details = {}
reason = details.get("reason")
retry_after = upstream.headers.get("Retry-After")
logger.warning(
"Selkay HTTP %s code=%s reason=%s request_id=%s",
upstream.status_code,
api_error.get("code", "unknown_error"),
reason or "unknown",
upstream.headers.get("X-Request-Id", "unknown"),
) # Do not log the key or submitted content.
# Inspect status, reason, and Retry-After; do not retry quota_exceeded.
headers = {"Retry-After": retry_after} if upstream.status_code == 429 and retry_after else None
status = 400 if upstream.status_code == 400 else 503
raise HTTPException(status_code=status, detail="moderation_unavailable", headers=headers)
if not isinstance(result, dict) or result.get("error") is not None:
logger.warning(
"Selkay returned a fail-closed decision request_id=%s",
result.get("request_id", "unknown") if isinstance(result, dict) else "unknown",
)
raise HTTPException(status_code=503, detail="moderation_unavailable")
# Apply the returned verdict before storing or publishing the comment.
return resultJavaSpring Boot RestClient
Uses Java 17+, Spring Framework 6.1+, and Spring Boot’s web starter. Configure connect and response timeouts on the request factory; inspect the exception body and headers for non-2xx responses. See the Spring REST client reference.
// Set SELKAY_API_KEY in the process environment.
import java.net.http.HttpClient;
import java.time.Duration;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientResponseException;
// Spring Boot web starter; RestClient is available from Spring Framework 6.1.
@Configuration
class SelkayConfiguration {
@Bean
RestClient selkayClient(RestClient.Builder builder, Environment environment) {
String apiKey = environment.getRequiredProperty("SELKAY_API_KEY");
var httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
var requestFactory = new JdkClientHttpRequestFactory(httpClient);
requestFactory.setReadTimeout(Duration.ofSeconds(20));
return builder
.baseUrl("https://api.selkay.com")
.requestFactory(requestFactory)
.defaultHeaders(headers -> headers.setBearerAuth(apiKey))
.build();
}
}
@Service
class SelkayModerationService {
private final RestClient selkay;
SelkayModerationService(RestClient selkay) {
this.selkay = selkay;
}
JsonNode moderate(String text) {
if (text == null || text.isBlank()) {
throw new IllegalArgumentException("text_required");
}
ResponseEntity<JsonNode> response;
try {
response = selkay.post()
.uri("/v1/moderate")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.body(Map.of("text", text))
.retrieve()
.toEntity(JsonNode.class);
} catch (RestClientResponseException ex) {
HttpHeaders headers = ex.getResponseHeaders();
String retryAfter = headers == null ? null : headers.getFirst("Retry-After");
String errorBody = ex.getResponseBodyAsString();
String code = "unknown_error";
String reason = "unknown";
try {
JsonNode body = new ObjectMapper().readTree(errorBody);
code = body.path("error").path("code").asText(code);
reason = body.path("error").path("details").path("reason").asText(reason);
} catch (JsonProcessingException ignored) { }
String requestId = headers == null ? "unknown" : headers.getFirst("X-Request-Id");
System.err.println("Selkay HTTP " + ex.getStatusCode().value()
+ " code=" + code + " reason=" + reason
+ " Retry-After=" + retryAfter + " request_id=" + requestId);
// Honor Retry-After only when supplied; do not time-retry quota_exceeded.
throw new IllegalStateException("Selkay returned HTTP " + ex.getStatusCode().value()
+ "; keep content on hold", ex);
} catch (ResourceAccessException ex) {
throw new IllegalStateException("Selkay request failed; keep content on hold", ex);
}
if (!response.getStatusCode().is2xxSuccessful() ||
response.getBody() == null || !response.getBody().isObject()) {
throw new IllegalStateException("Selkay returned no usable decision");
}
JsonNode decision = response.getBody();
if (decision.has("error") && !decision.get("error").isNull()) {
throw new IllegalStateException("Selkay failed closed; keep content on hold");
}
return decision;
}
}C#ASP.NET Core
Register an IHttpClientFactory client once, keep the API key in server configuration, and pass the incoming cancellation token through the request. See Microsoft’s HTTP client factory guidance.
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient("Selkay", client =>
{
client.BaseAddress = new Uri("https://api.selkay.com/");
client.Timeout = TimeSpan.FromSeconds(20);
});
var app = builder.Build();
app.MapPost("/comments", async (
CommentSubmission input,
IHttpClientFactory clients,
IConfiguration configuration,
HttpContext httpContext,
CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(input.Text))
return Results.BadRequest(new { error = "text_required" });
var apiKey = configuration["SELKAY_API_KEY"];
if (string.IsNullOrWhiteSpace(apiKey))
throw new InvalidOperationException("SELKAY_API_KEY is not configured");
using var request = new HttpRequestMessage(HttpMethod.Post, "v1/moderate")
{
Content = JsonContent.Create(new { text = input.Text })
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage upstream;
try
{
upstream = await clients.CreateClient("Selkay").SendAsync(request, cancellationToken);
}
catch (HttpRequestException)
{
return Results.Problem(statusCode: 503, title: "Moderation unavailable");
}
catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return Results.Problem(statusCode: 503, title: "Moderation timed out");
}
using (upstream)
{
var raw = await upstream.Content.ReadAsStringAsync(cancellationToken);
if (!upstream.IsSuccessStatusCode)
{
var retryAfter = upstream.Headers.RetryAfter?.ToString();
var code = "unknown_error";
var reason = "unknown";
try
{
using var errorDocument = JsonDocument.Parse(raw);
var errorRoot = errorDocument.RootElement;
if (errorRoot.ValueKind == JsonValueKind.Object &&
errorRoot.TryGetProperty("error", out var apiError) &&
apiError.ValueKind == JsonValueKind.Object)
{
if (apiError.TryGetProperty("code", out var codeValue) &&
codeValue.ValueKind == JsonValueKind.String)
code = codeValue.GetString() ?? code;
if (apiError.TryGetProperty("details", out var details) &&
details.ValueKind == JsonValueKind.Object &&
details.TryGetProperty("reason", out var reasonValue) &&
reasonValue.ValueKind == JsonValueKind.String)
reason = reasonValue.GetString() ?? reason;
}
}
catch (JsonException) { }
if ((int)upstream.StatusCode == 429 && retryAfter is not null)
httpContext.Response.Headers["Retry-After"] = retryAfter;
var requestId = upstream.Headers.TryGetValues("X-Request-Id", out var requestIds)
? requestIds.FirstOrDefault() ?? "unknown"
: "unknown";
Console.Error.WriteLine("Selkay HTTP " + (int)upstream.StatusCode +
"; code=" + code + "; reason=" + reason +
"; request_id=" + requestId);
// A quota_exceeded reason is not a timed retry; forward Retry-After only when supplied.
return Results.Problem(statusCode: 503, title: "Moderation unavailable");
}
try
{
using var parsed = JsonDocument.Parse(raw);
var decision = parsed.RootElement;
if (decision.ValueKind != JsonValueKind.Object)
return Results.Problem(statusCode: 503, title: "Selkay returned an unreadable decision");
if (decision.TryGetProperty("error", out var serviceError) &&
serviceError.ValueKind != JsonValueKind.Null)
return Results.Problem(statusCode: 503, title: "Moderation unavailable");
// Apply decision.GetProperty("verdict") before storing or publishing.
return Results.Ok(decision.Clone());
}
catch (JsonException)
{
return Results.Problem(statusCode: 503, title: "Selkay returned unreadable JSON");
}
}
});
app.Run();
record CommentSubmission(string Text);PHPLaravel HTTP client
Read the key from Laravel configuration backed by the environment. Laravel’s HTTP client does not throw automatically for 4xx and 5xx responses, so check the status explicitly. See the Laravel HTTP client reference.
<?php
// Add this entry inside config/services.php's returned array:
// 'selkay' => ['key' => env('SELKAY_API_KEY')],
// Then use the configured key from a controller or service.
$key = config('services.selkay.key');
if (! is_string($key) || $key === '') {
throw new RuntimeException('SELKAY_API_KEY is not configured');
}
if (! is_string($text) || trim($text) === '') {
abort(400, 'text_required');
}
try {
$response = IlluminateSupportFacadesHttp::withToken($key)
->acceptJson()
->asJson()
->connectTimeout(5)
->timeout(20)
->post('https://api.selkay.com/v1/moderate', [
'text' => $text,
]);
} catch (IlluminateHttpClientConnectionException $exception) {
abort(503, 'Moderation unavailable; keep the submission on hold.');
}
if (! $response->successful()) {
$apiError = $response->json('error', []);
$reason = data_get($apiError, 'details.reason');
$retryAfter = $response->header('Retry-After');
IlluminateSupportFacadesLog::warning('Selkay moderation request failed', [
'status' => $response->status(),
'reason' => $reason,
'request_id' => $response->header('X-Request-Id'),
]); // Do not log the key or submitted content.
$headers = $response->status() === 429 && $retryAfter !== null
? ['Retry-After' => $retryAfter]
: [];
// Do not retry quota_exceeded on a timer; the API provides no Retry-After for quota.
abort($response->status() === 400 ? 400 : 503, 'Moderation unavailable.', $headers);
}
$decision = $response->json();
if (! is_array($decision) || ($decision['error'] ?? null) !== null) {
abort(503, 'Moderation unavailable; keep the submission on hold.');
}
// Apply $decision['verdict'] before storing or publishing.
return $decision;RubyRails + Net::HTTP
Uses Rails encrypted credentials with an environment fallback, explicit TLS, and finite connect/read timeouts. See Ruby’s Net::HTTP reference.
require "json"
require "net/http"
require "uri"
class SelkayUnavailable < StandardError; end
class SelkayModeration
ENDPOINT = URI("https://api.selkay.com/v1/moderate")
def self.call(payload:)
unless payload.is_a?(Hash)
raise ArgumentError, "payload_must_be_an_object"
end
text = payload[:text]
image = payload[:image]
has_text = text.is_a?(String) && !text.strip.empty?
has_image = image.is_a?(String) && !image.strip.empty?
raise ArgumentError, "text_or_image_required" unless has_text || has_image
api_key =
Rails.application.credentials.dig(:selkay, :api_key) ||
ENV.fetch("SELKAY_API_KEY")
request = Net::HTTP::Post.new(ENDPOINT)
request["Authorization"] = "Bearer #{api_key}"
request["Content-Type"] = "application/json"
request["Accept"] = "application/json"
request.body = JSON.generate(payload)
http = Net::HTTP.new(ENDPOINT.hostname, ENDPOINT.port)
http.use_ssl = true
http.open_timeout = 5
http.read_timeout = 20
response = http.start { |connection| connection.request(request) }
result = JSON.parse(response.body)
unless response.is_a?(Net::HTTPSuccess)
api_error = result.is_a?(Hash) ? result["error"] : nil
api_error = {} unless api_error.is_a?(Hash)
reason = api_error.dig("details", "reason")
retry_after = response["Retry-After"]
request_id = response["X-Request-Id"]
code = api_error["code"]
Rails.logger.warn(
"Selkay HTTP #{response.code} code=#{code} reason=#{reason} request_id=#{request_id}"
)
# Honor retry_after only when supplied; do not retry quota_exceeded on a timer.
raise SelkayUnavailable, "Selkay returned HTTP #{response.code}; keep content on hold"
end
unless result.is_a?(Hash) && result["error"].nil?
raise SelkayUnavailable, "Selkay failed closed; keep content on hold"
end
result
rescue Net::OpenTimeout, Net::ReadTimeout, Net::HTTPError, SocketError,
EOFError, Errno::ECONNRESET, JSON::ParserError => error
raise SelkayUnavailable, "Selkay request failed; outcome may be unknown", cause: error
end
endRustAxum + reqwest
Add axum, serde, serde_json, and reqwest with its json feature. Build one timed client at startup and share it through Axum state. See the Reqwest client builder.
use axum::{
extract::State,
http::{header::RETRY_AFTER, StatusCode},
Json,
};
use serde_json::{json, Value};
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone)]
struct AppState {
client: reqwest::Client,
api_key: Arc<str>,
}
#[derive(serde::Deserialize)]
struct Comment {
text: String,
}
fn build_state() -> Result<AppState, Box<dyn std::error::Error>> {
let api_key = std::env::var("SELKAY_API_KEY")?;
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(20))
.build()?;
Ok(AppState {
client,
api_key: Arc::from(api_key),
})
}
// Create this state once at startup, then pass it to Router::with_state.
async fn moderate_comment(
State(state): State<AppState>,
Json(comment): Json<Comment>,
) -> Result<Json<Value>, StatusCode> {
if comment.text.trim().is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
let response = state.client
.post("https://api.selkay.com/v1/moderate")
.bearer_auth(state.api_key.as_ref())
.header("Accept", "application/json")
.json(&json!({ "text": comment.text }))
.send()
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let status = response.status();
let retry_after = response.headers()
.get(RETRY_AFTER)
.and_then(|value| value.to_str().ok())
.unwrap_or("not set")
.to_owned();
let request_id = response.headers()
.get("x-request-id")
.and_then(|value| value.to_str().ok())
.unwrap_or("unknown")
.to_owned();
let result = response.json::<Value>().await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
if !status.is_success() {
let code = result.pointer("/error/code").and_then(Value::as_str).unwrap_or("unknown_error");
let reason = result.pointer("/error/details/reason").and_then(Value::as_str).unwrap_or("unknown");
eprintln!("Selkay HTTP {status}; code={code}; reason={reason}; Retry-After={retry_after}; request_id={request_id}");
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
if !result.is_object() || result.get("error").is_some_and(|error| !error.is_null()) {
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
// Apply the returned verdict before storing or publishing the comment.
Ok(Json(result))
}Text, image, or both
Send one JSON object. Text-only requests require non-empty text. An image request uses one inline base64 data URI in image; text may be omitted or added for a combined decision.
{
"text": "Review this comment"
}{
"image": "data:image/png;base64,<BASE64_IMAGE>"
}{
"text": "Caption submitted with the photo",
"image": "data:image/jpeg;base64,<BASE64_IMAGE>"
}Supported image types are PNG, JPEG, and WebP. Encode the file bytes with the matching MIME type and include the full data:image/...;base64, prefix.
Encode an imageNode.js / Bun
import { readFile } from "node:fs/promises";
const bytes = await readFile("./uploads/photo.webp");
const image = "data:image/webp;base64," + bytes.toString("base64");
const body = { text: "Photo attached to a public profile", image };
// POST body: JSON.stringify(body), using the same headers and response handling above.Encode an imageDeno
Run with --allow-read=./uploads and --allow-env=SELKAY_API_KEY; add --allow-net=api.selkay.com to the request command.
import { Buffer } from "node:buffer";
const bytes = await Deno.readFile("./uploads/photo.webp");
const image = "data:image/webp;base64," + Buffer.from(bytes).toString("base64");
const body = { text: "Photo attached to a public profile", image };
// Run with --allow-read=./uploads and --allow-env=SELKAY_API_KEY.
// POST body: JSON.stringify(body), using the same fetch request and response handling above.Encode an imagePython
import base64
from pathlib import Path
image_bytes = Path("./uploads/photo.webp").read_bytes()
image = "data:image/webp;base64," + base64.b64encode(image_bytes).decode("ascii")
payload = {"text": "Photo attached to a public profile", "image": image}
# Send payload as JSON using the same Authorization and Content-Type headers above.Encode an imageGo
package main
import (
"encoding/base64"
"os"
)
func imagePayload(path string) (map[string]string, error) {
imageBytes, err := os.ReadFile(path)
if err != nil { return nil, err }
image := "data:image/webp;base64," + base64.StdEncoding.EncodeToString(imageBytes)
return map[string]string{
"text": "Photo attached to a public profile",
"image": image,
}, nil
}
// JSON-encode the returned map and POST it with the Go example's headers.Encode an imageJava
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.Map;
byte[] bytes = Files.readAllBytes(Path.of("uploads/photo.webp"));
String image = "data:image/webp;base64," + Base64.getEncoder().encodeToString(bytes);
Map<String, String> payload = Map.of(
"text", "Photo attached to a public profile",
"image", image
);
// Serialize payload as JSON and POST it using the RestClient configured above.Encode an imageC#
using System.Net.Http.Json;
var bytes = await File.ReadAllBytesAsync("uploads/photo.webp", cancellationToken);
var image = "data:image/webp;base64," + Convert.ToBase64String(bytes);
var payload = new { text = "Photo attached to a public profile", image };
// Send with PostAsJsonAsync("v1/moderate", payload, cancellationToken).Encode an imagePHP
$bytes = file_get_contents("uploads/photo.webp");
if ($bytes === false) {
throw new RuntimeException("Could not read image");
}
$image = "data:image/webp;base64," . base64_encode($bytes);
$payload = [
"text" => "Photo attached to a public profile",
"image" => $image,
];
// Pass $payload to the Laravel HTTP client's post() call.Encode an imageRuby
require "base64"
bytes = File.binread("uploads/photo.webp")
image = "data:image/webp;base64," + Base64.strict_encode64(bytes)
payload = { text: "Photo attached to a public profile", image: image }
decision = SelkayModeration.call(payload: payload)
# Apply decision["verdict"] before storing or publishing.Encode an imageRust
use base64::{engine::general_purpose::STANDARD, Engine as _};
use serde_json::json;
let bytes = std::fs::read("uploads/photo.webp")?;
let image = format!("data:image/webp;base64,{}", STANDARD.encode(bytes));
let payload = json!({
"text": "Photo attached to a public profile",
"image": image
});
// Send payload with the shared Reqwest client using .json(&payload).Selkay does not download remote image URLs and does not accept an images array. The image is processed from this request’s inline data URI. Selkay hashes decoded image bytes with SHA-256 for exact-image decision caching. Identical bytes may reuse a prior decision; the response does not include a cache-hit field. Send Cache-Control: no-cache when you need a fresh evaluation. Image bytes are not stored as cache values, but the derived hash and decision may be cached. HTTP responses use Cache-Control: no-store.
Request fields and limits
| Field | Required | Type and behavior |
|---|---|---|
text | Required unless a valid image is sent | String. Must contain non-whitespace characters for text-only requests. UTF-8 text value maximum 1 MiB; text-only JSON body also maximum 1 MiB. |
image | Required unless non-empty text is sent | One inline base64 data URI: PNG, JPEG, or WebP. Decoded image maximum 3 MiB; each side at most 8,192 pixels and total at most 16,000,000 pixels. |
policy_id | No | Active policy ID in the authenticated workspace. Omit it to use the workspace default. |
context | No | Object with optional platform, message_type, visibility, conversation_stage, sender_age_band, verified_sender (boolean), sender_role, and profile. |
user_hash | No | Non-empty pseudonymous value for associating requests with the same user. Do not send a name, email, or raw account identifier. |
{
"text": "Review this comment",
"policy_id": "YOUR_ACTIVE_POLICY_ID"
}Copy an ID from Dashboard → Policies. Pass an active policy from this workspace to override the default; omit policy_id to use the default. Draft or inactive IDs return 400; unknown IDs return 404. Completed decisions report the effective policy ID; service errors may omit it.
Image size and request-unit limits
All size limits apply at once. A request that fits the image-file limit can still exceed the JSON-body limit after base64 encoding, text, and JSON fields are added.
| Limit | Maximum | What is measured |
|---|---|---|
| Text-only request | 1 MiB | Entire UTF-8 JSON body, including JSON syntax. The text value is also limited to 1 MiB of UTF-8 data. |
| Text with an image | 1 MiB | UTF-8 size of the text value, if provided. |
| Decoded image | 3 MiB | Binary image size after base64 decoding. |
| Image dimensions | 8,192 px per side; 16,000,000 pixels total | Both the per-side and total-pixel limits must pass. |
| Image or multimodal request | 5 MiB | Entire UTF-8 JSON body, including the data URI prefix, base64 text, any moderation text, and JSON syntax. |
MiB means 1,048,576 bytes. Base64 length is 4 × ceil(binary_bytes / 3), before the data URI prefix and JSON fields, so check the final encoded body too. The API accepts one PNG, JPEG, or WebP image as an inline base64 data URI. Its declared MIME type must match the image bytes. It does not fetch remote image URLs or accept an images array.
How request units are calculated
Request units measure moderation usage, not just the number of HTTP calls. For non-whitespace text, Selkay counts JavaScript UTF-16 code units in the submitted string and rounds up in blocks of 2,500. Whitespace inside non-empty text counts; omitted, empty, or whitespace-only text adds zero text units. Each image adds one unit. The total has a one-unit minimum.
Formula: max(1, ceil(text_code_units / 2,500) + image_units), where blank or omitted text contributes 0 and image_units is 1 when an image is sent, otherwise 0.
| Request | Text length | Image units | Total |
|---|---|---|---|
| Text only | 1–2,500 UTF-16 code units | 0 | 1 unit |
| Text only | 2,501–5,000 UTF-16 code units | 0 | 2 units |
| Image only | None | 1 | 1 unit |
| Text and image | 2,501–5,000 UTF-16 code units | 1 | 3 units |
Some characters, including many emoji, use two UTF-16 code units. Use the response’s request_units value to reconcile usage instead of calculating it with a language-specific string-length function. Compare your usage with the current monthly plan allowance. Language is detected automatically; a language or lang field and language override headers are rejected.
Read and enforce the decision
A completed moderation decision returns HTTP 200, even when the policy verdict is Block. First check the HTTP status, then check error, then apply the verdict. Selkay returns a decision; your application still controls publishing, editing, review, and rejection.
type ModerationVerdict = "Pass" | "Warn" | "Redact" | "Block";
type ModerationModality = "text" | "image" | "multimodal";
type ModerationCategory =
| "harassment" | "hate_speech" | "sexual_explicit" | "violence"
| "self_harm" | "spam" | "pii" | "profanity"
| "prompt_injection" | "ai_generated";
type ModerateResponse = {
request_id: string;
policy_id?: string;
verdict: ModerationVerdict;
category: ModerationCategory | null;
confidence: number; // 0 to 1
actions: string[];
cleaned_text?: string | null;
truncated: boolean;
request_units: number;
modality?: ModerationModality;
error?: string | null;
};
type ModerateHttpError = {
status: number;
error: {
code: string;
message: string;
details?: Record<string, unknown>;
};
};{
"request_id": "01940a5c-...",
"policy_id": "YOUR_ACTIVE_POLICY_ID",
"verdict": "Redact",
"category": "pii",
"confidence": 0.92,
"actions": ["Redact"],
"cleaned_text": "Contact me at ****.",
"truncated": false,
"request_units": 1,
"modality": "text",
"error": null
}| Field | Meaning |
|---|---|
request_id | Unique request identifier. The same value is returned in the X-Request-Id response header. |
policy_id | The policy used for this decision. It may be absent when a fail-closed service error occurs. Store it with the request ID for audits. |
verdict | Pass, Warn, Redact, or Block. A policy block is still HTTP 200. |
category | Primary category matched by the decision, or null. ai_generated applies to visual assets; it is not evaluated for text-only requests. |
confidence | Confidence value from 0 to 1. Enforce the returned policy verdict; do not silently replace policy behavior with a new application threshold. |
actions | Actions applied by the active policy. |
cleaned_text | Optional redacted text. It may be absent or null; never substitute the original text when a Redact decision has no cleaned text. |
truncated | true when text exceeds 10,000 JavaScript string code units. Redaction changes only the first 10,000 code units; the remaining text is passed through unchanged. |
request_units | Usage units for this completed decision: each 2,500 UTF-16 code units of non-whitespace text rounds up to one unit, plus one for an image. The total is at least one; see calculation examples. |
modality | Optional value: text, image, or multimodal. |
error | Optional string or null. A non-null error on HTTP 200 is a fail-closed service result. |
error even after HTTP 200. If moderation cannot complete, the API returns verdict: "Block" with a non-null error. Keep the content on hold and treat it as a service failure, not a policy match. Log the request ID, not the submitted content or key.What each verdict means
| Verdict | Application behavior |
|---|---|
Pass | Continue the normal flow for this content. |
Warn | Hold the content for review or prompt for edits. Supply warning copy in your product; there is no warning_message response field. |
Redact | Use cleaned_text in place of the submitted text only when it is a string. If it is null or missing, keep the submission on hold. Check truncated for long text. |
Block | Reject or quarantine the content. If error is non-null, this is a fail-closed service result rather than a policy match. |
The response contains the effective action after plan gating. Free supports Pass and Block. Redact never changes image pixels: on image-only requests, Redact is converted to Warn before plan gating; Redact is also converted to Warn for the ai_generated category. A Free plan may therefore return Pass for those actions. In a text-and-image request, cleaned_text applies to text only.
Handle HTTP errors
A non-2xx response means the request did not return a moderation decision. Branch on the HTTP status first, then inspect the error body. Most errors use this shape:
{
"status": 400,
"error": {
"code": "invalid_request",
"message": "...",
"details": {}
}
}| HTTP | Code and detail | What to do |
|---|---|---|
400 | invalid_request | Correct the JSON, field types, required content, image data, or size. An inactive selected policy is also a 400. |
401 | unauthorized | Check that the API key is present, active, unexpired, and belongs to the expected workspace. |
403 | forbidden | Call from your backend and verify workspace access. Browser-origin requests are rejected. |
404 | not_found | The selected policy_id does not exist in this workspace. |
405 | method_not_allowed | Use POST. This response body omits the top-level status; use the HTTP status code. |
429 | rate_limited; inspect error.details.reason | rate_limited: honor Retry-After when present. quota_exceeded: monthly allowance is reached; this route does not currently send Retry-After for quota. Do not retry until the allowance resets or plan/overage settings change. |
500 | internal_error | For an unexpected server error, use a small bounded retry with exponential backoff and jitter. Do not retry indefinitely. |
A 429 from the moderation route uses error.code: "rate_limited" for both throttling and quota exhaustion. Distinguish the cases using error.details.reason; quota errors are not fixed by a short retry delay.
Secrets, retries, and user data
- Use a secret store in production. Inject
SELKAY_API_KEYat runtime from your deployment platform’s secret manager. For local work, use an ignored.envfile with a runtime-specific loader, or export the variable in your shell; commit only a.env.examplewith an empty placeholder. Never put a live key in source, a URL, a frontend-prefixed environment variable, source maps, logs, or error reports. - Limit access and rotate keys. Give the key only to the backend service that needs it. Use separate keys for environments where your workspace setup allows, restrict who can read deployment secrets, and rotate promptly after suspected exposure or staff/infra changes. Deploy the replacement before revoking the old key.
- Set a finite timeout. The examples use 20 seconds as a sample value. Set a deadline that fits your app and measured Selkay latency; a client timeout does not prove the server did not finish the request.
- Retry deliberately. Honor
Retry-Afteron a timed 429. Do not retry aquota_exceededresult until usage or plan settings change. For network failures or HTTP 500, use a small retry limit with exponential backoff and jitter. Do not retry 4xx validation/auth errors unchanged or a completed HTTP 200 decision. - Do not assume exactly-once processing. If a POST times out after it was sent, the outcome may be unknown. The moderation route does not promise idempotent retries. Keep content unpublished until a usable decision is available, and retry only when duplicate evaluation is acceptable.
- Minimize personal data in requests and logs. Send only moderation context you need. Keep names, emails, and message bodies out of routine logs. If using
user_hash, generate a stable pseudonymous value on your server, such as an HMAC, rather than sending a raw user identifier. - Validate images before encoding. Check actual file type and size, not only the filename. Keep the decoded file at or below 3 MiB, each dimension at or below 8,192 pixels, total pixels at or below 16 megapixels, and the complete JSON body at or below 5 MiB.
- Keep the redaction boundary in view. When
truncatedis true, text after the first 10,000 JavaScript string code units passes through unchanged incleaned_text. Do not treat the returned value as a fully redacted copy.
Record the X-Request-Id response header (also in request_id on successful decisions) with the HTTP status and error code. Avoid logging the authorization header or raw submitted content.
Agent skill
Add the official Selkay moderation skill to your agent (Cursor, Claude Code, Codex, Windsurf).
npx skills add Selkay-dev/selkay-skillSchemas, byte limits, and response headers.
Distinguish edge errors from policy blocks.
10k-char window and truncation guardrails.
TypeScript and Python with retry and backoff.
This reference describes the current POST /v1/moderate HTTP contract. Use the official agent skill to scaffold native clients directly in your codebase.