Skip to main content

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__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()

Credential resolution order: explicit api_key > 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", "income_static", "infosc"])
print(enriched.columns.tolist())
# ['lat', 'lng', 'prismadata__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: 'favela_distancia_m', '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", "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", "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 coordinates
  • client.reverse_geocode(lat, lng) - Coordinates to address

Location Services

  • client.slum(lat, lng) - Nearest slum/favela proximity
  • client.prison(lat, lng) - Nearest prison proximity
  • client.border(lat, lng) - Border proximity
  • client.infosc(lat, lng) - Census sector info
  • client.income_static(lat, lng) - Income percentiles
  • client.income_pdf(lat, lng, gender=..., age=...) - Detailed income statistics

Commercial Clusters

  • client.commercial_cluster(lat, lng, top_n=1, ...) - Nearest commercial cluster(s) + street
  • client.commercial_cluster(..., include_geometry=True, wkt=False) - Polygon as GeoJSON dict (default) or WKT string when wkt=True. Requires viewer:commercial_cluster role (or admin); otherwise raises GeometryNotAuthorizedError
  • client.commercial_cluster_detail(aglomeracao_hash) - Full cluster details + all streets
  • client.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") - Route between points
  • client.isochrone(lat, lng, time_limit=600, profile="car") - Reachable area
  • client.route_matrix(origin, destinations, profile="car") - Distance/time from 1 origin to up to 1024 destinations

Address Validation

  • client.compare_address(lat, lng, full_address=...) - Compare address with coordinates (also street_type, street_title, ...)
  • client.validate_address(locations, addresses) - Validate against location history
  • client.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 lists
  • client.cnpj_enriched(cnpj, slum=True, ...) - Registration + geo enrichment
  • client.cnpj_batch(cnpjs) / client.cnpj_raw_batch(cnpjs) / client.cnpj_batch_enriched(cnpjs, ...) - Batch lookups
  • client.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=...) - Head office and branches of the company (same CNPJ root), paginated
  • client.cnpj_events(cnpj) - Field-by-field changes over time
  • client.cnpj_diff(cnpj, date_from, date_to) - Changes between two dates
  • client.cnpjs_at_address(street, city, state, number=...) - CNPJs registered at an address
  • client.cnpjs_by_partner("PF", name=..., cpf=...) - CNPJs where a partner appears or appeared
  • client.cnpj_summary(cnpj) - Rule-based text summary and alerts

Account (free, never cached)

  • client.credits() - Prepaid balance, allowed products and credit packages
  • client.credit_debits(date_from=..., date_to=..., page=1) - Prepaid debit statement
  • client.activities(endpoint=..., status=..., page=1) - API call history
  • client.consumption("YYYY-MM") - Requests and cost per product in a month
  • client.projection() - Month cost projection; on prepaid, when the balance runs out
  • client.credit_offers() - Prepaid credit packages on sale (general price table)
  • client.contract_prices() - Postpaid contract prices (needs the billing:prices role)

Credit

  • client.precatory(cpf_cnpj=...) - Credit summary (precatorios/RPVs)
  • client.precatory_detail(cpf_cnpj=...) - Detailed credit list

Batch Operations

  • client.slum_batch(points) - Batch slum queries
  • client.prison_batch(points) - Batch prison queries
  • client.border_batch(points) - Batch border queries
  • client.infosc_batch(points) - Batch census sector queries
  • client.commercial_cluster_batch(points, top_n=1, ...) - Batch commercial cluster queries (up to 1024 points)
  • client.route_batch(items, profile="car") - Batch routing
  • client.isochrone_batch(items, profile="car") - Batch isochrones

Aggregator

  • client.aggregate(lat, lng, services=[...]) - Multiple services in one call
  • client.aggregate_batch(points, services=[...]) - Batch aggregation
  • client.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

Metadata

Release files for prismadata 0.24.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for prismadata 0.24.1
File Size Uploaded Provenance Actions
prismadata-0.24.1.tar.gz 74.6 kB Without provenance Details for prismadata-0.24.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for prismadata 0.24.1
File Interpreter ABI Platform Actions
prismadata-0.24.1-py3-none-any.whl Python 3 none any Details for prismadata-0.24.1-py3-none-any.whl

Total release size: 155.3 kB

Release files / prismadata-0.24.1.tar.gz

Download URL prismadata-0.24.1.tar.gz
Size 74.6 kB
Tags Source
SHA-256 checksum
How to use checksums
243c5813c143315d3b410a1583540026242f74f13a2a162369c6864ddcb7aa4b
BLAKE2b-256 checksum
How to use checksums
556d07493915508324fc03ef4c3970da90fe656bfb5026d7b1a37a6b72084bee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.13.18 Linux/6.12.113+

Release files / prismadata-0.24.1-py3-none-any.whl

Download URL prismadata-0.24.1-py3-none-any.whl
Size 80.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ff0be3643a15e02d11e8ff569e5d363b2b2e80dee465a2f4cbc8e8c6e3da6dd1
BLAKE2b-256 checksum
How to use checksums
138deccb369dd6079790a0655f946320c7d0b6353a05f3a5c3f4e9ca34400f9a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.13.18 Linux/6.12.113+

Security for prismadata 0.24.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page