import jsonimport osimport sysimport urllib.errorimport urllib.requestapi_key = os.environ.get("GENDERAPI_API_KEY")if not api_key: raise RuntimeError("Set GENDERAPI_API_KEY")body = json.loads("{\"items\":[{\"id\":\"profile-001\",\"type\":\"username\",\"value\":\"@alice_smith\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"profile-002\",\"type\":\"username\",\"value\":\"alexriver\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"profile-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 Nonerequest = 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.
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\":\"profile-001\",\"type\":\"username\",\"value\":\"@alice_smith\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"profile-002\",\"type\":\"username\",\"value\":\"alexriver\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"profile-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.}
package mainimport ( "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\":\"profile-001\",\"type\":\"username\",\"value\":\"@alice_smith\",\"options\":{\"ai_mode\":\"off\"}},{\"id\":\"profile-002\",\"type\":\"username\",\"value\":\"alexriver\",\"options\":{\"ai_mode\":\"fallback\"}},{\"id\":\"profile-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を実行します。実行環境のドキュメント
リストの結果と再送を扱う
POST /api/v2/gender/batchは、APIキーでは最大50項目、IPトライアルでは最大10項目を受け付けます。type、value、optionsは項目ごとに指定します。通常のAIフォールバックが必要な場合は、各項目でfallbackを明示してください。idはバッチ内で一意である必要があり、indexは送信したバッチ内で0から始まります。自社のジョブIDと元の行のIDは別に保存してください。