API 문서 V2

배치 이름, 이메일 및 사용자 이름 예측

한 배치에 최대 50개의 GenderAPI v2 예측을 보냅니다. 항목별 옵션, 보존된 ID, 부분 실패, 응답 요약 및 신용 회계에 대해 알아보세요.

배치 이름, 이메일 및 사용자 이름

POST /gender/batch는 API 키 액세스가 있는 1~50개의 항목 또는 IP 평가판이 있는 최대 10개의 항목이 포함된 items 배열을 허용합니다. 이름, 이메일 주소, 사용자 이름 또는 이 세 가지를 혼합하여 보내세요. 각 항목에는 별도의 country, forceToGenderize 및 options 필드가 있습니다. ID는 선택사항이지만 배치 내에서 고유해야 합니다.

결과는 입력 순서를 따릅니다. 각 결과에는 index, charged_credits 및 정확히 data 또는 error 중 하나가 포함됩니다. id를 제공한 경우에도 반환됩니다. HTTP 200 응답에는 개별 항목에 대한 실패가 포함될 수 있으므로 모든 결과를 확인하십시오. meta.summary에는 total, succeeded, identified, unknown 및 failed가 포함됩니다. 알려진 성별 없이 완료된 예측은 여전히 성공한 것으로 간주되며 크레딧이 필요합니다.

요청 검증 또는 계획이 실패하면 크레딧이 차감되기 전에 전체 배치가 거부됩니다. 실행 중에 모든 항목이 실패하면 API는 data 어레이 및 레거시 별칭 results를 사용하여 2xx가 아닌 문제 응답을 반환합니다. 실패한 항목은 환불 확인 후 크레딧 비용이 0이 됩니다. 청구가 확인되지 않은 경우 각 항목에 대해 보고된 비용이 최종적이라고 가정하지 마십시오.

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

모든 예측 요청은 재시도를 포함하여 청구 가능한 새로운 작업입니다. 이러한 예제는 자동으로 재시도하지 않습니다. 다른 요청을 보내기 전에 청구 상태를 확인하세요.

실행하기 전: 액세스 및 오류 처리

서버에서 다음 예제를 실행하세요. 프로세스 환경에서 GENDERAPI_API_KEY를 기존 API 키로 설정합니다. meta.access.mode가 api_key인지 확인하세요. 인식되지 않은 키는 IP 평가판으로 대체될 수 있습니다.

HTTP 4xx 및 5xx JSON 응답의 경우 예제에서는 오류 본문을 유지하고 0이 아닌 상태로 종료됩니다. 다시 시도하기 전에 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": "Onur",
      "country": "TR"
    },
    {
      "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
    }
  ]
}'

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 = {
  "items": [
    {
      "id": "contact-1",
      "type": "name",
      "value": "Onur",
      "country": "TR"
    },
    {
      "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+; 내장된 가져오기. 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\":\"Onur\",\"country\":\"TR\"},{\"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":"Onur","country":"TR"},{"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\":\"Onur\",\"country\":\"TR\"},{\"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\":\"Onur\",\"country\":\"TR\"},{\"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\":\"Onur\",\"country\":\"TR\"},{\"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를 실행합니다. 런타임 문서

일괄 응답 읽기

이 독립적인 합성 예시에는 데이터 세트 일치, 알 수 없는 결과 및 공급자 오류가 포함되어 있습니다. 이는 위 일괄 요청의 예상 출력이 아닌 부분 성공 HTTP 200 응답을 보여줍니다. 성공적인 두 항목의 비용은 각각 1크레딧입니다. 실패한 항목에는 요금이 0으로 확인되었습니다.

예시적인 JSON 응답
{
  "data": [
    {
      "index": 0,
      "id": "known",
      "charged_credits": 1,
      "data": {
        "input": {
          "type": "name",
          "value": "Onur",
          "country": "TR"
        },
        "name": "onur",
        "gender": "male",
        "country": "TR",
        "confidence": 0.9,
        "confidence_kind": "observed_frequency",
        "sample_count": 100,
        "source": "dataset",
        "result_status": "identified",
        "reason": null,
        "country_source": "dataset",
        "match": {
          "name": "onur",
          "method": "normalized",
          "scope": "country",
          "country": "TR"
        }
      }
    },
    {
      "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
    }
  }
}

일괄 크레딧 및 재시도 계획

기존 Bearer API 키로 인증하고 Content-Type: application/json를 보냅니다. 제출된 모든 배치는 새로운 작업입니다. 부분실패를 재시도하는 경우 결제 확인 후 실패한 항목만 제출합니다. 성공한 항목을 다시 보내면 다시 요금이 부과됩니다.

기본적으로 일괄 항목은 off를 사용하며 완료된 예측당 1크레딧이 필요합니다. fallback를 선택하는 데에도 AI를 포함해 총 1크레딧이 필요합니다. always를 선택하려면 2크레딧이 필요합니다. forceToGenderize를 사용하면 데이터세트에서 발견된 성별에 1크레딧이 소요됩니다. AI를 사용하려면 총 2크레딧이 필요합니다. 성별을 알 수 없는 예측을 완료해도 크레딧이 필요합니다. 1크레딧의 시작 잔액이면 배치를 시작하기에 충분합니다. 최종 공제 시 잔액이 마이너스가 될 수 있습니다.