TÀI LIỆU API V2

Giới tính từ tên với API V2

Dự đoán giới tính từ tên hoặc họ tên đầy đủ với GenderAPI.io V2. Xem ví dụ bằng bảy ngôn ngữ lập trình, phản hồi JSON, ngữ cảnh quốc gia, AI dự phòng và chi phí tín dụng.

Trước khi gửi yêu cầu

Gửi JSON đến POST https://api.genderapi.io/api/v2/gender. Dùng khóa API hiện có trong Authorization: Bearer YOUR_API_KEY và Content-Type: application/json. Mỗi yêu cầu được xử lý độc lập.

Chọn ngôn ngữ lập trình trong ví dụ mã. Đặt GENDERAPI_API_KEY trong biến môi trường của tiến trình trước khi chạy. Khóa bị thiếu hoặc không được nhận diện có thể dùng thử theo IP dùng chung, vì vậy khi tích hợp một tài khoản, hãy xác nhận meta.access.mode là api_key.

Giới tính từ tên

Tham sốKiểuBắt buộcMặc địnhMô tả
typestringCó—Loại đầu vào: name, email hoặc username.
valuestringCó—Bắt buộc. 1–254 ký tự; không để trống, không chứa ký tự điều khiển. Giá trị email phải đúng cú pháp email.
countrystringKhông—Mã ISO 3166-1 alpha-2 viết hoa, tùy chọn, ví dụ TR hoặc US. Tra cứu theo quốc gia có thể chuyển sang tập dữ liệu toàn cầu.
forceToGenderizebooleanKhôngfalseTra tập dữ liệu trước, sau đó dùng AI có phân tích biệt danh nếu chưa xác định được. Hỗ trợ name, email và username.
optionsobjectKhông—Đối tượng chứa tùy chọn AI cho từng đầu vào.
options.ai_modestringKhôngfallbackGiá trị hợp lệ: off, fallback, always. Với forceToGenderize: true, bỏ qua trường này hoặc dùng fallback.
idstringKhông—Mã định danh tùy chọn dài 1–64 ký tự trong JSON của POST. Được trả về cùng từng kết quả trong lô; phải là duy nhất trong một lô. Yêu cầu đơn lẻ chấp nhận trường này nhưng không trả lại. Không hỗ trợ trong truy vấn GET.

Dùng type: name cho tên hoặc họ tên đầy đủ. Phản hồi thành công vẫn có thể chứa gender: null. Yêu cầu đơn lẻ tra tập dữ liệu trước và theo mặc định sẽ dùng AI khi không xác định được giới tính.

Chọn ngôn ngữ lập trình. Thiết lập khóa API, sau đó chạy ví dụ trên máy chủ của bạn.

Mỗi yêu cầu dự đoán là một thao tác mới bị tính phí, kể cả khi thử lại. Các ví dụ này không tự động thử lại. Kiểm tra trạng thái tính phí trước khi gửi yêu cầu khác.

Trước khi chạy: quyền truy cập và xử lý lỗi

Chạy các ví dụ này trên máy chủ của bạn. Đặt GENDERAPI_API_KEY trong biến môi trường của tiến trình bằng khóa API hiện có. Xác nhận meta.access.mode là api_key: khóa không được nhận diện có thể chuyển sang dùng thử theo IP.

Với phản hồi JSON HTTP 4xx và 5xx, ví dụ giữ nguyên nội dung lỗi và kết thúc với mã thoát khác 0. Kiểm tra code, action và meta.usage.billing_status trước khi thử lại.

Hướng dẫn về lỗi và thử lại →
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": "name",
  "value": "Tuấn",
  "country": "VN"
}'

cURL 7.76+ trong shell POSIX. Chạy trong terminal. Tài liệu môi trường chạy

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": "name",
  "value": "Tuấn",
  "country": "VN"
};

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 tích hợp sẵn. Lưu thành example.mjs và chạy node example.mjs. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Tuấn\",\"country\":\"VN\"}")

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+; thư viện chuẩn. Lưu thành example.py và chạy python3 example.py. Tài liệu môi trường chạy

PHP
<?php
$apiKey = getenv('GENDERAPI_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set GENDERAPI_API_KEY');
}
$body = json_decode('{"type":"name","value":"Tuấn","country":"VN"}', 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+ với tiện ích mở rộng cURL. Lưu thành example.php và chạy php example.php. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Tuấn\",\"country\":\"VN\"}";
        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 client chuẩn. Lưu thành GenderApiExample.java và chạy java GenderApiExample.java. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Tuấn\",\"country\":\"VN\"}", 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.
}

Ứng dụng console .NET 8+. Dùng làm Program.cs trong một dự án console, sau đó chạy dotnet run. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Tuấn\",\"country\":\"VN\"}"
    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+; thư viện chuẩn. Lưu thành main.go và chạy go run main.go. Tài liệu môi trường chạy

Ví dụ phản hồi

Đây là phản hồi thực được ghi lại ngày 1 tháng 10 năm 2026 bằng khóa API; chỉ số dư tài khoản đã được thay thế. Đây không phải là thước đo độ chính xác, và một yêu cầu trực tiếp có thể trả về kết quả khác. Yêu cầu dùng khóa API trả về meta.access.mode: api_key và null ở các trường hạn mức chỉ dành cho dùng thử; yêu cầu dùng thử theo IP trả về ip_trial. Đọc data để xem kết quả suy luận và meta.usage để biết kết quả tính phí của thao tác.

Phản hồi JSON minh họa
{
  "data": {
    "input": {
      "type": "name",
      "value": "Tuấn",
      "country": "VN"
    },
    "name": "tuấn",
    "gender": "male",
    "country": "VN",
    "confidence": 0.9915730337078652,
    "confidence_kind": "observed_frequency",
    "sample_count": 356,
    "source": "dataset",
    "result_status": "identified",
    "reason": null,
    "country_source": "dataset",
    "match": {
      "name": "tuấn",
      "method": "normalized",
      "scope": "country",
      "country": "VN"
    }
  },
  "meta": {
    "request_id": "6630814b-b7c8-4e85-860d-dacee06d0d8c",
    "duration_ms": 11,
    "access": {
      "mode": "api_key",
      "reason": null
    },
    "usage": {
      "charged_credits": 1,
      "remaining_credits": 49999,
      "billing_status": "confirmed",
      "resets_at": null,
      "limit": null,
      "period_seconds": null
    }
  }
}

Trường phản hồi dự đoán

TrườngKiểuCó thể là nullVí dụMô tả
data.inputobjectKhông{"type":"name","value":"Tuấn","country":"VN"}Loại đầu vào, giá trị và quốc gia. forceToGenderize được đưa vào khi là true.
data.namestringCó"tuấn"Tên riêng đã khớp hoặc trích xuất được; null khi không có.
data.genderstringCó"male"male, female hoặc JSON null. Đây là suy luận, không phải danh tính cá nhân đã xác minh.
data.result_statusstringKhông"identified"identified khi có giới tính được trả về; nếu không thì unknown.
data.reasonstringCónullnull với kết quả identified. Lý do cho unknown: not_found, no_name_candidate, ambiguous hoặc insufficient_evidence.
data.confidencenumberCó0.95Giá trị từ 0 đến 1 hoặc null. Khi gender là null, độ tin cậy cũng là null.
data.confidence_kindstringCó"observed_frequency"observed_frequency: số lượng của nhóm chiếm ưu thế trong tập dữ liệu chia cho tổng số. model_reported: điểm do AI đưa ra, không phải xác suất đã hiệu chỉnh. Là null khi không có.
data.sample_countintegerCó1200Cỡ mẫu trong tập dữ liệu hoặc null. AI không tự tạo ra số lượng mẫu.
data.sourcestringKhông"dataset"dataset, ai hoặc none.
data.countrystringCó"VN"Mối liên hệ quốc gia từ dataset hoặc ai_association, hoặc null. Không xác định quốc tịch, nơi cư trú hay dân tộc.
data.country_sourcestringCó"dataset"Nguồn của mối liên hệ quốc gia: dataset, ai_association hoặc null.
data.matchobjectKhông{"name":"tuấn","method":"normalized","scope":"country","country":"VN"}Tên khớp trong tập dữ liệu, phương thức (normalized, token, substring hoặc model_inference), phạm vi country hoặc global và quốc gia đã khớp. Bằng chứng không có sẽ là null.

Siêu dữ liệu về truy cập, tính phí và yêu cầu

TrườngKiểuCó thể là nullVí dụMô tả
meta.request_idstringKhông"550e8400-e29b-41d4-a716-446655440000"Mã định danh duy nhất của lần gửi HTTP này; cũng được gửi trong X-Request-ID.
meta.duration_msintegerKhông42Thời gian xử lý yêu cầu tính bằng mili giây.
meta.access.modestringKhông"api_key"api_key, ip_trial hoặc unauthenticated. Khi dùng tài khoản trả phí, hãy kiểm tra giá trị là api_key.
meta.access.reasonstringCónullLý do chuyển sang dùng thử: api_key_missing, api_key_invalid hoặc api_key_not_found; trường hợp khác là null.
meta.usage.charged_creditsintegerCó1Số tín dụng thực tính. Bằng 0 trước khi tính phí hoặc sau khi hoàn trả toàn bộ đã được xác nhận; null khi việc tính phí chưa được xác nhận.
meta.usage.remaining_creditsintegerCó99Số dư khi thao tác hoàn tất. Có thể âm; null khi không có thông tin hoặc việc tính phí chưa được xác nhận.
meta.usage.billing_statusstringKhông"confirmed"not_charged, confirmed hoặc unconfirmed. Kiểm tra trường này trước khi thử lại một dự đoán thất bại.
meta.usage.resets_atstringCó"2026-09-27T12:00:00.000Z"Thời điểm đặt lại dùng thử theo IP, theo UTC (ISO 8601); null với tài khoản dùng khóa API hoặc khi chưa biết.
meta.usage.limitintegerCó10Hạn mức dùng thử theo IP; null với tài khoản dùng khóa API.
meta.usage.period_secondsintegerCó86400Chu kỳ dùng thử theo IP tính bằng giây; null với tài khoản dùng khóa API.

Ngữ cảnh quốc gia và tên không xác định

Chỉ gửi country khi bạn có ngữ cảnh liên quan. API có thể chọn một dòng tập dữ liệu theo quốc gia hoặc chuyển sang dòng toàn cầu. data.match.scope cho biết dòng nào đã được chọn; quốc gia được trả về không xác định nơi người đó sinh sống.

Theo mặc định, yêu cầu đơn lẻ dùng AI dự phòng với tổng chi phí 1 tín dụng. Để chỉ dùng tập dữ liệu, gửi options: {"ai_mode": "off"}. Đầu vào chưa xác định được có thể trả về gender: null và vẫn bị tính phí khi thao tác thành công. Họ tên đầy đủ có thể khớp qua một thành phần; data.match ghi lại ứng viên được chọn và phương thức so khớp.

Với giá trị name giống biệt danh, forceToGenderize: true cho phép suy luận mà không cần tên thật: kết quả xác định được từ tập dữ liệu tốn 1 tín dụng; nếu không, AI có phân tích biệt danh tốn tổng cộng 2 tín dụng. Chỉ cần số dư ban đầu dương và số dư sau đó có thể âm.

Tra cứu họ tên đầy đủ mà không mặc định từ đầu tiên sẽ được chọn

Gửi tên ở dạng Unicode gốc. Khi so khớp với tập dữ liệu, hệ thống áp dụng chuẩn hóa NFKC, chuyển thành chữ thường và tách token; bạn không cần chuyển tên sang ASCII. Trong số các bản ghi ứng viên hiện có, API chọn bản ghi có tổng số lượng lưu trữ lớn nhất. Ứng viên đó có thể là một thành phần đứng sau trong tên, vì vậy đừng mặc định rằng từ đầu tiên hoặc tên riêng đã được chọn.

Yêu cầu chỉ dùng tập dữ liệu này giúp bạn dễ kiểm tra bằng chứng đã được chọn. Đọc data.input.value để biết họ tên đầy đủ đã gửi, data.match.name để biết ứng viên được tra cứu và data.match.method để biết phương thức so khớp. Ví dụ này không hứa hẹn một giới tính hay một token cụ thể nào sẽ được chọn. Ứng viên trong tập dữ liệu phải dài hơn hai ký tự; đầu vào ngắn có thể không xác định được. Hãy dùng AI dự phòng thông thường khi suy luận bổ sung đó phù hợp với ứng dụng của bạn.

Chọn ngôn ngữ lập trình. Thiết lập khóa API, sau đó chạy ví dụ trên máy chủ của bạn.

Mỗi yêu cầu dự đoán là một thao tác mới bị tính phí, kể cả khi thử lại. Các ví dụ này không tự động thử lại. Kiểm tra trạng thái tính phí trước khi gửi yêu cầu khác.

Trước khi chạy: quyền truy cập và xử lý lỗi

Chạy các ví dụ này trên máy chủ của bạn. Đặt GENDERAPI_API_KEY trong biến môi trường của tiến trình bằng khóa API hiện có. Xác nhận meta.access.mode là api_key: khóa không được nhận diện có thể chuyển sang dùng thử theo IP.

Với phản hồi JSON HTTP 4xx và 5xx, ví dụ giữ nguyên nội dung lỗi và kết thúc với mã thoát khác 0. Kiểm tra code, action và meta.usage.billing_status trước khi thử lại.

Hướng dẫn về lỗi và thử lại →
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": "name",
  "value": "Ayşe Yılmaz",
  "country": "TR",
  "options": {
    "ai_mode": "off"
  }
}'

cURL 7.76+ trong shell POSIX. Chạy trong terminal. Tài liệu môi trường chạy

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": "name",
  "value": "Ayşe Yılmaz",
  "country": "TR",
  "options": {
    "ai_mode": "off"
  }
};

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 tích hợp sẵn. Lưu thành example.mjs và chạy node example.mjs. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}}")

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+; thư viện chuẩn. Lưu thành example.py và chạy python3 example.py. Tài liệu môi trường chạy

PHP
<?php
$apiKey = getenv('GENDERAPI_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set GENDERAPI_API_KEY');
}
$body = json_decode('{"type":"name","value":"Ayşe Yılmaz","country":"TR","options":{"ai_mode":"off"}}', 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+ với tiện ích mở rộng cURL. Lưu thành example.php và chạy php example.php. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}}";
        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 client chuẩn. Lưu thành GenderApiExample.java và chạy java GenderApiExample.java. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}}", 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.
}

Ứng dụng console .NET 8+. Dùng làm Program.cs trong một dự án console, sau đó chạy dotnet run. Tài liệu môi trường chạy

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\":\"name\",\"value\":\"Ayşe Yılmaz\",\"country\":\"TR\",\"options\":{\"ai_mode\":\"off\"}}"
    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+; thư viện chuẩn. Lưu thành main.go và chạy go run main.go. Tài liệu môi trường chạy

Kiểm tra ngữ cảnh quốc gia nào thực sự được sử dụng

Chỉ dùng mã quốc gia ISO khi bạn có ngữ cảnh liên quan; đừng suy ra mã quốc gia từ kết quả dự đoán. Với mỗi ứng viên, dòng theo quốc gia (nếu có) được ưu tiên hơn dòng toàn cầu của ứng viên đó. Nếu không có dòng theo quốc gia, ứng viên có thể dùng dòng toàn cầu. Dòng theo quốc gia có số lượng bằng nhau không bị thay thế bằng dòng toàn cầu; nếu dòng được chọn có số lượng bằng nhau, kết quả từ tập dữ liệu là không xác định và AI dự phòng (nếu được bật) có thể chạy.

Bằng chứng trong phản hồiCách hiểuViệc ứng dụng nên làm
match.scope: country; match.country: TRỨng viên được chọn từ tập dữ liệu đã dùng dòng của quốc gia trong yêu cầu.Lưu ứng viên được chọn và phạm vi quốc gia cùng với dự đoán.
match.scope: global; match.country: nullỨng viên được chọn đã dùng dòng toàn cầu, kể cả khi yêu cầu có gửi quốc gia.Không gắn nhãn kết quả là kết quả khớp theo quốc gia.
country_source: dataset hoặc ai_associationCho biết nguồn gốc của data.country, không phải phạm vi tra cứu tập dữ liệu hay quốc tịch của người đó.Đọc riêng với match.country; không trường nào xác minh nơi cư trú hay quốc tịch.
source: ai; match.scope: nullAI tạo ra phản hồi cuối cùng, vì vậy phản hồi đó không có dòng tập dữ liệu nào được chọn.Áp dụng hướng dẫn về độ tin cậy của AI và giữ nguyên các kết quả không xác định.

Hướng dẫn liên quan