prismadata
Cliente Python para la API de inteligencia de ubicación PrismaData
Descargas y Adopción en la Comunidad
Análisis de Salud e Ingeniería (5 Pilares)
1. Gobernanza y Comunidad50 / 200 ▾
2. Metadatos y Empaquetado PEP200 / 200 ▾
3. Seguridad y Cadena de Suministro150 / 200 ▾
4. Documentación, SEO y Ecosistema105 / 200 ▾
5. Ingeniería, CI y Calidad35 / 200 ▾
Documentación Oficial y Guía de Uso — prismadata
Mostrar documentación original completa (README en inglés) ▾
prismadata
Python client for the PrismaData location intelligence API.
Installation
pip install prismadata
With optional extras:
pip install prismadata[pandas] # DataFrame enrichment
pip install prismadata[sklearn] # scikit-learn transformer
pip install prismadata[all] # everything (pandas, sklearn, cache, progress bars)
Quick Start
from prismadata import Client
client = Client(api_key="your-api-key")
# Geocode an address
result = client.geocode(full_address="Av Paulista 1000, Sao Paulo")
print(result["prismadata__geocoder__latitude"], result["prismadata__geocoder__longitude"])
# Query slum proximity
slum = client.slum(lat=-23.56, lng=-46.65)
print(slum["prismadata__slum__favela_distancia_m"])
# Calculate a route
route = client.route([(-23.56, -46.65), (-23.57, -46.66)])
print(route["prismadata__routing_route__distancia_m"])
Authentication
The client supports two authentication methods:
# Using API key
client = Client(api_key="your-api-key")
# Using username and password
client = Client(username="your-user", password="your-pass")
Credentials can also be provided via environment variables:
export PRISMADATA_APIKEY="your-api-key"
# or
export PRISMADATA_USERNAME="your-user"
export PRISMADATA_PASSWORD="your-pass"
# Picks up credentials from environment automatically
client = Client()
If your key lives in a variable with another name, pass its name:
client = Client(api_key_env="MY_PRISMADATA_KEY") # AuthenticationError if unset or empty
Credential resolution order: explicit api_key (or api_key_env) > explicit username/password > PRISMADATA_APIKEY env var > PRISMADATA_USERNAME+PRISMADATA_PASSWORD env vars.
DataFrame Enrichment
import pandas as pd
from prismadata import Client
client = Client(api_key="your-api-key")
df = pd.DataFrame({
"lat": [-23.56, -23.57, -23.58],
"lng": [-46.65, -46.66, -46.67],
})
enriched = client.enrich(df, services=["slum", "personal_income_static", "infosc"])
print(enriched.columns.tolist())
# ['lat', 'lng', 'prismadata__slum__favela_distancia_m', ..., 'prismadata__personal_income_static__percentil_br', ...]
# Use clean_columns=True for shorter column names
client = Client(api_key="your-api-key", clean_columns=True)
enriched = client.enrich(df, services=["slum"])
# Column names: 'slum_favela_distancia_m', 'slum_favela_nome', ...
scikit-learn Pipeline
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from prismadata.sklearn import PrismaDataTransformer
pipe = Pipeline([
("enrich", PrismaDataTransformer(
api_key="your-api-key",
services=["slum", "personal_income_static"],
)),
("model", RandomForestClassifier()),
])
pipe.fit(X_train, y_train)
Async Client
All methods are available asynchronously via AsyncClient:
from prismadata import AsyncClient
async with await AsyncClient.create(api_key="your-api-key") as client:
result = await client.slum(lat=-23.56, lng=-46.65)
print(result)
# Batch and enrichment work the same way
enriched = await client.enrich(df, services=["slum", "personal_income_static"])
Error Handling
from prismadata import Client
from prismadata.exceptions import (
AuthenticationError,
BatchError,
RateLimitError,
PrismaDataError,
)
try:
result = client.slum_batch(large_point_dict)
except BatchError as e:
# Some chunks succeeded, some failed
print(f"Got {len(e.partial_results)} results, {len(e.failed_keys)} failed")
for key, value in e.partial_results.items():
process(key, value) # use what succeeded
retry(e.failed_keys) # retry what failed
except RateLimitError:
print("Rate limit exceeded, wait and retry")
except AuthenticationError:
print("Invalid credentials")
except PrismaDataError as e:
print(f"API error {e.status_code}: {e}")
Available Methods
Geocoding
client.geocode(full_address=..., zipcode=..., city=..., state=...)- Address to coordinatesclient.reverse_geocode(lat, lng)- Coordinates to address
Location Services
client.slum(lat, lng)- Nearest slum/favela proximityclient.prison(lat, lng)- Nearest prison proximityclient.border(lat, lng)- Border proximityclient.infosc(lat, lng)- Census sector infoclient.income_static(lat, lng)- Income percentilesclient.income_pdf(lat, lng, gender=..., age=...)- Detailed income statistics
Commercial Clusters
client.commercial_cluster(lat, lng, top_n=1, ...)- Nearest commercial cluster(s) + streetclient.commercial_cluster(..., include_geometry=True, wkt=False)- Polygon as GeoJSON dict (default) or WKT string whenwkt=True. Requiresviewer:commercial_clusterrole (oradmin); otherwise raisesGeometryNotAuthorizedErrorclient.commercial_cluster_detail(aglomeracao_hash)- Full cluster details + all streetsclient.commercial_cluster_street(lat, lng, radius_m=200)- Nearest street segment (fine granularity)client.commercial_cluster_search(filters=...)- Filter-based search (paginated list)client.commercial_cluster_ranking(criterion="score", scope="national", top_n=50)- Top-N ranking
Routing
client.route(points, profile="car", include_geometry=True)- Route between pointsclient.isochrone(lat, lng, time_limit=600, profile="car")- Reachable areaclient.route_matrix(origin, destinations, profile="car", include_geometry=True)- Distance/time from 1 origin to up to 1024 destinations (sent in chunks of the group limit)
Address Validation
client.compare_address(lat, lng, full_address=...)- Compare address with coordinates (alsostreet_type,street_title, ...)client.validate_address(locations, addresses)- Validate against location historyclient.cluster_locations(locations)- Cluster location history
CNPJ
client.cnpj(cnpj, as_of=None)- Company registration, flat shape (as_of="YYYY-MM-DD"for a past date)client.cnpj_raw(cnpj)- Company registration with partners/CNAEs as listsclient.cnpj_enriched(cnpj, slum=True, ...)- Registration + geo enrichmentclient.cnpj_batch(cnpjs)/client.cnpj_raw_batch(cnpjs)/client.cnpj_batch_enriched(cnpjs, ...)- Batch lookupsclient.cnpj_history(cnpj)/client.cnpj_partners_history(cnpj)- Registration / partner history (since May 2023)client.cnpj_history_batch(cnpjs)/client.cnpj_partners_history_batch(cnpjs)- History in batch (100 / 50 per call)client.cnpj_branches(cnpj, limit=..., offset=..., status=..., lat=..., lng=...)- Head office and branches of the company (same CNPJ root), paginated; withlat/lng, nearest first withdistancia_kmclient.cnpj_events(cnpj)- Field-by-field changes over timeclient.cnpj_diff(cnpj, date_from, date_to)- Changes between two datesclient.cnpjs_at_address(street, city, state, number=..., history=False)- CNPJs registered at an address (history=True: all since May 2023)client.cnpjs_by_partner("PF", name=..., cpf=...)- CNPJs where a partner appears or appearedclient.cnpj_summary(cnpj)- Rule-based text summary and alerts
Social Benefits
client.social_benefits(name, cpf=... or nis=..., as_of=..., purpose=..., origin=...)- Federal social benefits a person receives or received (program, role, period, amount); not found isbeneficiario=False, not an errorclient.social_benefits_batch({id: {"cpf": ..., "name": ...}}, mode="full"|"summary")- Up to 200 per call (split automatically); invalid items come back witherroclient.social_benefits_programs()- Coverage per program
Authentication
client.me()- Authenticated user and tenantclient.change_password(username, current_password, new_password)- Change the password (15-30 chars, upper and lower case)
Account (free, never cached)
client.credits()- Prepaid balance, allowed products and credit packagesclient.credit_debits(date_from=..., date_to=..., page=1)- Prepaid debit statementclient.activities(endpoint=..., status=..., page=1)- API call historyclient.consumption("YYYY-MM")- Requests and cost per product in a monthclient.projection()- Month cost projection; on prepaid, when the balance runs outclient.credit_offers()- Prepaid credit packages on sale (general price table)client.contract_prices()- Postpaid contract prices (needs thebilling:pricesrole)
Batch Operations
client.slum_batch(points)- Batch slum queriesclient.prison_batch(points)- Batch prison queriesclient.border_batch(points)- Batch border queriesclient.infosc_batch(points)- Batch census sector queriesclient.commercial_cluster_batch(points, top_n=1, ...)- Batch commercial cluster queriesclient.route_batch(items, profile="car", geodesic_floor_m=..., direction=...)- Batch routingclient.isochrone_batch(items, profile="car")- Batch isochrones
Aggregator
client.aggregate(lat, lng, services=[...])- Multiple services in one callclient.aggregate_batch(points, services=[...])- Batch aggregationclient.geocode_aggregate(full_address=..., services=[...])- Geocode + aggregate
AI agents (MCP)
For AI agents (Claude.ai, Claude Code or any MCP client) there is the official
PrismaData MCP server at https://mcp.prismadata.io, with the same APIs as tools
and the same billing. See https://prismadata.io/llm/guias/servidor-mcp.md.
Configuration
client = Client(
api_key="your-key",
timeout=30, # Request timeout (seconds)
cache=True, # Enable disk cache (requires diskcache)
cache_ttl=86400, # Cache TTL (seconds)
clean_columns=False, # Keep 'prismadata__' prefix (default)
show_progress=True, # Show tqdm progress bars
app_name="my-app", # Sent as X-App header on every request
)
License
MIT