みんなの自動翻訳@KI
ヘルプ

API仕様

みんなの自動翻訳@KIでは、以下のAPIを提供しています。

共通

認証情報

APIを使用するには、サーバー名、ユーザー名、APIキー、APIシークレットが必要です。みんなの自動翻訳@KIマイページにログインし、[API情報]にある[API認証情報をコピー]ドロップダウンメニューからコピーしてください。

認証形式

OAuth 1.0(2-legged)、OAuth 2.0(Client Credentials)

通信形式

POST(application/x-www-form-urlencoded、multipart/form-data、application/json)

処理コード

処理コードはHTTPステータスコードとは異なります。HTTPステータスコードが200の場合に、レスポンスに処理コードが含まれます。
  • 0: 成功
  • 500: API keyエラー
  • 501: nameエラー
  • 510: OAuth認証エラー
  • 511: OAuthヘッダエラー
  • 520: アクセスURLエラー
  • 521: アクセスURLエラー
  • 522: リクエストkeyエラー
  • 523: リクエストnameエラー
  • 524: リクエストパラメータエラー
  • 525: リクエストパラメータエラー(送信データサイズ制限)
  • 530: 権限エラー
  • 531: 実行エラー
  • 10001: システムエラー
  • 10002: 当月の翻訳量上限超過
  • 10003: 有効な契約無し

利用可能な翻訳エンジンの取得

URL

https://minna-mt.k-intl.jp/api/mt_list/

リクエストパラメータ

パラメータ 必須 説明
name Yes ユーザー名
key Yes APIキー
access_token No

OAuth 2.0アクセストークン

設定しない場合、OAuth 1.0で認証されます

取得方法は下記「OAuth 2.0アクセストークンの取得」を参照

type No

レスポンスタイプ

  • xml: XML形式
  • json: JSON形式

(初期値: xml

lang_s No

原言語で絞り込み

  • 設定しない場合、すべての原言語のエンジンを取得します。
  • 設定する場合、可能な値は「ja」「en」「zh-CN」などです。
lang_t No

訳言語で絞り込み

  • 設定しない場合、すべての訳言語のエンジンを取得します。
  • 設定する場合、可能な値は「ja」「en」「zh-CN」などです。
mt_type No

翻訳エンジン種別で絞り込み

  • 設定しない場合、すべての種別のエンジンを取得します。
  • 設定する場合、可能な値は以下の通りです。
  • standard: 標準翻訳エンジン
  • adapted: 追加学習エンジン
  • custom: 用語適用エンジン
追加学習エンジンおよび用語適用エンジンは、本サービスのオプションサービスにてそれぞれのエンジンを作成したユーザーのみ利用できます。

レスポンス

フィールド 説明
/resultset ルート要素
/resultset/code 処理コード(詳細は上記参照)
/resultset/message 処理メッセージ
/resultset/request 送信要素
/resultset/result 結果要素
/resultset/result/list 翻訳エンジンリスト
/resultset/result/list/item 翻訳エンジン要素(0個以上)
/resultset/result/list/item/id 翻訳エンジンID
/resultset/result/list/item/name 翻訳エンジン名称
/resultset/result/list/item/lang_s 原言語
/resultset/result/list/item/lang_t 訳言語
/resultset/result/list/item/limit 翻訳対象テキストのリクエストあたり最大長さ(単位: byte)

言語判定

URL

https://minna-mt.k-intl.jp/api/langdetect/

リクエストパラメータ

パラメータ 必須 説明
name Yes ユーザー名
key Yes APIキー
access_token No

OAuth 2.0アクセストークン

設定しない場合、OAuth 1.0で認証されます

取得方法は下記「OAuth 2.0アクセストークンの取得」を参照

type No

レスポンスタイプ

  • xml: XML形式
  • json: JSON形式

(初期値: xml

text Yes

対象テキスト

レスポンス

フィールド 説明
/resultset ルート要素
/resultset/code 処理コード(詳細は上記参照)
/resultset/message 処理メッセージ
/resultset/request 送信要素
/resultset/result 結果要素
/resultset/result/langdetect 可能性のある言語のリスト
/resultset/result/langdetect/item 可能性のある言語(0個以上)
/resultset/result/langdetect/item/lang 言語コード
/resultset/result/langdetect/item/rate 確率
判定結果の例
"langdetect": []
判定不能(本サービスで対応していない言語の場合など)
"langdetect": [{"lang": "en", "rate": 0.95}]
英語である確率95%
"langdetect": [{"lang": "es", "rate": 0.4}, {"lang": "it", "rate": 0.3}]
スペイン語である確率40%、イタリア語である確率30%

翻訳

URL

https://minna-mt.k-intl.jp/api/mt/<翻訳エンジンID>/

翻訳エンジンIDは、上記「利用可能な翻訳エンジンの取得」APIで取得できます。

リクエストパラメータ

パラメータ 必須 説明
name Yes ユーザー名
key Yes APIキー
access_token No

OAuth 2.0アクセストークン

設定しない場合、OAuth 1.0で認証されます

取得方法は下記「OAuth 2.0アクセストークンの取得」を参照

type No

レスポンスタイプ

  • xml: XML形式
  • json: JSON形式

(初期値: json

text Yes

翻訳対象テキスト

改行ごとに翻訳します。(注を参照)

split No

文区切り

  • 0: 各行のテキストを文ごとに区切らずに翻訳します。
  • 1: 各行のテキストを文ごとに区切って翻訳します。

(初期値: 0

xml No

XMLタグを考慮した翻訳

  • 0: 翻訳時にXMLタグを考慮しません。XMLタグも通常の文字列として翻訳します。
  • 1: 翻訳時にXMLタグを考慮します。翻訳結果の&、'、"、<、>をエスケープします。
  • 2: 翻訳時にXMLタグを考慮します。翻訳結果の<、>をエスケープします。

(初期値: 0

複数の文章を改行で区切って一度にリクエストすることで、バルク翻訳が可能です。改行文字は翻訳文字数に加算されません。多数の文章を翻訳する場合、バルク翻訳をすることで翻訳速度が数倍になります。

レスポンス

フィールド 説明
/resultset ルート要素
/resultset/code 処理コード(詳細は上記参照)
/resultset/message 処理メッセージ
/resultset/request 送信要素
/resultset/result 結果要素
/resultset/result/text 翻訳結果テキスト
/resultset/result/information 翻訳処理内容詳細要素
/resultset/result/information/text-s 原文
/resultset/result/information/text-t 訳文
/resultset/result/information/sentence 行のリスト
/resultset/result/information/sentence/item 行ごとの翻訳処理内容詳細要素(1個以上)
/resultset/result/information/sentence/item/text-s 行ごとの原文
/resultset/result/information/sentence/item/text-t 行ごとの訳文
/resultset/result/information/sentence/item/split 行ごとの文のリスト
/resultset/result/information/sentence/item/split/item 文ごとの翻訳処理内容詳細要素(1個以上)
/resultset/result/information/sentence/item/split/item/text-s 文ごとの原文
/resultset/result/information/sentence/item/split/item/text-t 文ごとの訳文

OAuth 2.0アクセストークンの取得

URL

https://minna-mt.k-intl.jp/oauth2/token.php

リクエストパラメータ

パラメータ 必須 説明
grant_type Yes client_credentials
client_id Yes APIキー
client_secret Yes APIシークレット

レスポンス(JSON)

フィールド 説明
access_token アクセストークン
expires_in 有効期間の長さ(秒)
翻訳リクエストのたびにアクセストークンを取得することは避けてください。セキュリティの面からもパフォーマンスの面からも推奨されません。有効期間内のアクセストークンを再利用してください。

サンプルコード

以下のサンプルコードでは、OAuth 2.0を使用し、アクセストークンをファイルに保存します。
import json
import sys
import time
from pathlib import Path
from urllib import request

class Translator:
  def __init__(self,
    user_name,
    api_key,
    api_secret,
    server_name,
    token_file_path,
  ):
    self._user_name = user_name
    self._api_key = api_key
    self._api_secret = api_secret
    self._token_file = Path(token_file_path)
    self._token_endpoint = f"https://{server_name}/oauth2/token.php"
    self._mt_endpoint = f"https://{server_name}/api/mt"

  def translate(self,
    source_text,
    engine_id,
    split,
    xml,
  ):
    access_token = self._get_access_token()
    result = self._post_data(f"{self._mt_endpoint}/{engine_id}/", {
      'name': self._user_name,
      'key': self._api_key,
      'access_token': access_token,
      'type': 'json',
      'text': source_text,
      'split': split,
      'xml': xml,
    })
    result_code = result['resultset']['code']
    if result_code != 0:
      raise RuntimeError(f"Translation error {result_code}")
    target_text = result['resultset']['result']['text']
    return target_text

  def _get_access_token(self):
    access_token = self._load_access_token()
    if access_token is not None: return access_token
    token = self._post_data(self._token_endpoint, {
      'grant_type': 'client_credentials',
      'client_id': self._api_key,
      'client_secret': self._api_secret,
    })
    access_token = token['access_token']
    expires_in = token['expires_in']
    self._save_token(access_token, expires_in)
    return access_token

  def _load_access_token(self):
    if not self._token_file.is_file(): return None
    token_json = self._token_file.read_text()
    token = json.loads(token_json)
    access_token = token['access_token']
    expires_at = token['expires_at']
    return access_token if expires_at > time.time() else None

  def _save_token(self, access_token, expires_in):
    token_json = json.dumps({
      'access_token': access_token,
      'expires_at': 0.9 * expires_in + time.time(),
    })
    self._token_file.write_text(token_json)

  def _post_data(self, url, data):
    request_body = json.dumps(data).encode('utf-8')
    http_request = request.Request(
      url,
      method='POST',
      headers={'Content-Type': 'application/json'},
      data=request_body,
    )
    with request.urlopen(http_request) as response:
      response_body = response.read().decode('utf-8')
    return json.loads(response_body)

try:
  source_text = sys.stdin.read()
  translator = Translator(...)
  target_text = translator.translate(source_text, ...)
  sys.stdout.write(f"{target_text}\n")
except Exception as error:
  sys.stderr.write(f"{error}\n")
  sys.exit(1)
const fs = require('fs');

class Translator {
  #userName;
  #apiKey;
  #apiSecret;
  #tokenFilePath;
  #tokenEndpoint;
  #mtEndpoint;

  constructor(
    userName,
    apiKey,
    apiSecret,
    serverName,
    tokenFilePath,
  ) {
    this.#userName = userName;
    this.#apiKey = apiKey;
    this.#apiSecret = apiSecret;
    this.#tokenFilePath = tokenFilePath;
    this.#tokenEndpoint = `https://${serverName}/oauth2/token.php`;
    this.#mtEndpoint = `https://${serverName}/api/mt`;
  }

  async translate(
    sourceText,
    engineId,
    split,
    xml,
  ) {
    const accessToken = await this.#getAccessToken();
    const result = await this.#postData(`${this.#mtEndpoint}/${engineId}/`, {
      name: this.#userName,
      key: this.#apiKey,
      access_token: accessToken,
      type: 'json',
      text: sourceText,
      split: split,
      xml: xml,
    });
    const resultCode = result.resultset.code;
    if (resultCode !== 0)
      throw new Error(`Translation error ${resultCode}`);
    const targetText = result.resultset.result.text;
    return targetText;
  }

  async #getAccessToken() {
    let accessToken = this.#loadAccessToken();
    if (accessToken !== null) return accessToken;
    const token = await this.#postData(this.#tokenEndpoint, {
      grant_type: 'client_credentials',
      client_id: this.#apiKey,
      client_secret: this.#apiSecret,
    });
    accessToken = token.access_token;
    const expiresIn = token.expires_in;
    this.#saveToken(accessToken, expiresIn);
    return accessToken;
  }

  #loadAccessToken() {
    if (!fs.existsSync(this.#tokenFilePath)) return null;
    const now = Date.now() / 1000;
    const tokenJson = fs.readFileSync(this.#tokenFilePath, 'utf8');
    const token = JSON.parse(tokenJson);
    const accessToken = token.access_token;
    const expiresAt = token.expires_at;
    return (expiresAt > now) ? accessToken : null;
  }

  #saveToken(accessToken, expiresIn) {
    const now = Date.now() / 1000;
    const tokenJson = JSON.stringify({
      access_token: accessToken,
      expires_at: 0.9 * expiresIn + now,
    });
    fs.writeFileSync(this.#tokenFilePath, tokenJson);
  }

  async #postData(url, data) {
    const requestBody = JSON.stringify(data);
    const response = await fetch(url, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: requestBody,
    });
    if (!response.ok) throw new Error(`HTTP error ${response.status}`);
    return response.json();
  }
}

(async () => {
  try {
    let sourceText = '';
    process.stdin.setEncoding('utf8');
    for await (const chunk of process.stdin) { sourceText += chunk; }
    const translator = new Translator(...);
    const targetText = await translator.translate(sourceText, ...);
    process.stdout.write(`${targetText}\n`);
  } catch (error) {
    process.stderr.write(`${error}\n`);
    process.exitCode = 1;
  }
})();
<?php

class Translator {
  private $user_name;
  private $api_key;
  private $api_secret;
  private $token_file_path;
  private $token_endpoint;
  private $mt_endpoint;

  public function __construct(
    $user_name,
    $api_key,
    $api_secret,
    $server_name,
    $token_file_path,
  ) {
    $this->user_name = $user_name;
    $this->api_key = $api_key;
    $this->api_secret = $api_secret;
    $this->token_file_path = $token_file_path;
    $this->token_endpoint = "https://$server_name/oauth2/token.php";
    $this->mt_endpoint = "https://$server_name/api/mt";
  }

  public function translate(
    $source_text,
    $engine_id,
    $split,
    $xml
  ) {
    $access_token = $this->get_access_token();
    $result = $this->post_data("{$this->mt_endpoint}/{$engine_id}/", [
      'name' => $this->user_name,
      'key' => $this->api_key,
      'access_token' => $access_token,
      'type' => 'json',
      'text' => $source_text,
      'split' => $split,
      'xml' => $xml,
    ]);
    $result_code = $result->resultset->code;
    if ($result_code !== 0)
      throw new RuntimeException("Translation error $result_code");
    $target_text = $result->resultset->result->text;
    return $target_text;
  }

  private function get_access_token() {
    $access_token = $this->load_access_token();
    if (!is_null($access_token)) return $access_token;
    $token = $this->post_data($this->token_endpoint, [
      'grant_type' => 'client_credentials',
      'client_id' => $this->api_key,
      'client_secret' => $this->api_secret,
    ]);
    $access_token = $token->access_token;
    $expires_in = $token->expires_in;
    $this->save_token($access_token, $expires_in);
    return $access_token;
  }

  private function load_access_token() {
    if (!is_file($this->token_file_path)) return null;
    $token_json = file_get_contents($this->token_file_path);
    $token = json_decode($token_json);
    $access_token = $token->access_token;
    $expires_at = $token->expires_at;
    return ($expires_at > time()) ? $access_token : null;
  }

  private function save_token($access_token, $expires_in) {
    $token_json = json_encode([
      'access_token' => $access_token,
      'expires_at' => 0.9 * $expires_in + time(),
    ]);
    file_put_contents($this->token_file_path, $token_json);
  }

  private function post_data($url, $data) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response_body = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status_code >= 400)
      throw new RuntimeException("HTTP error $status_code");
    return json_decode($response_body);
  }
}

try {
  $source_text = file_get_contents('php://stdin');
  $translator = new Translator(...);
  $target_text = $translator->translate($source_text, ...);
  file_put_contents('php://stdout', "$target_text\n");
} catch (Throwable $error) {
  file_put_contents('php://stderr', "$error\n");
  exit(1);
}