เอกสาร API V2

คาดการณ์แบบกลุ่มจากชื่อ อีเมล และชื่อผู้ใช้

ส่งคำขอคาดการณ์ของ GenderAPI.io V2 ได้สูงสุด 50 รายการในคำขอแบบกลุ่มเดียว เรียนรู้ตัวเลือกของแต่ละรายการ id ที่ส่งคืนตามเดิม ความล้มเหลวบางส่วน สรุปผลในการตอบกลับ และการคิดเครดิต

ชื่อ อีเมล และชื่อผู้ใช้ในคำขอแบบกลุ่ม

พารามิเตอร์ชนิดข้อมูลจำเป็นค่าเริ่มต้นคำอธิบาย
itemsarray<object>ใช่—รายการคาดการณ์ 1–50 รายการ หรือสูงสุด 10 รายการสำหรับการทดลองใช้ตาม IP ผลลัพธ์คงลำดับตามข้อมูลนำเข้า
items[].typestringใช่—ประเภทข้อมูลนำเข้า: name, email หรือ username
items[].valuestringใช่—จำเป็น ความยาว 1–254 อักขระ ต้องไม่ว่างและไม่มีอักขระควบคุม ค่าอีเมลต้องมีรูปแบบอีเมลที่ถูกต้อง
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ไม่—ตัวระบุใน JSON ของ POST ความยาว 1–64 อักขระ ไม่บังคับ ส่งคืนคู่กับผลลัพธ์แต่ละรายการของคำขอแบบกลุ่ม และต้องไม่ซ้ำกันภายในคำขอแบบกลุ่มเดียวกัน คำขอเดี่ยวรับค่านี้ได้แต่ไม่ส่งคืน ไม่รองรับในคิวรีของ GET

POST /gender/batch รับอาร์เรย์ items ที่มี 1–50 รายการเมื่อใช้คีย์ API หรือสูงสุด 10 รายการเมื่อใช้การทดลองใช้ตาม IP ส่งได้ทั้งชื่ออย่างเดียว อีเมลอย่างเดียว ชื่อผู้ใช้อย่างเดียว หรือผสมทั้งสามประเภท แต่ละรายการมี country, forceToGenderize และ options ของตัวเอง id ไม่บังคับแต่ต้องไม่ซ้ำกัน

ผลลัพธ์คงลำดับตามข้อมูลนำเข้า และมี index, id ที่คุณระบุ (ถ้ามี), charged_credits และมี data หรือ error อย่างใดอย่างหนึ่งเท่านั้น HTTP 200 อาจมีความล้มเหลวระดับรายการ จึงต้องตรวจสอบทุกรายการ meta.summary รายงาน total, succeeded, identified, unknown และ failed การคาดการณ์ที่ไม่ทราบผลถือเป็นรายการที่สำเร็จและถูกหักเครดิต

หากการตรวจสอบคำขอหรือการวางแผนล้มเหลว คำขอแบบกลุ่มทั้งหมดจะถูกปฏิเสธก่อนหักเครดิต หากทุกรายการที่ดำเนินการล้มเหลว API จะส่งคืนการตอบกลับ Problem ที่ไม่ใช่ 2xx พร้อมอาร์เรย์ data และชื่อแทนแบบเดิม results รายการที่ล้มเหลวจะไม่มีค่าใช้จ่ายหลังยืนยันการคืนเครดิต หากการหักเครดิตยังไม่ได้รับการยืนยัน อย่าถือว่าจำนวนเครดิตของแต่ละรายการเป็นยอดสุดท้าย

เลือกภาษาโปรแกรม ตั้งค่าคีย์ API จากนั้นรันตัวอย่างบนเซิร์ฟเวอร์ของคุณ

คำขอคาดการณ์ทุกครั้งเป็นงานใหม่ที่มีการหักเครดิต รวมถึงคำขอที่ส่งซ้ำ ตัวอย่างเหล่านี้ไม่ส่งคำขอซ้ำโดยอัตโนมัติ ตรวจสอบสถานะการหักเครดิตก่อนส่งคำขออีกครั้ง

ก่อนรัน: การเข้าถึงและการจัดการข้อผิดพลาด

รันตัวอย่างเหล่านี้บนเซิร์ฟเวอร์ของคุณ ตั้งค่า GENDERAPI_API_KEY ในสภาพแวดล้อมของโปรเซสเป็นคีย์ API ที่มีอยู่ ตรวจสอบว่า meta.access.mode เป็น api_key เพราะคีย์ที่ระบบไม่รู้จักอาจทำให้ใช้การทดลองใช้ตาม IP แทน

การตอบกลับ JSON ที่มี HTTP 4xx และ 5xx จะคงเนื้อหาข้อผิดพลาดไว้และจบด้วยสถานะการออกที่ไม่ใช่ศูนย์ ตรวจสอบ 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": "Malee",
      "country": "TH"
    },
    {
      "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 รันในเทอร์มินัล เอกสารของรันไทม์

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": "Malee",
      "country": "TH"
    },
    {
      "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\":\"Malee\",\"country\":\"TH\"},{\"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":"Malee","country":"TH"},{"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\":\"Malee\",\"country\":\"TH\"},{\"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\":\"Malee\",\"country\":\"TH\"},{\"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\":\"Malee\",\"country\":\"TH\"},{\"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 เอกสารของรันไทม์

อ่านการตอบกลับของคำขอแบบกลุ่ม

ตัวอย่างนี้รวมผลลัพธ์จริงสองรายการที่บันทึกเมื่อวันที่ 1 ตุลาคม 2026 ได้แก่ รายการที่ตรงกับชุดข้อมูลและผลลัพธ์ที่ไม่ทราบ เข้ากับความล้มเหลวของผู้ให้บริการที่ใช้เพื่อการอธิบาย เพื่อแสดงการตอบกลับ HTTP 200 ที่สำเร็จบางส่วน ไม่ใช่ผลลัพธ์ที่คาดว่าจะได้จากคำขอแบบกลุ่มด้านบน รายการที่สำเร็จสองรายการใช้รายการละ 1 เครดิต ส่วนรายการที่ล้มเหลวได้รับการยืนยันว่าไม่มีการหักเครดิต

ตัวอย่างการตอบกลับ JSON
{
  "data": [
    {
      "index": 0,
      "id": "known",
      "charged_credits": 1,
      "data": {
        "input": {
          "type": "name",
          "value": "Malee",
          "country": "TH"
        },
        "name": "malee",
        "gender": "female",
        "country": "TH",
        "confidence": 0.9176470588235294,
        "confidence_kind": "observed_frequency",
        "sample_count": 85,
        "source": "dataset",
        "result_status": "identified",
        "reason": null,
        "country_source": "dataset",
        "match": {
          "name": "malee",
          "method": "normalized",
          "scope": "country",
          "country": "TH"
        }
      }
    },
    {
      "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) เป็น null สำหรับบัญชีที่ใช้คีย์ API หรือเมื่อไม่ทราบ
meta.usage.limitintegerใช่10จำนวนเครดิตของการทดลองใช้ตาม IP เป็น null สำหรับบัญชีที่ใช้คีย์ API
meta.usage.period_secondsintegerใช่86400รอบเวลาของการทดลองใช้ตาม IP เป็นวินาที เป็น null สำหรับบัญชีที่ใช้คีย์ API

วางแผนเครดิตและการส่งคำขอซ้ำสำหรับคำขอแบบกลุ่ม

ยืนยันตัวตนด้วยคีย์ API แบบ Bearer ที่มีอยู่ และส่ง Content-Type: application/json คำขอแบบกลุ่มทุกครั้งที่ส่งเป็นงานใหม่ หากจะส่งซ้ำหลังความล้มเหลวบางส่วน ให้ตรวจสอบการหักเครดิตก่อน แล้วส่งเฉพาะรายการที่ล้มเหลว เพราะการส่งรายการที่สำเร็จซ้ำจะถูกหักเครดิตอีกครั้ง

รายการในคำขอแบบกลุ่มใช้ off (ไม่ใช้ AI) เป็นค่าเริ่มต้นและใช้ 1 เครดิตต่อรายการที่สำเร็จ การระบุ fallback ก็ใช้รวม 1 เครดิตเช่นกันแม้จะใช้ AI ส่วน always ใช้ 2 เครดิต forceToGenderize ใช้ 1 เครดิตเมื่อชุดข้อมูลระบุเพศได้ หรือรวม 2 เครดิตหากใช้ AI ผลลัพธ์ที่ไม่ทราบซึ่งดำเนินการสำเร็จก็ถูกหักเครดิต ยอดเริ่มต้นที่เป็นบวกเพียง 1 เครดิตก็เริ่มคำขอแบบกลุ่มได้ และการหักครั้งสุดท้ายอาจทำให้ยอดคงเหลือติดลบ

ประมวลผลรายชื่อผู้ติดต่อโดยติดตามผลของทุกแถวได้ครบ

endpoint คำขอแบบกลุ่มรองรับรายการที่มีแต่ชื่อ รายการที่มีแต่อีเมล และข้อมูลนำเข้าแบบผสม แบ่งงานที่ใช้คีย์ API เป็นชุดละไม่เกิน 50 รายการ ส่วนการทดลองใช้ตาม IP รับได้สูงสุด 10 รายการต่อคำขอ เก็บตำแหน่งในงานของคุณเอง และกำหนด id ที่ไม่ซ้ำกันภายในคำขอแบบกลุ่มให้แต่ละรายการ index ที่ส่งคืนนับจากศูนย์ภายในชุดที่ส่งเท่านั้น ไม่ใช่ตำแหน่งในรายชื่อผู้ติดต่อทั้งหมด

ขั้นตอนสิ่งที่ต้องเก็บหรือตรวจสอบเหตุผลที่สำคัญ
1. เตรียมแต่ละชุดเก็บแถวต้นทางและ id ของรายการไว้ และกำหนด country กับตัวเลือก AI แยกตามรายการอย่าพึ่งพาการที่ชื่อไม่ซ้ำกันในรายชื่อผู้ติดต่อ
2. อ่านการตอบกลับทั้งหมดบันทึก meta.request_id และจับคู่แต่ละรายการใน data[] ด้วย id หรือ indexHTTP 200 อาจมีทั้งการคาดการณ์ที่สำเร็จและข้อผิดพลาดของรายการ
3. จัดเก็บผลลัพธ์ที่สำเร็จเก็บการคาดการณ์ทั้งแบบ identified และ unknown รวมถึง JSON null และฟิลด์หลักฐานผลลัพธ์ที่ไม่ทราบเป็นผลที่เสร็จสมบูรณ์และถูกหักเครดิต ไม่ใช่แถวที่ล้มเหลวซึ่งต้องส่งซ้ำอัตโนมัติ
4. ตรวจสอบข้อผิดพลาดและเครดิตตรวจสอบ error แต่ละรายการและ meta.usage.billing_status ก่อนตัดสินใจส่งคำขอถัดไปเมื่อยืนยันการหักเครดิตแล้ว ให้ส่งซ้ำเฉพาะรายการที่ล้มเหลวซึ่งข้อผิดพลาดควรส่งซ้ำ รายการที่สำเร็จจะถูกหักเครดิตอีกครั้ง
5. พักการส่งซ้ำที่ไม่แน่นอนเก็บ รหัสคำขอ ไว้เมื่อการหักเครดิตยังไม่ยืนยันหรือความล้มเหลวของเครือข่ายทำให้ไม่ทราบผลอย่าส่งทั้งชุดซ้ำโดยไม่ตรวจสอบ ให้ทำตามคู่มือข้อผิดพลาดและการหักเครดิตก่อน

เลือกโหมดการคาดการณ์สำหรับผู้ติดต่อแต่ละราย

คำขอที่รันได้นี้ใช้นโยบายสามแบบ ได้แก่ เฉพาะชุดข้อมูลสำหรับชื่อ-นามสกุล AI สำรองแบบปกติสำหรับอีเมล และ AI สำรองที่ตีความชื่อเล่นสำหรับชื่อผู้ใช้ นี่เป็นเพียงข้อมูลนำเข้าตัวอย่าง ไม่ได้รับประกันว่าผู้ติดต่อทั้งสามรายจะได้ผลเป็นเพศ เลือกภาษาโปรแกรมเหนือโค้ด และตั้งค่า GENDERAPI_API_KEY ก่อนรัน

หากไม่ใช้ forceToGenderize รายการในคำขอแบบกลุ่มจะปิด AI ไว้ตามค่าเริ่มต้น ซึ่งต่างจากการค้นหาแบบเดี่ยว ระบุ fallback อย่างชัดเจนเมื่อต้องการ AI สำรองแบบปกติ ทั้ง off และ fallback แบบปกติใช้ 1 เครดิตต่อรายการที่สำเร็จ ส่วน always ข้ามชุดข้อมูลและใช้ 2 เครดิต forceToGenderize ใช้ 1 เครดิตเมื่อชุดข้อมูลระบุเพศได้ หรือรวม 2 เครดิตหากใช้ AI ผลลัพธ์ที่ไม่ทราบซึ่งดำเนินการสำเร็จก็ถูกหักเครดิตเช่นกัน อย่าใช้ forceToGenderize ร่วมกับ off หรือ always

เลือกภาษาโปรแกรม ตั้งค่าคีย์ API จากนั้นรันตัวอย่างบนเซิร์ฟเวอร์ของคุณ

คำขอคาดการณ์ทุกครั้งเป็นงานใหม่ที่มีการหักเครดิต รวมถึงคำขอที่ส่งซ้ำ ตัวอย่างเหล่านี้ไม่ส่งคำขอซ้ำโดยอัตโนมัติ ตรวจสอบสถานะการหักเครดิตก่อนส่งคำขออีกครั้ง

ก่อนรัน: การเข้าถึงและการจัดการข้อผิดพลาด

รันตัวอย่างเหล่านี้บนเซิร์ฟเวอร์ของคุณ ตั้งค่า GENDERAPI_API_KEY ในสภาพแวดล้อมของโปรเซสเป็นคีย์ API ที่มีอยู่ ตรวจสอบว่า meta.access.mode เป็น api_key เพราะคีย์ที่ระบบไม่รู้จักอาจทำให้ใช้การทดลองใช้ตาม IP แทน

การตอบกลับ JSON ที่มี HTTP 4xx และ 5xx จะคงเนื้อหาข้อผิดพลาดไว้และจบด้วยสถานะการออกที่ไม่ใช่ศูนย์ ตรวจสอบ 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 รันในเทอร์มินัล เอกสารของรันไทม์

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 เอกสารของรันไทม์