เอกสาร API V2

คาดการณ์เพศจากชื่อผู้ใช้ด้วย API V2

คาดการณ์จากชื่อผู้ใช้และชื่อเล่นด้วย GenderAPI.io V2 เรียนรู้ forceToGenderize การค้นหาในชุดข้อมูลก่อน ฟิลด์การตอบกลับของ AI และอัตรา 1 หรือ 2 เครดิต

ก่อนส่งคำขอ

ส่ง JSON ไปยัง POST https://api.genderapi.io/api/v2/gender ใช้คีย์ API ที่มีอยู่ใน Authorization: Bearer YOUR_API_KEY และ Content-Type: application/json คำขอแต่ละรายการได้รับการประมวลผลแยกกัน

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

คาดการณ์เพศจากชื่อผู้ใช้หรือชื่อเล่น

พารามิเตอร์ชนิดข้อมูลจำเป็นค่าเริ่มต้นคำอธิบาย
typestringใช่—ประเภทข้อมูลนำเข้า: name, email หรือ username
valuestringใช่—จำเป็น ความยาว 1–254 อักขระ ต้องไม่ว่างและไม่มีอักขระควบคุม ค่าอีเมลต้องมีรูปแบบอีเมลที่ถูกต้อง
countrystringไม่—รหัส ISO 3166-1 alpha-2 ตัวพิมพ์ใหญ่ ไม่บังคับ เช่น TR หรือ US การค้นหาตามประเทศอาจใช้ชุดข้อมูลส่วนกลางแทนได้
forceToGenderizebooleanไม่falseค้นหาในชุดข้อมูลก่อน แล้วใช้ AI ที่ตีความชื่อเล่นหากยังระบุเพศไม่ได้ รองรับ name, email และ username
optionsobjectไม่—ออบเจ็กต์ที่เก็บตัวเลือก AI ของข้อมูลนำเข้าแต่ละรายการ
options.ai_modestringไม่fallbackค่าที่อนุญาต: off, fallback, always หากใช้ forceToGenderize: true ให้ละฟิลด์นี้หรือใช้ fallback
idstringไม่—ตัวระบุใน JSON ของ POST ความยาว 1–64 อักขระ ไม่บังคับ ส่งคืนคู่กับผลลัพธ์แต่ละรายการของคำขอแบบกลุ่ม และต้องไม่ซ้ำกันภายในคำขอแบบกลุ่มเดียวกัน คำขอเดี่ยวรับค่านี้ได้แต่ไม่ส่งคืน ไม่รองรับในคิวรีของ GET

ใช้ type: username สำหรับชื่อบัญชีและชื่อเล่น ตั้งค่า forceToGenderize เป็น true เมื่อต้องการให้คาดการณ์จากความหมายของชื่อเล่น เช่น prenses แม้จะดึงชื่อจริงออกมาไม่ได้ ระบบยังค้นหาในชุดข้อมูลก่อน การคาดการณ์จากชื่อเล่นอาจส่งคืนเพศที่ไม่ใช่ null พร้อม name: null

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

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

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

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

การตอบกลับ JSON ที่มี HTTP 4xx และ 5xx จะคงเนื้อหาข้อผิดพลาดไว้และจบด้วยสถานะการออกที่ไม่ใช่ศูนย์ ตรวจสอบ code, action และ meta.usage.billing_status ก่อนส่งคำขอซ้ำ

คู่มือข้อผิดพลาดและการส่งคำขอซ้ำ →
cURL
curl --silent --show-error --fail-with-body --max-time 30 \
  --request POST 'https://api.genderapi.io/api/v2/gender' \
  --header "Authorization: Bearer ${GENDERAPI_API_KEY:?Set GENDERAPI_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{
  "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 = {
  "type": "username",
  "value": "prenses",
  "country": "TR",
  "forceToGenderize": true
};

const response = await fetch("https://api.genderapi.io/api/v2/gender", {
  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("{\"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",
    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('{"type":"username","value":"prenses","country":"TR","forceToGenderize":true}', true, 512, JSON_THROW_ON_ERROR);

$ch = curl_init('https://api.genderapi.io/api/v2/gender');
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 = "{\"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"))
            .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");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent("{\"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 := "{\"type\":\"username\",\"value\":\"prenses\",\"country\":\"TR\",\"forceToGenderize\":true}"
    request, err := http.NewRequest("POST", "https://api.genderapi.io/api/v2/gender", 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 ด้วยคีย์ API โดยแทนที่เฉพาะยอดคงเหลือของบัญชีเท่านั้น การตอบกลับนี้ไม่ใช่ตัววัดความแม่นยำ และคำขอจริงอาจได้ผลลัพธ์ที่ต่างออกไป คำขอที่ใช้คีย์ API จะรายงาน meta.access.mode: api_key และฟิลด์โควตาที่ใช้เฉพาะการทดลองใช้จะเป็น null ส่วนคำขอแบบทดลองใช้ตาม IP จะรายงาน ip_trial อ่าน data เพื่อดูผลการคาดการณ์ และอ่าน meta.usage เพื่อดูผลการหักเครดิตของงาน

ตัวอย่างการตอบกลับ JSON
{
  "data": {
    "input": {
      "type": "username",
      "value": "prenses",
      "country": "TR",
      "forceToGenderize": true
    },
    "name": "prenses",
    "gender": "female",
    "country": "TR",
    "confidence": 0.9456521739130435,
    "confidence_kind": "observed_frequency",
    "sample_count": 184,
    "source": "dataset",
    "result_status": "identified",
    "reason": null,
    "country_source": "dataset",
    "match": {
      "name": "prenses",
      "method": "normalized",
      "scope": "country",
      "country": "TR"
    }
  },
  "meta": {
    "request_id": "a799faa4-bc1a-4537-90b3-2c1b60205499",
    "duration_ms": 15,
    "access": {
      "mode": "api_key",
      "reason": null
    },
    "usage": {
      "charged_credits": 1,
      "remaining_credits": 49999,
      "billing_status": "confirmed",
      "resets_at": null,
      "limit": null,
      "period_seconds": null
    }
  }
}

ฟิลด์การตอบกลับของการคาดการณ์

ฟิลด์ชนิดข้อมูลเป็น null ได้ตัวอย่างคำอธิบาย
data.inputobjectไม่{"type":"name","value":"สมชาย","country":"TH"}ประเภท ค่า และประเทศของข้อมูลนำเข้า จะมี forceToGenderize ด้วยเมื่อเป็น true
data.namestringใช่"สมชาย"ชื่อจริงที่ตรงกันหรือที่ดึงออกมา เป็น null เมื่อไม่มี
data.genderstringใช่"male"male, female หรือ JSON null เป็นผลการคาดการณ์ ไม่ใช่ตัวตนของบุคคลที่ได้รับการยืนยัน
data.result_statusstringไม่"identified"เป็น identified เมื่อส่งคืนเพศ มิฉะนั้นเป็น unknown
data.reasonstringใช่nullเป็น null สำหรับผลลัพธ์ identified เหตุผลของผลลัพธ์ที่ไม่ทราบ: not_found, no_name_candidate, ambiguous หรือ insufficient_evidence
data.confidencenumberใช่0.95คะแนน 0–1 หรือ null เมื่อเพศเป็น null ค่าความเชื่อมั่นก็เป็น null
data.confidence_kindstringใช่"observed_frequency"observed_frequency: จำนวนของเพศที่พบมากที่สุดในชุดข้อมูลหารด้วยจำนวนทั้งหมด model_reported: คะแนนจาก AI ไม่ใช่ความน่าจะเป็นที่ปรับเทียบแล้ว เป็น null เมื่อไม่มีค่า
data.sample_countintegerใช่1200ขนาดตัวอย่างในชุดข้อมูลหรือ null AI จะไม่สร้างจำนวนตัวอย่างขึ้นเอง
data.sourcestringไม่"dataset"dataset, ai หรือ none
data.countrystringใช่"TH"ความเชื่อมโยงกับประเทศจาก dataset หรือ ai_association หรือเป็น null ไม่ได้บ่งบอกสัญชาติ ถิ่นที่อยู่ หรือชาติพันธุ์
data.country_sourcestringใช่"dataset"แหล่งที่มาของความเชื่อมโยงกับประเทศ: dataset, ai_association หรือ null
data.matchobjectไม่{"name":"สมชาย","method":"normalized","scope":"country","country":"TH"}ชื่อที่ตรงกันในชุดข้อมูล วิธีจับคู่ (normalized, token, substring หรือ model_inference) ขอบเขต country/global และประเทศที่ตรงกัน หลักฐานที่ไม่มีจะเป็น null

เมทาดาทาของการเข้าถึง การหักเครดิต และคำขอ

ฟิลด์ชนิดข้อมูลเป็น 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

อ่านผลการคาดการณ์จากชื่อเล่น

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

ในโหมดชื่อเล่น เพศที่คาดการณ์ได้พร้อม name: null ถือว่าถูกต้อง หมายความว่าไม่ได้ดึงชื่อจริงออกมา ไม่ใช่ข้อผิดพลาดของตัวแยกวิเคราะห์ เมื่อ AI ส่งคืนเพศ ผลลัพธ์จะมี sample_count: null และ confidence_kind: model_reported คะแนนนี้ไม่ใช่ความน่าจะเป็นที่ปรับเทียบแล้วหรือการยืนยันตัวตน

หากไม่ใช้ forceToGenderize การค้นหาชื่อผู้ใช้แบบเดี่ยวยังใช้ AI สำรองแบบปกติเป็นค่าเริ่มต้น รวมทั้งหมด 1 เครดิต แต่ต้องมีชื่อจริงที่ใช้ได้ ใช้ options.ai_mode: off หากต้องการประมวลผลเฉพาะชุดข้อมูล

คู่มือที่เกี่ยวข้อง