Python · Gender prediction
Predict gender from names in Python
The name endpoint returns a prediction object under data with result_status, gender, confidence and a source field that tells you whether the answer came from the dataset or the AI fallback. Passing a country code matters for names such as Andrea, Jean or Kim, which lean differently depending on where someone lives. Python makes it easy to compare the same name across countries, as the script below does.
A result_status of unknown is a normal, successful response, not an exception. Your code should branch on it and read reason, which can be not_found, no_name_candidate, ambiguous or insufficient_evidence. Store unknown as its own value in your analytics tables rather than defaulting to a gender, and keep predictions out of any decision that affects eligibility, pricing or access.
Steps
- 1
Install requests and set FINOWL_API_KEY in your shell or .env file.
- 2
Pass a first name or full name, plus a two-letter country code when you know it.
- 3
Branch on result_status before reading gender, since unknown results have gender set to None.
- 4
Record confidence and source alongside the prediction so analysts can filter low-certainty rows.
pip install requestsimport os
import time
import requests
API_URL = "https://api.finowl.co/v1/gender/name"
HEADERS = {
"Authorization": f"Bearer {os.environ['FINOWL_API_KEY']}",
"Content-Type": "application/json",
}
def predict_gender(name, country=None, attempts=3):
payload = {"name": name}
if country:
payload["country"] = country # ISO 3166-1 alpha-2 hint, any case
for _ in range(attempts):
resp = requests.post(API_URL, json=payload, headers=HEADERS, timeout=10)
if resp.status_code == 200:
return resp.json()["data"]
try:
code = resp.json()["error"]["code"]
except (ValueError, KeyError, TypeError):
code = "unknown_error"
if resp.status_code == 400:
raise ValueError(f"Rejected input for {name!r}: {code}")
if resp.status_code == 401:
raise PermissionError("Unauthorized: check FINOWL_API_KEY")
if resp.status_code == 429 and code == "rate_limited":
time.sleep(int(resp.headers.get("Retry-After", "1")))
continue
raise RuntimeError(f"Finowl returned {resp.status_code}: {code}")
raise RuntimeError("Gave up after repeated rate limiting")
if __name__ == "__main__":
for name, country in [("Andrea", "IT"), ("Andrea", "US"), ("Kim", "KR"), ("Qwzx", None)]:
p = predict_gender(name, country)
label = f"{name} ({country or 'no country'})"
if p["result_status"] == "unknown":
print(f"{label}: unknown, reason={p['reason']}")
continue
print(
f"{label}: {p['gender']} confidence={p['confidence']} "
f"kind={p['confidence_kind']} source={p['source']} country={p['country']}"
)IN PRODUCTION
Production tips
For bulk enrichment in pandas, send up to 50 rows per call to /v1/gender/batch instead of looping over the name endpoint. A batch counts as one request against the rate limit.
Keep the default ai_mode of fallback unless you have a reason to change it. Setting ai_mode to always costs 3 credits per lookup and returns model_reported confidence.
Let people set or correct their own gender in your product. A prediction is a statistical estimate of how a name is typically used, and it will be wrong for some people.
Each lookup costs 1 credit (3 when it requests AI), with 100 free credits every month. See pricing and error codes.
A FEW GOOD QUESTIONS
Common questions
Related guides
- Check email breaches in Python with requests
- Check breached passwords in Python at signup
- Predict gender from a name in Node.js
- Batch gender prediction in TypeScript
- Predict gender from names in Go with net/http
- Predict gender from names in Java 17
- Gender analytics from names for fintech audiences
- Gender insights from names for e-commerce analytics
- Gender estimates for SaaS user research and analytics
Predict gender from names in Python
Grab an API key, paste the example and run it. 100 free credits every month.