API 문서 V2

GenderAPI.io V2로 이름에서 성별 추정

GenderAPI.io V2로 이름이나 전체 이름에서 성별을 추정하세요. 7개 프로그래밍 언어 예시, JSON 응답, 국가 컨텍스트, AI 폴백과 크레딧 비용을 확인할 수 있습니다.

요청을 보내기 전에

POST https://api.genderapi.io/api/v2/gender로 JSON을 보내세요. Authorization: Bearer YOUR_API_KEY 헤더에 기존 API 키를 넣고 Content-Type: application/json을 지정하세요. 모든 요청은 독립적으로 처리됩니다.

코드 예시에서 언어를 선택하세요. 실행하기 전에 프로세스 환경 변수 GENDERAPI_API_KEY를 설정하세요. 키가 없거나 인식되지 않으면 공유 IP 체험이 사용될 수 있으므로, 계정을 연동할 때는 meta.access.mode가 api_key인지 확인하세요.

이름에서 성별 추정

매개변수유형필수기본값설명
typestring예—입력 종류: name, email 또는 username.
valuestring예—필수. 1~254자이며 공백만으로 이루어질 수 없고 제어 문자를 포함할 수 없습니다. 이메일 값은 올바른 이메일 구문이어야 합니다.
countrystring아니요—선택 사항. TR이나 US 같은 대문자 ISO 3166-1 alpha-2 코드입니다. 국가별 조회는 전역 데이터셋으로 대체될 수 있습니다.
forceToGenderizeboolean아니요false먼저 데이터셋을 조회하고, 결과가 없으면 별명을 해석하는 AI를 사용합니다. name, email, username을 지원합니다.
optionsobject아니요—입력별 AI 옵션을 담는 객체입니다.
options.ai_modestring아니요fallback허용값: off, fallback, always. forceToGenderize: true이면 이 필드를 생략하거나 fallback을 사용하세요.
idstring아니요—POST JSON에서 쓸 수 있는 1~64자의 선택적 식별자입니다. 일괄 요청에서는 각 결과와 함께 반환되며 일괄 요청 안에서 고유해야 합니다. 단일 추정 요청에서는 받기만 하고 응답에 다시 포함하지 않습니다. GET 쿼리에서는 지원하지 않습니다.

이름이나 전체 이름에는 type: name을 사용하세요. 요청이 성공해도 응답에 gender: null이 포함될 수 있습니다. 단일 요청은 먼저 데이터셋을 확인하고, 성별을 판단할 수 없으면 기본적으로 AI에 요청합니다.

프로그래밍 언어를 선택하세요. API 키 설정하기, 그다음 서버에서 예시를 실행하세요.

재시도를 포함해 모든 추정 요청은 새로 과금되는 작업입니다. 이 예시는 자동으로 재시도하지 않습니다. 다른 요청을 보내기 전에 과금 상태를 확인하세요.

실행하기 전에: 접근과 오류 처리

이 예시는 서버에서 실행하세요. 프로세스 환경 변수 GENDERAPI_API_KEY에 기존 API 키를 설정하세요. 인식되지 않는 키는 IP 체험으로 전환될 수 있으므로 meta.access.mode가 api_key인지 확인하세요.

HTTP 4xx 및 5xx JSON 응답에서는 오류 본문을 그대로 출력하고 0이 아닌 종료 코드를 반환합니다. 재시도하기 전에 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": "name",
  "value": "Jihoon",
  "country": "KR"
}'

POSIX 셸의 cURL 7.76+. 터미널에서 실행하세요. 런타임 문서

JavaScript / Node.js
// Server-side Node.js. Save as example.mjs.
const apiKey = process.env.GENDERAPI_API_KEY;
if (!apiKey) throw new Error("Set GENDERAPI_API_KEY");
const body = {
  "type": "name",
  "value": "Jihoon",
  "country": "KR"
};

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\":\"name\",\"value\":\"Jihoon\",\"country\":\"KR\"}")

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":"name","value":"Jihoon","country":"KR"}', 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\":\"name\",\"value\":\"Jihoon\",\"country\":\"KR\"}";
        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\":\"name\",\"value\":\"Jihoon\",\"country\":\"KR\"}", 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\":\"name\",\"value\":\"Jihoon\",\"country\":\"KR\"}"
    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를 실행하세요. 런타임 문서

응답 예시

이 응답은 2026년 10월 1일에 API 키로 받은 실제 응답이며, 계정 잔액만 바꿨습니다. 정확도를 측정한 값이 아니며, 실제 요청에서는 다른 결과가 반환될 수 있습니다. API 키 요청에서는 meta.access.mode: api_key와 null인 IP 체험 전용 한도 필드가 반환되고, IP 체험 요청에서는 ip_trial이 반환됩니다. 추정 결과는 data에서, 작업의 과금 결과는 meta.usage에서 확인하세요.

설명용 JSON 응답
{
  "data": {
    "input": {
      "type": "name",
      "value": "Jihoon",
      "country": "KR"
    },
    "name": "jihoon",
    "gender": "male",
    "country": "KR",
    "confidence": 0.9693877551020408,
    "confidence_kind": "observed_frequency",
    "sample_count": 196,
    "source": "dataset",
    "result_status": "identified",
    "reason": null,
    "country_source": "dataset",
    "match": {
      "name": "jihoon",
      "method": "normalized",
      "scope": "country",
      "country": "KR"
    }
  },
  "meta": {
    "request_id": "81a126a7-5333-4023-ada5-19823d8e9bf4",
    "duration_ms": 8,
    "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":"Jihoon","country":"KR"}입력 유형, 값과 국가입니다. forceToGenderize가 true이면 함께 포함됩니다.
data.namestring예"jihoon"일치하거나 추출된 이름이며, 없으면 null입니다.
data.genderstring예"male"male, female 또는 JSON null. 확인된 개인 신원이 아닌 추정입니다.
data.result_statusstring아니요"identified"성별이 반환되면 identified, 그렇지 않으면 unknown입니다.
data.reasonstring예nullidentified 결과에서는 null입니다. 알 수 없는 결과의 사유: not_found, no_name_candidate, ambiguous 또는 insufficient_evidence.
data.confidencenumber예0.950~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예"KR"dataset 또는 ai_association에서 나온 국가 연관성, 또는 null. 국적, 거주지, 민족을 나타내지 않습니다.
data.country_sourcestring예"dataset"국가 연관성의 출처: dataset, ai_association 또는 null.
data.matchobject아니요{"name":"jihoon","method":"normalized","scope":"country","country":"KR"}일치한 데이터셋 이름, 일치 방법(normalized, token, substring 또는 model_inference), 국가/전역 범위와 일치한 국가입니다. 확인할 수 없는 근거는 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예nullIP 체험으로 전환된 사유: api_key_missing, api_key_invalid 또는 api_key_not_found. 그 외에는 null입니다.
meta.usage.charged_creditsinteger예1차감된 순 크레딧입니다. 차감 전이나 전액 반환이 확인된 뒤에는 0이며, 과금이 미확정이면 null입니다.
meta.usage.remaining_creditsinteger예99작업 완료 시점의 잔액입니다. 음수일 수 있으며, 확인할 수 없거나 과금이 미확정이면 null입니다.
meta.usage.billing_statusstring아니요"confirmed"not_charged, confirmed 또는 unconfirmed. 실패한 추정을 재시도하기 전에 확인하세요.
meta.usage.resets_atstring예"2026-09-27T12:00:00.000Z"IP 체험 초기화 시각(UTC, ISO 8601)입니다. API 키 계정이거나 알 수 없으면 null입니다.
meta.usage.limitinteger예10IP 체험 크레딧 한도이며, API 키 계정에서는 null입니다.
meta.usage.period_secondsinteger예86400IP 체험 기간(초)이며, API 키 계정에서는 null입니다.

국가 컨텍스트와 알 수 없는 이름

관련된 컨텍스트가 있을 때만 country를 보내세요. API는 국가별 데이터셋 행을 선택하거나 전역 행으로 대체할 수 있습니다. 어느 쪽이 선택되었는지는 data.match.scope에서 확인할 수 있으며, 반환된 국가가 그 사람이 사는 곳을 나타내지는 않습니다.

단일 요청은 기본적으로 AI 폴백을 사용하며 총 1크레딧입니다. 데이터셋만 사용하려면 options: {"ai_mode": "off"}를 보내세요. 추정할 수 없는 입력은 gender: null을 반환할 수 있으며, 작업이 성공하면 이 경우에도 과금됩니다. 전체 이름은 그 일부가 일치할 수 있으며, data.match에는 선택된 후보와 일치 방법이 기록됩니다.

별명 형태의 name 값에 forceToGenderize: true를 사용하면 실제 이름이 없어도 추정할 수 있습니다. 데이터셋에서 결과를 얻으면 1크레딧, 그렇지 않아 별명을 해석하는 AI를 사용하면 총 2크레딧입니다. 시작 잔액이 0보다 크면 요청할 수 있으며, 차감 후 잔액은 음수가 될 수 있습니다.

전체 이름을 조회할 때 첫 단어가 선택된다고 가정하지 않기

원래의 Unicode 이름을 그대로 보내세요. 데이터셋 일치에서는 NFKC 정규화, 소문자 변환과 토큰 추출이 적용되므로 이름을 ASCII로 바꿀 필요가 없습니다. API는 사용할 수 있는 후보 레코드 중 저장된 합계가 가장 큰 레코드를 선택합니다. 그 후보가 이름의 뒷부분일 수도 있으므로 첫 단어나 이름 부분이 선택되었다고 가정하지 마세요.

이 요청은 데이터셋만 사용하므로 선택된 근거를 확인하기 쉽습니다. 제출한 전체 이름은 data.input.value에서, 조회에 사용된 후보는 data.match.name에서, 일치 방법은 data.match.method에서 확인하세요. 이 예시는 특정 성별이나 특정 토큰이 선택된다고 약속하지 않습니다. 데이터셋 후보는 두 글자보다 길어야 하므로 짧은 입력은 추정되지 않을 수 있습니다. 추가 추정이 애플리케이션에 적절하다면 일반 AI 폴백을 사용하세요.

프로그래밍 언어를 선택하세요. API 키 설정하기, 그다음 서버에서 예시를 실행하세요.

재시도를 포함해 모든 추정 요청은 새로 과금되는 작업입니다. 이 예시는 자동으로 재시도하지 않습니다. 다른 요청을 보내기 전에 과금 상태를 확인하세요.

실행하기 전에: 접근과 오류 처리

이 예시는 서버에서 실행하세요. 프로세스 환경 변수 GENDERAPI_API_KEY에 기존 API 키를 설정하세요. 인식되지 않는 키는 IP 체험으로 전환될 수 있으므로 meta.access.mode가 api_key인지 확인하세요.

HTTP 4xx 및 5xx JSON 응답에서는 오류 본문을 그대로 출력하고 0이 아닌 종료 코드를 반환합니다. 재시도하기 전에 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": "name",
  "value": "Ayşe Yılmaz",
  "country": "TR",
  "options": {
    "ai_mode": "off"
  }
}'

POSIX 셸의 cURL 7.76+. 터미널에서 실행하세요. 런타임 문서

JavaScript / Node.js
// Server-side Node.js. Save as example.mjs.
const apiKey = process.env.GENDERAPI_API_KEY;
if (!apiKey) throw new Error("Set GENDERAPI_API_KEY");
const body = {
  "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. 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\":\"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+, 표준 라이브러리. 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":"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+, 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\":\"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 클라이언트. 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\":\"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.
}

.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\":\"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+, 표준 라이브러리. main.go로 저장하고 go run main.go를 실행하세요. 런타임 문서

실제로 어떤 국가 컨텍스트가 사용되었는지 확인하기

ISO 국가 코드는 관련된 컨텍스트가 있을 때만 사용하세요. 추정 결과를 보고 국가를 만들어 넣지 마세요. 각 후보에서는 국가별 행이 있으면 그 후보의 전역 행보다 우선합니다. 국가별 행이 없으면 그 후보는 전역 행을 사용할 수 있습니다. 건수가 같은 국가별 행은 전역 행으로 대체되지 않습니다. 선택된 행의 건수가 같으면 데이터셋 결과는 알 수 없음이 되며, 활성화된 AI 폴백이 실행될 수 있습니다.

응답의 근거의미애플리케이션에서 할 일
match.scope: country; match.country: TR선택된 데이터셋 후보가 요청한 국가의 행을 사용했습니다.선택된 후보와 국가 범위를 추정 결과와 함께 저장합니다.
match.scope: global; match.country: null요청에 국가를 지정했더라도 선택된 후보는 전역 행을 사용했습니다.이 결과를 국가별 일치로 표시하지 마세요.
country_source: dataset 또는 ai_associationdata.country의 출처를 설명할 뿐, 데이터셋 조회 범위나 그 사람의 국적을 나타내지 않습니다.match.country와 따로 확인하세요. 두 필드 모두 거주지나 국적을 확인해 주지 않습니다.
source: ai; match.scope: null최종 응답을 AI가 생성했으므로 이 응답에는 선택된 데이터셋 행이 없습니다.AI 신뢰도 가이드를 따르고 알 수 없는 결과를 그대로 유지합니다.

관련 가이드