Skip to main content
Gender API
Get Free API Key

Python & pandas Guide · API v2

How to predict gender from names in Python: pandas, batches and thresholds

One request per row works for ten names and falls over at a hundred thousand. This is the version for a real DataFrame: deduplicated, batched, retried where a retry helps, and with a probability and a record count on every row so you can decide which answers to trust.

  • 100 free lookups / month
  • Up to 100 names per batch request
  • EU servers in Germany · DPA available

Last reviewed 2026-12-05 Every snippet was run against the API before publishing

  • 100 names / batch JSON array in one POST
  • requests / httpx Plain HTTP or official SDK
  • 0-credit format check POST /v2/name-format-detect
  • EU / Germany German servers & GDPR DPA

The short answer

  • POST the names to /v2/gender as a JSON array — up to 100 per request, each with an id to join the answer back.
  • Deduplicate on name and country first. You pay per distinct name found, and names that are not found cost nothing.
  • Retry timeouts and server errors with a back-off. Do not retry a 400 or a 401 — those need a fix, not a second try.
  • Keep probability and samples as columns and set a cut-off on both, instead of trusting every label.

Offline vs. API

An offline package or an API?

  • Offline: gender-guesser on PyPI

    The usual offline choice is the gender-guesser package on PyPI. It looks names up in a fixed dictionary and returns one of six labels — male, female, mostly_male, mostly_female, andy for androgynous, or unknown — and it can prefer a country such as great_britain. No network, no account, no cost. If your names are common and a label is all you need, that may be enough.

  • API: Gender-API v2 with requests

    Reach for an API when you need what a label cannot carry: a probability and a sample count, so you can set a cut-off; an answer for the country the person lives in; and names that are not in a fixed list. The rest of this page uses the Gender-API endpoint with plain requests. If you only need the call itself, the Python code example is shorter.

Single Lookup

One name

Create a token in your account, then send one POST request:

import requests

response = requests.post(
    "https://gender-api.com/v2/gender",
    headers={"Authorization": "Bearer YOUR_TOKEN"},
    json={"first_name": "Andrea", "country": "IT"},
    timeout=30,
)
print(response.json())
  • probability

    Between 0 and 1, and belongs to the gender returned. Keep it as a column so you can set your own confidence cut-off.

  • samples

    The sample count — how much data the answer rests on. A single-digit value means thin evidence.

  • country

    Without country, Andrea is answered across all countries; with it, Italy says male and Germany says female.

Batch Pipeline

A whole DataFrame

Two functions. The first sends one batch and decides what deserves a retry. The second turns a DataFrame column into batches and merges the answers back.

From a DataFrame to three new columns. The rows are cleaned and reduced to distinct pairs of name and country, sent in chunks of 100 to POST /v2/gender, retried only on timeouts and server errors, and the answers are merged back onto every row as gender, probability and samples. You pay for distinct names found, not for rows.
The whole function in one picture. The deduplication step is where the money is saved.
import time

import pandas as pd
import requests

API_URL = "https://gender-api.com/v2/gender"
BATCH_SIZE = 100  # the most names one request accepts

session = requests.Session()
session.headers["Authorization"] = "Bearer YOUR_TOKEN"


def post_batch(rows, attempts=5):
    """Send up to 100 lookups. Retry only what a retry can fix."""
    for attempt in range(attempts):
        try:
            response = session.post(API_URL, json=rows, timeout=30)
        except (requests.ConnectionError, requests.Timeout):
            response = None

        if response is not None and response.status_code < 500:
            # 400 = something in the request is wrong, 401 = no credits left.
            # Neither gets better by asking again, so stop here.
            response.raise_for_status()
            return response.json()

        if attempt < attempts - 1:
            time.sleep(2 ** attempt)  # 1, 2, 4, 8 seconds

    raise RuntimeError("Gender API not reachable after retries")

The Test run output tab shows the real output of a run with deliberately awkward rows — a duplicate, a leading space, an empty cell, a blank string, a name nobody has, and one longer than the 50 characters the API accepts:

  • Every input row comes back, in its original order, with the same number of rows.
  • Both Andreas in Italy were one lookup, not two.
  • Blank, missing and over-long names never reach the API; unknown names come back empty.
  • The batch crossed a 100-name boundary in the test (150 rows), so the chunking is exercised too.

Error Handling

Errors, retries and credits

Most failures in a long job are one of four cases, and only one of them should be retried.

A batch needs enough credits for every name in it before it runs, but is only charged for the names it finds — one credit each, from €0.35 per 1,000. Credits are bought in advance and are valid for 12 months from your last purchase.

API error responses in batch jobs and how post_batch() handles each
What comes back What it means What the code does
200, one entry has a "status" field That one name was invalid — the rest of the batch answered normally Leaves that row empty and carries on
400 for the whole request Something in the call is wrong: more than 100 entries, a missing or invalid token Raises — fix the call, a retry gives the same answer
401 limit-exceeded Not enough credits left for every name in the batch Raises — top up credits, then rerun
Timeout or 5xx The request did not get through Waits 1, 2, 4, 8 seconds and tries again

Confidence Cut-Offs

Which answers to trust

A probability alone cannot tell a 0.95 resting on five records from a 0.95 resting on a thousand. The sample count can. Two cut-offs give three groups:

Two cut-offs split every result into three groups. A probability of at least 0.9 on at least 20 records: use it. A probability of at least 0.9 on fewer records: confident but thin, review it. Below 0.9 the name is genuinely mixed and gets a neutral fallback — Kim lands there despite tens of thousands of records, because more data does not make a unisex name less unisex.
Example values. The two cut-offs are starting points to measure, not settings to copy.

Do not copy the 0.9 and 20 from this page. Label a few hundred of your own rows by hand and pick the cut-offs from the result — how to measure it walks through the method, with an independent check as a worked example.

  • Confident and well-backed: use the gender.
  • Confident but thin: review it, or treat it as unknown if review is not worth it.
  • Below the probability cut-off: the name is genuinely mixed. Use a neutral salutation — more records will not make Kim less ambiguous.

More Endpoints & Compliance

Beyond first names

  • Only a full name in the column? Send full_name instead of first_name to /v2/gender/by-full-name — the name is split for you and the same one credit applies.
  • Only an e-mail address? Send email to /v2/gender/by-email-address, which extracts the name first. Expect more unknowns: "jsmith84@" hides the name.
  • A one-off list rather than a pipeline? Upload the CSV or Excel file instead — same credits, no code.
  • Every field and error is in the v2 reference; official clients exist for Python and eight other languages.

FAQ

Frequently asked questions

How do I get the gender of a name in Python?

Send a POST request to https://gender-api.com/v2/gender with your token in the Authorization header and {"first_name": "…"} as JSON, for example with requests. The answer carries the gender, a probability between 0 and 1, and a sample count. Add a country code when you know it.

Can I use DataFrame.apply with one request per row?

It works, but it sends one request per row, including every duplicate. Deduplicating on name and country and sending batches of 100 needs a fraction of the requests and only pays for each distinct name once.

How many names can one request contain?

Up to 100. The answers come back in the same order, each with the id you sent, and a single bad entry gets an error object in its own slot without failing the rest of the batch.

What happens to names that are not found?

They come back with result_found set to false and cost no credit. In the DataFrame they stay empty, so they are easy to filter and give a neutral salutation.

Is gender-guesser enough?

For common names, offline, with no budget, it may be. It returns one of six labels from a fixed dictionary. If you need a probability and a record count to set a cut-off on, a country-specific answer, or names outside that dictionary, use a lookup that returns them.

Do I need the official Python client?

No. The client (pip install gender-api-client) wraps the same endpoints; this page uses plain requests so every step — batching, retries, merging — is visible and yours to change.

Get a token and run it

100 free lookups every month — enough to run this page's code on a sample of your own data. Names we do not find cost nothing.

Chat