Python SDK
适用于 Python 3.8+ 的官方 SDK。它执行标准查询(GET /cpf/{cpf}),并以 dict 形式返回 API 的 JSON。CPF 是巴西个人税号。
安装
bash
pip install cpfhub使用 Poetry:
bash
poetry add cpfhub环境要求: Python 3.8+
初始化
Python
import os
from cpfhub import CPFHub
client = CPFHub(api_key=os.environ["CPFHUB_API_KEY"])客户端通过 x-api-key 请求头发送密钥,超时时间为 10 秒。它也可以作为上下文管理器使用,代码块结束时会自动关闭连接:
Python
with CPFHub(api_key=os.environ["CPFHUB_API_KEY"]) as client:
result = client.lookup("12345678909")构造函数参数
| 参数 | 类型 | 说明 |
|---|---|---|
api_key | str | 您的 API 密钥(必填)。为空时抛出 ValueError |
方法
client.lookup(cpf)
查询一个 CPF,并以 dict 形式返回 API 响应体。
Python
result = client.lookup("123.456.789-09")
print(result["data"]["name"]) # "Fulano de Tal"
print(result["data"]["birthDate"]) # "15/06/1990"参数:
| 参数 | 类型 | 说明 |
|---|---|---|
cpf | str | 带或不带格式符号的 CPF |
返回值: 标准查询格式的 dict:
Python
{
"success": True,
"data": {
"cpf": "12345678909",
"name": "Fulano de Tal",
"nameUpper": "FULANO DE TAL",
"gender": "M",
"birthDate": "15/06/1990",
"day": 15,
"month": 6,
"year": 1990,
},
}实时查询和批量查询通过 REST API 调用:POST https://api.cpfhub.io/cpf/realtime 和 POST https://api.cpfhub.io/cpf/bulk。
⚠
请勿使用 client.get_quota()
该包的 1.0.0 版本包含一个 get_quota() 方法,但它调用了错误的地址,无法使用。如需查看余额和套餐,请直接调用 GET https://api.cpfhub.io/quota(不消耗积分)。
错误处理
- CPF 不是 11 位数字:
lookup会在调用 API 之前抛出ValueError(不消耗积分)。 - 4xx 和 5xx 响应:SDK 抛出
httpx.HTTPStatusError。状态码在e.response.status_code中,API 响应体在e.response.json()中。根据状态码不同,error字段可能是文本("..."),也可能是对象({"message": "..."})。
Python
import os
import httpx
from cpfhub import CPFHub
client = CPFHub(api_key=os.environ["CPFHUB_API_KEY"])
try:
result = client.lookup("12345678909")
except httpx.HTTPStatusError as e:
print(e.response.status_code) # 404
print(e.response.json()) # {"success": False, "data": None, "error": {"message": "CPF não encontrado na base de dados"}} (the API replies in Portuguese: "CPF not found in the database")| 状态码 | 原因 |
|---|---|
401 | 缺少 API 密钥或密钥无效 |
403 | 积分已用完或账户被封禁 |
404 | 未查到该 CPF(不消耗积分) |
422 | 校验位错误(不消耗积分) |
429 | 超出每分钟请求限制:等待 Retry-After 请求头中的秒数 |
完整列表见错误码。
集成示例
FastAPI
Python
import os
import httpx
from fastapi import FastAPI, HTTPException
from cpfhub import CPFHub
app = FastAPI()
client = CPFHub(api_key=os.environ["CPFHUB_API_KEY"])
@app.get("/cpf/{cpf}")
def lookup_cpf_route(cpf: str):
try:
return client.lookup(cpf)["data"]
except ValueError:
raise HTTPException(status_code=400, detail="CPF must contain 11 digits")
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
raise HTTPException(status_code=404, detail="CPF not found")
if e.response.status_code == 422:
raise HTTPException(status_code=422, detail="Invalid CPF")
# 401, 403, 429 and 5xx: key, credits or rate limit. Log it and do not expose it to the client.
try:
error_detail = e.response.json()
except ValueError:
error_detail = e.response.text
print("CPFHub.io", e.response.status_code, error_detail)
raise HTTPException(status_code=503, detail="CPF lookup unavailable right now")Django 视图
Python
import os
import httpx
from django.http import JsonResponse
from cpfhub import CPFHub
client = CPFHub(api_key=os.environ["CPFHUB_API_KEY"])
def lookup_cpf_route(request, cpf):
try:
data = client.lookup(cpf)["data"]
return JsonResponse({"name": data["name"], "gender": data["gender"]})
except ValueError:
return JsonResponse({"error": "CPF must contain 11 digits"}, status=400)
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
return JsonResponse({"error": "CPF not found"}, status=404)
if e.response.status_code == 422:
return JsonResponse({"error": "Invalid CPF"}, status=422)
# 401, 403, 429 and 5xx: key, credits or rate limit. Do not expose it to the client.
return JsonResponse({"error": "CPF lookup unavailable right now"}, status=503)表单验证
Python
import os
import httpx
from cpfhub import CPFHub
client = CPFHub(api_key=os.environ["CPFHUB_API_KEY"])
def validate_cpf_onboarding(cpf: str) -> dict:
try:
data = client.lookup(cpf)["data"]
return {"valid": True, "name": data["name"]}
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
return {"valid": False, "name": None}
raise代码仓库与支持
- github.com/cpfhub/cpfhub-python:源代码、问题反馈和贡献
- PyPI: cpfhub:版本列表
更新于 2026 年 10 月 3 日