API 文档 V2

姓名、电子邮箱地址和用户名的批量预测

在一个批量请求中发送最多 50 个 GenderAPI.io V2 预测。了解每个条目的选项、保留的 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 接受一个 items 数组:使用 API 密钥访问时包含 1–50 个条目,使用 IP 试用时最多 10 个。您可以只发送姓名、只发送电子邮箱地址、只发送用户名,也可以三者混合。每个条目都有各自的 country、forceToGenderize 和 options。ID 可选,但必须唯一。

结果保持输入顺序,并包含 index、您提供的可选 id、charged_credits,以及 data 或 error 二者之一。HTTP 200 中可能包含单个条目的失败,因此请逐条检查。meta.summary 会给出 total、succeeded、identified、unknown 和 failed。未知预测也是成功完成、需要计费的条目。

如果请求验证或执行计划失败,整个批量请求会在扣费前被拒绝。如果所有已执行的条目都失败,API 会返回非 2xx 的 Problem 响应,其中包含 data 数组和旧版别名 results。失败的条目在退款确认后费用为零。如果计费尚未确认,请不要假定各条目的扣费已是最终结果。

选择编程语言。设置您的 API 密钥,然后在您的服务器上运行示例。

每个预测请求(包括重试)都是一次新的计费操作。这些示例不会自动重试。发送下一个请求之前,请先检查计费状态。

运行之前:访问与错误处理

请在您的服务器上运行这些示例。在进程环境中将 GENDERAPI_API_KEY 设置为您现有的 API 密钥。请确认 meta.access.mode 为 api_key:无法识别的密钥可能会转为使用 IP 试用。

对于 HTTP 4xx 和 5xx JSON 响应,示例会保留错误响应体并以非零状态退出。重试前请检查 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": "Xiuying",
      "country": "CN"
    },
    {
      "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
    }
  ]
}'

cURL 7.76+,在 POSIX shell 中运行。在终端中运行。运行环境文档

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": "Xiuying",
      "country": "CN"
    },
    {
      "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\":\"Xiuying\",\"country\":\"CN\"},{\"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":"Xiuying","country":"CN"},{"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\":\"Xiuying\",\"country\":\"CN\"},{\"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\":\"Xiuying\",\"country\":\"CN\"},{\"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\":\"Xiuying\",\"country\":\"CN\"},{\"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日获取的两个真实结果(一个数据集匹配和一个未知结果)与一个用于说明的服务提供方故障组合在一起。它展示的是部分成功的 HTTP 200 响应,而不是上面批量请求的预期输出。两个成功的条目各消耗 1 个积分;失败条目的费用已确认为零。

说明性 JSON 响应
{
  "data": [
    {
      "index": 0,
      "id": "known",
      "charged_credits": 1,
      "data": {
        "input": {
          "type": "name",
          "value": "Xiuying",
          "country": "CN"
        },
        "name": "xiuying",
        "gender": "female",
        "country": "TH",
        "confidence": 1,
        "confidence_kind": "observed_frequency",
        "sample_count": 4,
        "source": "dataset",
        "result_status": "identified",
        "reason": null,
        "country_source": "dataset",
        "match": {
          "name": "xiuying",
          "method": "normalized",
          "scope": "global",
          "country": null
        }
      }
    },
    {
      "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 数组中的位置,从零开始。
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 尝试的唯一标识符,也会通过 X-Request-ID 返回。
meta.duration_msinteger否42请求处理时间(毫秒)。
meta.access.modestring否"api_key"api_key、ip_trial 或 unauthenticated。使用付费账户时,请确认值为 api_key。
meta.access.reasonstring是null转为试用的原因:api_key_missing、api_key_invalid 或 api_key_not_found;其他情况为 null。
meta.usage.charged_creditsinteger是1净扣除的积分。扣费前或全额退款确认后为零;计费未确认时为 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。

规划批量请求的积分与重试

使用您现有的 Bearer API 密钥进行身份验证,并发送 Content-Type: application/json。每次提交的批量请求都是一次新操作。重试部分失败时,请先检查计费,再只提交失败的条目;重新发送成功的条目会再次扣费。

批量请求中的条目默认关闭 AI(off),每个成功的条目消耗 1 个积分。显式设置 fallback 时,包含 AI 在内总共也是 1 个积分。always 消耗 2 个积分。forceToGenderize 在数据集得出结果时消耗 1 个积分,使用 AI 时消耗 2 个积分。成功完成的未知结果同样计费。起始余额只要有 1 个正积分即可开始批量请求;最终扣费后余额可能为负数。

处理联系人列表,确保每一行都有着落

批量端点可以处理只含姓名的列表、只含电子邮箱地址的列表以及混合输入。使用 API 密钥时,请把任务拆分为每批最多 50 个条目;IP 试用每个请求最多允许 10 个。请自行记录任务进度,并为每个条目分配在该批量请求中唯一的 id。返回的 index 是在所提交的这一批中从零开始的位置,而不是在整个联系人列表中的位置。

步骤需要保存或检查的内容为什么重要
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。不要盲目地重新发送整批;请先遵循错误和计费相关指引。

为每个联系人选择推断模式

这个可运行的请求使用了三种不同的策略:全名仅使用数据集,电子邮箱地址使用普通的 AI 回退,用户名使用可识别昵称的回退。这些只是示例输入,并不承诺三个联系人都会得到性别。请在代码上方选择编程语言,并在运行前设置 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 响应,示例会保留错误响应体并以非零状态退出。重试前请检查 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
    }
  ]
}'

cURL 7.76+,在 POSIX shell 中运行。在终端中运行。运行环境文档

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。运行环境文档