APIドキュメント V2

名前・メールアドレス・ユーザー名のバッチ推定

GenderAPI.io V2で最大50件の推定を1回のバッチリクエストで送信します。項目ごとのオプション、IDの保持、部分的な失敗、レスポンスの集計、クレジットの計算を説明します。

名前・メールアドレス・ユーザー名のバッチ処理

パラメーター型必須デフォルト説明
itemsarray<object>はい—1–50件の推定項目。IPトライアルでは最大10件。結果は入力の順序を保ちます。
items[].typestringはい—入力の種類:name、email、username。
items[].valuestringはい—必須。1–254文字。空白のみは不可で、制御文字は使用できません。emailの値はメールアドレスとして有効な構文である必要があります。
items[].countrystringいいえ—任意。大文字のISO 3166-1 alpha-2コード(例:TR、US)。国別の検索はグローバルデータセットにフォールバックすることがあります。
items[].forceToGenderizebooleanいいえfalseまずデータセットを確認し、推定できない場合はニックネームを解釈するAIを使用します。name、email、usernameで使用できます。
items[].optionsobjectいいえ—入力ごとのAIオプションを格納するオブジェクト。
items[].options.ai_modestringいいえoff使用できる値:off、fallback、always。forceToGenderize: trueの場合は、このフィールドを省略するかfallbackを使用してください。
items[].idstringいいえ—POSTのJSONで指定できる1–64文字の任意の識別子。バッチの各結果とともに返され、バッチ内で一意である必要があります。単一の推定でも受け付けますが、レスポンスには含まれません。GETクエリでは使用できません。

POST /gender/batchは、APIキーでのアクセスでは1–50項目、IPトライアルでは最大10項目のitems配列を受け付けます。名前だけ、メールアドレスだけ、ユーザー名だけを送ることも、3種類を混在させることもできます。各項目にはそれぞれcountry、forceToGenderize、optionsを指定できます。IDは任意ですが、一意である必要があります。

結果は入力の順序を保ち、index、指定した場合はid、charged_credits、そしてdataまたはerrorのどちらか一方を含みます。HTTP 200でも項目単位の失敗が含まれることがあるため、すべての項目を確認してください。meta.summaryにはtotal、succeeded、identified、unknown、failedが含まれます。不明な推定も成功した項目であり、課金対象です。

リクエストの検証や実行計画に失敗した場合、バッチは差し引きの前に拒否されます。実行したすべての項目が失敗した場合、APIは2xx以外のProblemレスポンスを返し、data配列と旧形式のエイリアスresultsを含めます。失敗した項目は、払い戻しが確認されると0クレジットになります。課金が未確定の場合は、項目ごとの課金額を確定したものとみなさないでください。

プログラミング言語を選んでください。APIキーを設定する。次に、サーバー上で例を実行してください。

推定のリクエストは、再試行を含め、毎回新たに課金される処理です。これらの例は自動的に再試行しません。次のリクエストを送信する前に課金ステータスを確認してください。

実行する前に:アクセスとエラー処理

これらの例はサーバー上で実行してください。プロセスの環境変数GENDERAPI_API_KEYに既存のAPIキーを設定し、meta.access.modeがapi_keyであることを確認します。認識されないキーはIPトライアルに切り替わることがあります。

HTTP 4xxと5xxのJSONレスポンスでは、例はエラーのボディをそのまま残し、0以外の終了ステータスで終了します。再試行する前にcode、action、meta.usage.billing_statusを確認してください。HTTP 200のバッチレスポンスでは、各項目のdataまたはerrorも確認してください。

エラーと再試行のガイド →
cURL
curl --silent --show-error --fail-with-body --max-time 30 \
  --request POST 'https://api.genderapi.io/api/v2/gender/batch' \
  --header "Authorization: Bearer ${GENDERAPI_API_KEY:?Set GENDERAPI_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{
  "items": [
    {
      "id": "contact-1",
      "type": "name",
      "value": "Kenji",
      "country": "JP"
    },
    {
      "id": "contact-2",
      "type": "email",
      "value": "alice.smith@example.com",
      "options": {
        "ai_mode": "fallback"
      }
    },
    {
      "id": "contact-3",
      "type": "username",
      "value": "prenses",
      "country": "TR",
      "forceToGenderize": true
    }
  ]
}'

POSIXシェルでcURL 7.76以上。ターミナルで実行します。実行環境のドキュメント

JavaScript / Node.js
// Server-side Node.js. Save as example.mjs.
const apiKey = process.env.GENDERAPI_API_KEY;
if (!apiKey) throw new Error("Set GENDERAPI_API_KEY");
const body = {
  "items": [
    {
      "id": "contact-1",
      "type": "name",
      "value": "Kenji",
      "country": "JP"
    },
    {
      "id": "contact-2",
      "type": "email",
      "value": "alice.smith@example.com",
      "options": {
        "ai_mode": "fallback"
      }
    },
    {
      "id": "contact-3",
      "type": "username",
      "value": "prenses",
      "country": "TR",
      "forceToGenderize": true
    }
  ]
};

const response = await fetch("https://api.genderapi.io/api/v2/gender/batch", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30_000),
  redirect: "error",
});
const raw = await response.text();
if (!(response.headers.get("content-type") ?? "").includes("json")) {
  throw new Error(`HTTP ${response.status}: expected JSON; request ID ${response.headers.get("x-request-id")}`);
}
const result = JSON.parse(raw); // Also accepts application/problem+json.
if (!response.ok) {
  console.error(`HTTP ${response.status}`, result);
  process.exitCode = 1; // A retry is a new operation; inspect billing first.
} else {
  console.log(JSON.stringify(result, null, 2));
  // For batches, inspect every item: HTTP 200 may contain item errors.
}

Node.js 22以上、組み込みのfetch。example.mjsとして保存し、node example.mjsを実行します。実行環境のドキュメント

Python
import json
import os
import sys
import urllib.error
import urllib.request

api_key = os.environ.get("GENDERAPI_API_KEY")
if not api_key:
    raise RuntimeError("Set GENDERAPI_API_KEY")
body = json.loads("{\"items\":[{\"id\":\"contact-1\",\"type\":\"name\",\"value\":\"Kenji\",\"country\":\"JP\"},{\"id\":\"contact-2\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-3\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}")

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

request = urllib.request.Request(
    "https://api.genderapi.io/api/v2/gender/batch",
    method="POST",
    data=json.dumps(body).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + api_key,
        "Content-Type": "application/json",
    },
)
opener = urllib.request.build_opener(NoRedirect())
try:
    response = opener.open(request, timeout=30)
except urllib.error.HTTPError as error:
    response = error  # Keep the Problem Details body on non-2xx responses.
with response:
    status = response.status
    raw = response.read().decode("utf-8")
    if "json" not in response.headers.get("Content-Type", ""):
        raise RuntimeError(f"HTTP {status}: expected a JSON response")
    result = json.loads(raw)
print(json.dumps(result, indent=2), file=sys.stderr if status >= 300 else sys.stdout)
if not 200 <= status < 300:
    sys.exit(1)  # Inspect code, action and billing before retrying.
# For batches, inspect every item even when HTTP status is 200.

Python 3.10以上、標準ライブラリ。example.pyとして保存し、python3 example.pyを実行します。実行環境のドキュメント

PHP
<?php
$apiKey = getenv('GENDERAPI_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set GENDERAPI_API_KEY');
}
$body = json_decode('{"items":[{"id":"contact-1","type":"name","value":"Kenji","country":"JP"},{"id":"contact-2","type":"email","value":"alice.smith@example.com","options":{"ai_mode":"fallback"}},{"id":"contact-3","type":"username","value":"prenses","country":"TR","forceToGenderize":true}]}', true, 512, JSON_THROW_ON_ERROR);

$ch = curl_init('https://api.genderapi.io/api/v2/gender/batch');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
]);
$raw = curl_exec($ch);
if ($raw === false) {
    throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($ch);
if (strpos($contentType, 'json') === false) {
    throw new RuntimeException("HTTP $status: expected a JSON response");
}
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$output = json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR) . PHP_EOL;
if ($status < 200 || $status >= 300) {
    fwrite(STDERR, $output); // Preserve the Problem Details body.
    exit(1);
}
echo $output;
// For batches, inspect every item; HTTP 200 can contain item errors.

PHP 8以上とcURL拡張機能。example.phpとして保存し、php example.phpを実行します。実行環境のドキュメント

Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class GenderApiExample {
    private static String requiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) throw new IllegalStateException("Set " + name);
        return value;
    }

    public static void main(String[] args) throws Exception {
        String apiKey = requiredEnv("GENDERAPI_API_KEY");
        String body = "{\"items\":[{\"id\":\"contact-1\",\"type\":\"name\",\"value\":\"Kenji\",\"country\":\"JP\"},{\"id\":\"contact-2\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-3\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}";
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .followRedirects(HttpClient.Redirect.NEVER)
            .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.genderapi.io/api/v2/gender/batch"))
            .timeout(Duration.ofSeconds(30))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
            .build();
        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        if (!response.headers().firstValue("content-type").orElse("").contains("json")) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": expected JSON");
        }
        // JSON text; parse with your application's JSON library when integrating.
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            System.err.println(response.body()); // Includes Problem Details.
            System.exit(1);
        }
        System.out.println(response.body());
        // For batches, inspect each item's data or error, including on HTTP 200.
    }
}

Java 17以上、標準のHTTPクライアント。GenderApiExample.javaとして保存し、java GenderApiExample.javaを実行します。実行環境のドキュメント

C# / .NET
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

string RequiredEnv(string name) =>
    !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(name))
        ? Environment.GetEnvironmentVariable(name)!
        : throw new InvalidOperationException($"Set {name}");

var apiKey = RequiredEnv("GENDERAPI_API_KEY");
using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.genderapi.io/api/v2/gender/batch");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"items\":[{\"id\":\"contact-1\",\"type\":\"name\",\"value\":\"Kenji\",\"country\":\"JP\"},{\"id\":\"contact-2\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-3\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}", Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
var raw = await response.Content.ReadAsStringAsync();
if (!(response.Content.Headers.ContentType?.MediaType?.Contains("json") ?? false))
    throw new InvalidOperationException($"HTTP {(int)response.StatusCode}: expected JSON");
using var result = JsonDocument.Parse(raw);
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(result.RootElement); // Preserve Problem Details.
    Environment.ExitCode = 1;
}
else
{
    Console.WriteLine(result.RootElement);
    // For batches, inspect every item even on HTTP 200.
}

.NET 8以上のコンソールアプリケーション。コンソールプロジェクトのProgram.csとして使用し、dotnet runを実行します。実行環境のドキュメント

Go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strings"
    "time"
)

func requiredEnv(name string) string {
    value := os.Getenv(name)
    if value == "" { panic("Set " + name) }
    return value
}

func run() error {
    apiKey := requiredEnv("GENDERAPI_API_KEY")
    body := "{\"items\":[{\"id\":\"contact-1\",\"type\":\"name\",\"value\":\"Kenji\",\"country\":\"JP\"},{\"id\":\"contact-2\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-3\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}"
    request, err := http.NewRequest("POST", "https://api.genderapi.io/api/v2/gender/batch", strings.NewReader(body))
    if err != nil { return err }
    request.Header.Set("Authorization", "Bearer " + apiKey)
    request.Header.Set("Content-Type", "application/json")
    client := &http.Client{
        Timeout: 30 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    response, err := client.Do(request)
    if err != nil { return err }
    defer response.Body.Close()
    raw, err := io.ReadAll(response.Body)
    if err != nil { return err }
    if !strings.Contains(response.Header.Get("Content-Type"), "json") || !json.Valid(raw) {
        return fmt.Errorf("HTTP %d: expected a JSON response", response.StatusCode)
    }
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return fmt.Errorf("HTTP %d: %s", response.StatusCode, raw)
    }
    fmt.Println(string(raw))
    // For batches, inspect every item even on HTTP 200.
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err) // Keep Problem Details for error handling.
        os.Exit(1)
    }
}

Go 1.22以上、標準ライブラリ。main.goとして保存し、go run main.goを実行します。実行環境のドキュメント

バッチレスポンスを読む

この例は、2026年10月1日に取得した2件の実際の結果(データセットでの一致と不明な結果)に、説明用のプロバイダー障害を組み合わせたものです。部分的に成功したHTTP 200レスポンスを示すもので、上のバッチリクエストで期待される出力ではありません。成功した2項目はそれぞれ1クレジットで、失敗した項目は0クレジットであることが確認されています。

説明用のJSONレスポンス
{
  "data": [
    {
      "index": 0,
      "id": "known",
      "charged_credits": 1,
      "data": {
        "input": {
          "type": "name",
          "value": "Kenji",
          "country": "JP"
        },
        "name": "kenji",
        "gender": "male",
        "country": "JP",
        "confidence": 0.9943127962085309,
        "confidence_kind": "observed_frequency",
        "sample_count": 1055,
        "source": "dataset",
        "result_status": "identified",
        "reason": null,
        "country_source": "dataset",
        "match": {
          "name": "kenji",
          "method": "normalized",
          "scope": "country",
          "country": "JP"
        }
      }
    },
    {
      "index": 1,
      "id": "missing",
      "charged_credits": 1,
      "data": {
        "input": {
          "type": "name",
          "value": "zzzxxyy",
          "country": null
        },
        "name": null,
        "gender": null,
        "country": null,
        "confidence": null,
        "confidence_kind": null,
        "sample_count": null,
        "source": "none",
        "result_status": "unknown",
        "reason": "not_found",
        "country_source": null,
        "match": {
          "name": null,
          "method": null,
          "scope": null,
          "country": null
        }
      }
    },
    {
      "index": 2,
      "id": "failed",
      "charged_credits": 0,
      "error": {
        "type": "urn:genderapi:problem:ai_upstream_error",
        "title": "ai upstream error",
        "status": 502,
        "detail": "The AI provider could not complete the request.",
        "instance": "urn:uuid:11111111-1111-4111-8111-111111111111",
        "code": "ai_upstream_error",
        "request_id": "11111111-1111-4111-8111-111111111111",
        "documentation": "https://api.genderapi.io/api/v2/errors",
        "action": "inspect_billing_before_retry"
      }
    }
  ],
  "meta": {
    "request_id": "11111111-1111-4111-8111-111111111111",
    "duration_ms": 12,
    "access": {
      "mode": "ip_trial",
      "reason": "api_key_missing"
    },
    "usage": {
      "charged_credits": 2,
      "remaining_credits": 6,
      "billing_status": "confirmed",
      "resets_at": "2026-09-26T12:00:00.000Z",
      "limit": 10,
      "period_seconds": 86400
    },
    "summary": {
      "total": 3,
      "succeeded": 2,
      "identified": 1,
      "unknown": 1,
      "failed": 1
    }
  }
}

バッチの結果フィールド

フィールド型nullの場合あり例説明
dataarray<object>いいえ[…]順序どおりの結果。各項目には推定結果またはエラーが含まれます。すべての項目を確認してください。
data[].indexintegerいいえ0送信したitems配列内の位置(0始まり)。
data[].idstringいいえ"contact-1"入力の識別子。指定した場合にのみ含まれます。
data[].charged_creditsintegerいいえ1確認済みの払い戻しを差し引いた、項目ごとの正味の課金額。全体の課金が未確定の場合は確定値とみなさないでください。
data[].dataobjectいいえ{…}不明な結果を含め、成功した項目に含まれます。レスポンスのガイドで説明している推定のフィールドを使用します。
data[].errorobjectいいえ{…}失敗した項目で、dataの代わりに含まれます。エラーのガイドで説明しているProblem Detailsのフィールドを使用します。

バッチの集計フィールド

フィールド型nullの場合あり例説明
meta.summary.totalintegerいいえ3バッチ内の項目の総数。
meta.summary.succeededintegerいいえ2不明な推定を含む、成功した項目の数。
meta.summary.identifiedintegerいいえ1性別がnullでない、成功した項目の数。
meta.summary.unknownintegerいいえ1性別がnullの、成功した項目の数。これらも課金対象の結果です。
meta.summary.failedintegerいいえ1失敗した項目の数。total = succeeded + failed、succeeded = identified + unknown。

アクセス、課金、リクエストのメタデータ

フィールド型nullの場合あり例説明
meta.request_idstringいいえ"550e8400-e29b-41d4-a716-446655440000"このHTTPの試行を一意に識別するID。X-Request-IDでも返されます。
meta.duration_msintegerいいえ42リクエストの処理時間(ミリ秒)。
meta.access.modestringいいえ"api_key"api_key、ip_trial、unauthenticatedのいずれか。有料アカウントを使う場合はapi_keyであることを確認してください。
meta.access.reasonstringはいnullIPトライアルに切り替わった理由:api_key_missing、api_key_invalid、api_key_not_found。それ以外はnull。
meta.usage.charged_creditsintegerはい1差し引かれた正味のクレジット。課金前、または全額の払い戻しが確認された後は0。課金が未確定の場合はnull。
meta.usage.remaining_creditsintegerはい99処理完了時の残高。マイナスになることがあります。取得できない場合や課金が未確定の場合はnull。
meta.usage.billing_statusstringいいえ"confirmed"not_charged、confirmed、unconfirmedのいずれか。失敗した推定を再試行する前に確認してください。
meta.usage.resets_atstringはい"2026-09-27T12:00:00.000Z"IPトライアルのリセット時刻(UTC、ISO 8601)。APIキーのアカウントや不明な場合はnull。
meta.usage.limitintegerはい10IPトライアルのクレジット上限。APIキーのアカウントではnull。
meta.usage.period_secondsintegerはい86400IPトライアルの期間(秒)。APIキーのアカウントではnull。

バッチのクレジットと再試行を計画する

既存のAPIキーをBearer認証で送信し、Content-Type: application/jsonを付けてください。送信するバッチは毎回新しい処理です。部分的な失敗を再試行する場合は、課金を確認してから失敗した項目だけを送信してください。成功した項目を再送すると、再び課金されます。

バッチの項目はデフォルトでAIがoffで、成功した項目ごとに1クレジットです。fallbackを明示した場合も、AIを含めて合計1クレジットです。alwaysは2クレジットです。forceToGenderizeは、データセットで推定できた場合は1クレジット、AIを使った場合は2クレジットです。成功した不明な結果も課金されます。バッチを開始するには残高が1クレジット以上あれば十分で、最終的な課金により残高がマイナスになることがあります。

連絡先リストを処理し、すべての行の結果を把握する

バッチのエンドポイントでは、名前だけのリスト、メールアドレスだけのリスト、入力が混在したリストを処理できます。APIキーを使うジョブは1回あたり最大50項目に分割してください。IPトライアルでは1リクエストあたり最大10項目です。ジョブの進捗は自分で記録し、各項目にはそのバッチ内で一意のidを付けてください。返されるindexは、送信したそのバッチ内での0始まりの位置であり、連絡先リスト全体での位置ではありません。

手順保存・確認する内容重要な理由
1. バッチを準備する元の行と項目のidを保持し、項目ごとにcountryとAIオプションを設定します。名前が連絡先全体で一意であることを前提にしないでください。
2. レスポンス全体を読むmeta.request_idを保存し、idまたはindexでdata[]の各要素を対応付けます。HTTP 200でも、成功した推定と項目ごとのエラーが両方含まれることがあります。
3. 成功した結果を保存するidentifiedとunknownの推定を、JSONのnullや根拠のフィールドも含めて保持します。不明な結果は完了した課金対象の結果であり、自動的に再試行すべき失敗した行ではありません。
4. エラーとクレジットを照合する次のリクエストを決める前に、各errorとmeta.usage.billing_statusを確認します。課金が確定したら、再試行に適したエラーの失敗した項目だけを再試行します。成功した項目は再び課金されます。
5. 不確かな再試行を保留する課金が未確定の場合や、ネットワーク障害で結果が分からない場合は、リクエストIDを保持します。バッチ全体をむやみに再送せず、まずエラーと課金のガイドに従ってください。

連絡先ごとに推定モードを選ぶ

この実行可能なリクエストでは3つの異なる方針を使っています。フルネームにはデータセットのみ、メールアドレスには通常のAIフォールバック、ユーザー名にはニックネームを解釈するフォールバックです。これは入力の例であり、3件すべてで性別が返ることを約束するものではありません。コードの上でプログラミング言語を選び、実行前にGENDERAPI_API_KEYを設定してください。

forceToGenderizeを使わない場合、バッチの項目は単一の検索とは異なり、デフォルトでAIがoffです。通常のAIフォールバックを使うにはfallbackを明示してください。offと通常のフォールバックは、どちらも成功した項目ごとに1クレジットです。alwaysはデータセットを使わず、2クレジットです。forceToGenderizeは、データセットで推定できた場合は1クレジット、AIを使った場合は合計2クレジットです。成功した不明な結果も課金されます。forceToGenderizeをoffまたはalwaysと組み合わせないでください。

プログラミング言語を選んでください。APIキーを設定する。次に、サーバー上で例を実行してください。

推定のリクエストは、再試行を含め、毎回新たに課金される処理です。これらの例は自動的に再試行しません。次のリクエストを送信する前に課金ステータスを確認してください。

実行する前に:アクセスとエラー処理

これらの例はサーバー上で実行してください。プロセスの環境変数GENDERAPI_API_KEYに既存のAPIキーを設定し、meta.access.modeがapi_keyであることを確認します。認識されないキーはIPトライアルに切り替わることがあります。

HTTP 4xxと5xxのJSONレスポンスでは、例はエラーのボディをそのまま残し、0以外の終了ステータスで終了します。再試行する前にcode、action、meta.usage.billing_statusを確認してください。HTTP 200のバッチレスポンスでは、各項目のdataまたはerrorも確認してください。

エラーと再試行のガイド →
cURL
curl --silent --show-error --fail-with-body --max-time 30 \
  --request POST 'https://api.genderapi.io/api/v2/gender/batch' \
  --header "Authorization: Bearer ${GENDERAPI_API_KEY:?Set GENDERAPI_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{
  "items": [
    {
      "id": "contact-001",
      "type": "name",
      "value": "Ayşe Yılmaz",
      "country": "TR",
      "options": {
        "ai_mode": "off"
      }
    },
    {
      "id": "contact-002",
      "type": "email",
      "value": "alice.smith@example.com",
      "options": {
        "ai_mode": "fallback"
      }
    },
    {
      "id": "contact-003",
      "type": "username",
      "value": "prenses",
      "country": "TR",
      "forceToGenderize": true
    }
  ]
}'

POSIXシェルでcURL 7.76以上。ターミナルで実行します。実行環境のドキュメント

JavaScript / Node.js
// Server-side Node.js. Save as example.mjs.
const apiKey = process.env.GENDERAPI_API_KEY;
if (!apiKey) throw new Error("Set GENDERAPI_API_KEY");
const body = {
  "items": [
    {
      "id": "contact-001",
      "type": "name",
      "value": "Ayşe Yılmaz",
      "country": "TR",
      "options": {
        "ai_mode": "off"
      }
    },
    {
      "id": "contact-002",
      "type": "email",
      "value": "alice.smith@example.com",
      "options": {
        "ai_mode": "fallback"
      }
    },
    {
      "id": "contact-003",
      "type": "username",
      "value": "prenses",
      "country": "TR",
      "forceToGenderize": true
    }
  ]
};

const response = await fetch("https://api.genderapi.io/api/v2/gender/batch", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30_000),
  redirect: "error",
});
const raw = await response.text();
if (!(response.headers.get("content-type") ?? "").includes("json")) {
  throw new Error(`HTTP ${response.status}: expected JSON; request ID ${response.headers.get("x-request-id")}`);
}
const result = JSON.parse(raw); // Also accepts application/problem+json.
if (!response.ok) {
  console.error(`HTTP ${response.status}`, result);
  process.exitCode = 1; // A retry is a new operation; inspect billing first.
} else {
  console.log(JSON.stringify(result, null, 2));
  // For batches, inspect every item: HTTP 200 may contain item errors.
}

Node.js 22以上、組み込みのfetch。example.mjsとして保存し、node example.mjsを実行します。実行環境のドキュメント

Python
import json
import os
import sys
import urllib.error
import urllib.request

api_key = os.environ.get("GENDERAPI_API_KEY")
if not api_key:
    raise RuntimeError("Set GENDERAPI_API_KEY")
body = json.loads("{\"items\":[{\"id\":\"contact-001\",\"type\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"contact-002\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}")

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

request = urllib.request.Request(
    "https://api.genderapi.io/api/v2/gender/batch",
    method="POST",
    data=json.dumps(body).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + api_key,
        "Content-Type": "application/json",
    },
)
opener = urllib.request.build_opener(NoRedirect())
try:
    response = opener.open(request, timeout=30)
except urllib.error.HTTPError as error:
    response = error  # Keep the Problem Details body on non-2xx responses.
with response:
    status = response.status
    raw = response.read().decode("utf-8")
    if "json" not in response.headers.get("Content-Type", ""):
        raise RuntimeError(f"HTTP {status}: expected a JSON response")
    result = json.loads(raw)
print(json.dumps(result, indent=2), file=sys.stderr if status >= 300 else sys.stdout)
if not 200 <= status < 300:
    sys.exit(1)  # Inspect code, action and billing before retrying.
# For batches, inspect every item even when HTTP status is 200.

Python 3.10以上、標準ライブラリ。example.pyとして保存し、python3 example.pyを実行します。実行環境のドキュメント

PHP
<?php
$apiKey = getenv('GENDERAPI_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set GENDERAPI_API_KEY');
}
$body = json_decode('{"items":[{"id":"contact-001","type":"name","value":"Ayşe Yılmaz","country":"TR","options":{"ai_mode":"off"}},{"id":"contact-002","type":"email","value":"alice.smith@example.com","options":{"ai_mode":"fallback"}},{"id":"contact-003","type":"username","value":"prenses","country":"TR","forceToGenderize":true}]}', true, 512, JSON_THROW_ON_ERROR);

$ch = curl_init('https://api.genderapi.io/api/v2/gender/batch');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
]);
$raw = curl_exec($ch);
if ($raw === false) {
    throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($ch);
if (strpos($contentType, 'json') === false) {
    throw new RuntimeException("HTTP $status: expected a JSON response");
}
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$output = json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR) . PHP_EOL;
if ($status < 200 || $status >= 300) {
    fwrite(STDERR, $output); // Preserve the Problem Details body.
    exit(1);
}
echo $output;
// For batches, inspect every item; HTTP 200 can contain item errors.

PHP 8以上とcURL拡張機能。example.phpとして保存し、php example.phpを実行します。実行環境のドキュメント

Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class GenderApiExample {
    private static String requiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) throw new IllegalStateException("Set " + name);
        return value;
    }

    public static void main(String[] args) throws Exception {
        String apiKey = requiredEnv("GENDERAPI_API_KEY");
        String body = "{\"items\":[{\"id\":\"contact-001\",\"type\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"contact-002\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}";
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .followRedirects(HttpClient.Redirect.NEVER)
            .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.genderapi.io/api/v2/gender/batch"))
            .timeout(Duration.ofSeconds(30))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
            .build();
        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        if (!response.headers().firstValue("content-type").orElse("").contains("json")) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": expected JSON");
        }
        // JSON text; parse with your application's JSON library when integrating.
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            System.err.println(response.body()); // Includes Problem Details.
            System.exit(1);
        }
        System.out.println(response.body());
        // For batches, inspect each item's data or error, including on HTTP 200.
    }
}

Java 17以上、標準のHTTPクライアント。GenderApiExample.javaとして保存し、java GenderApiExample.javaを実行します。実行環境のドキュメント

C# / .NET
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

string RequiredEnv(string name) =>
    !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(name))
        ? Environment.GetEnvironmentVariable(name)!
        : throw new InvalidOperationException($"Set {name}");

var apiKey = RequiredEnv("GENDERAPI_API_KEY");
using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.genderapi.io/api/v2/gender/batch");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"items\":[{\"id\":\"contact-001\",\"type\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"contact-002\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}", Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
var raw = await response.Content.ReadAsStringAsync();
if (!(response.Content.Headers.ContentType?.MediaType?.Contains("json") ?? false))
    throw new InvalidOperationException($"HTTP {(int)response.StatusCode}: expected JSON");
using var result = JsonDocument.Parse(raw);
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(result.RootElement); // Preserve Problem Details.
    Environment.ExitCode = 1;
}
else
{
    Console.WriteLine(result.RootElement);
    // For batches, inspect every item even on HTTP 200.
}

.NET 8以上のコンソールアプリケーション。コンソールプロジェクトのProgram.csとして使用し、dotnet runを実行します。実行環境のドキュメント

Go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strings"
    "time"
)

func requiredEnv(name string) string {
    value := os.Getenv(name)
    if value == "" { panic("Set " + name) }
    return value
}

func run() error {
    apiKey := requiredEnv("GENDERAPI_API_KEY")
    body := "{\"items\":[{\"id\":\"contact-001\",\"type\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"contact-002\",\"type\":\"email\",\"value\":\"alice.smith@example.com\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"contact-003\",\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}]}"
    request, err := http.NewRequest("POST", "https://api.genderapi.io/api/v2/gender/batch", strings.NewReader(body))
    if err != nil { return err }
    request.Header.Set("Authorization", "Bearer " + apiKey)
    request.Header.Set("Content-Type", "application/json")
    client := &http.Client{
        Timeout: 30 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    response, err := client.Do(request)
    if err != nil { return err }
    defer response.Body.Close()
    raw, err := io.ReadAll(response.Body)
    if err != nil { return err }
    if !strings.Contains(response.Header.Get("Content-Type"), "json") || !json.Valid(raw) {
        return fmt.Errorf("HTTP %d: expected a JSON response", response.StatusCode)
    }
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return fmt.Errorf("HTTP %d: %s", response.StatusCode, raw)
    }
    fmt.Println(string(raw))
    // For batches, inspect every item even on HTTP 200.
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err) // Keep Problem Details for error handling.
        os.Exit(1)
    }
}

Go 1.22以上、標準ライブラリ。main.goとして保存し、go run main.goを実行します。実行環境のドキュメント