Skip to main content

Data Legion

Data Legion Python SDK

Tests   License: MIT   Python

The official Python client for the Data Legion API.

Installation

pip install datalegion

Quick Start

from datalegion import DataLegion

client = DataLegion(api_key="legion_...")

Or set the DATALEGION_API_KEY environment variable and omit the api_key argument:

client = DataLegion()

Person Enrichment

Look up a person by email, phone, social URL, name, or other identifiers. Returns a PersonResponse with full type hints and dot access.

person = client.person.enrich(email="john@example.com")
print(person.full_name)
print(person.job_title)
print(person.company_name)

# Enrich by name + company
person = client.person.enrich(
    first_name="John",
    last_name="Doe",
    company="Google",
)

# Enrich by LinkedIn URL
person = client.person.enrich(social_url="https://linkedin.com/in/johndoe")

# Enrich a US healthcare provider by NPI (your plan must include NPI)
person = client.person.enrich(npi="1234567893")
print(person.npi, person.npi_last_updated)

Search with exactly one of filters, sql or es_query. limit is optional: without it the API returns one result (max 100).

filters uses the record's own field names, the ones every response carries. A value or a list (any of them), {"gte": ..., "lte": ...} for a range, {"exists": True} for a filled field; every field given must hold.

results = client.person.search(
    filters={"job_title": ["vp of sales", "head of sales"], "state_code": "TX"},
    limit=10,
)
for match in results.matches:
    print(match.person.full_name)

Location fields (city, state, state_code) come with contact data; on a plan without it, a filter on them is refused with a 400.

Combine sets of fields with {"and": [...]}, {"or": [...]} or {"not": {...}}, and search the profile text with a Boolean keywords string (AND, OR, NOT in capitals, "quoted phrases", parentheses):

results = client.person.search(
    filters={
        "and": [
            {"keywords": '("data engineer" OR "analytics engineer") AND python NOT intern'},
            {"or": [{"state_code": "TX"}, {"city": "boston"}]},
        ]
    },
    limit=10,
)

SQL, query objects and cursors

sql takes a SELECT * FROM people WHERE ... statement (no LIMIT or OFFSET: use limit and offset). es_query takes an Elasticsearch-style query object: bool (must, should, filter, must_not), term, terms, match, match_phrase, range, exists, prefix, wildcard and nested, on the response's own field names. The older query argument still works.

results = client.person.search(
    sql="SELECT * FROM people WHERE company_name ILIKE '%google%' AND job_title ILIKE '%engineer%'",
    limit=10,
)
results = client.person.search(
    es_query={"bool": {"filter": [{"term": {"company_name": "google"}}, {"match": {"job_title": "engineer"}}]}},
    limit=100,
)

For deep paging and exports, send each page's next_cursor back as cursor (instead of offset). The last page has no next_cursor. A cursor belongs to one search on one dataset build, so after a new build, start again from the first page.

cursor = None
while True:
    page = client.person.search(filters={"state_code": "OH"}, limit=100, cursor=cursor)
    for match in page.matches:
        print(match.person.legion_id)
    cursor = page.next_cursor
    if not cursor:
        break

Company search takes the same inputs and cursor.

count takes what search takes and returns how many records match, rounded, without returning any. It is free and works with zero credits left: it needs an active plan that includes search, not a balance.

counted = client.person.count(
    filters={"job_title": "nurse practitioner", "company_industry": "hospitals and health care"}
)
print(counted.total, counted.total_status)  # 110000 about

total_status is about (the rounded count), at_least (counting ran out of time: a lower bound) or under (fewer than 10, possibly none). Counts are limited to 10 a minute and 100 an hour (5 and 30 on a free trial), and refuse filters on fields that identify one record (ids, names, emails, phones, URLs, domains, tickers): look one record up with enrich.

Person Discover

Search for people using natural language.

results = client.person.discover(
    query="engineers in San Francisco who worked at Google",
    limit=10,
)
for match in results.matches:
    print(match.person.full_name)

For the next page, send next_cursor back as cursor with the same query: it reruns the same search, past 10,000 results too. Company discover pages the same way.

query = "engineers in San Francisco who worked at Google"
cursor = None
while True:
    page = client.person.discover(query=query, limit=100, cursor=cursor)
    for match in page.matches:
        print(match.person.legion_id)
    cursor = page.next_cursor
    if not cursor:
        break

Company Enrichment

Look up a company by domain, name, LinkedIn ID, or ticker symbol. Returns a CompanyResponse with dot access.

# By domain
company = client.company.enrich(domain="google.com")
print(company.name.cleaned)
print(company.industry)
print(company.legion_employee_count)

# By name
company = client.company.enrich(name="Google")

Search for companies with filters, sql or es_query, as person search does.

results = client.company.search(
    filters={"industry": "software development", "locations.city": "austin", "locations.primary": True},
    limit=10,
)
for match in results.matches:
    print(match.company.name.cleaned)

counted = client.company.count(sql="SELECT * FROM companies WHERE industry = 'banking'")

Company Discover

Search for companies using natural language.

results = client.company.discover(
    query="AI companies with more than 100 employees",
    limit=10,
)
for match in results.matches:
    print(match.company.name.cleaned)

Utilities

Clean & Normalize Fields

cleaned = client.utility.clean(
    fields={
        "email": "John.Doe+tag@gmail.com",
        "phone": "(555) 123-4567",
        "domain": "https://www.Google.com/about",
    }
)
for field, result in cleaned.results.items():
    print(f"{field}: {result.original} -> {result.cleaned}")

Hash Email

hashed = client.utility.hash_email(email="john@example.com")
print(hashed.hashes["sha256"])
print(hashed.hashes["md5"])

Validate Data

validated = client.utility.validate(
    email="john@example.com",
    phone="+15551234567",
    first_name="John",
)
print(validated.valid)
for error in validated.errors:
    print(f"{error.field}: {error.error}")

Report a Data Issue

Report an inaccuracy in a person or company record against its legion_id. Free; see the docs for the issue_type/issue_level rules.

report = client.utility.report_person(
    legion_id="abc123",
    issue_type="incorrect",
    issue_level="field",
    field="job_title",
    observed_value="CEO",
    correct_value="CTO",
)
print(report.report_id, report.status)

Company records use client.utility.report_company() with the same parameters.

Credits

balance = client.credits.balance()
for contract in balance.contracts:
    print(contract.endpoint, contract.credits_remaining)  # "/person" 380.0 (None when unlimited)

Health Check

health = client.health()
print(health.status)

Async Usage

import asyncio
from datalegion import AsyncDataLegion

async def main():
    client = AsyncDataLegion(api_key="legion_...")

    person = await client.person.enrich(email="john@example.com")
    print(person.full_name)

    company = await client.company.enrich(domain="google.com")
    print(company.name.cleaned)

    await client.close()

asyncio.run(main())

Or use as a context manager:

async with AsyncDataLegion(api_key="legion_...") as client:
    person = await client.person.enrich(email="john@example.com")

Response Types

All responses are Pydantic models with full type hints and autocomplete support. Import them directly:

from datalegion import PersonResponse, CompanyResponse, PersonMatchesResponse

Response Headers

After each request, these attributes are updated on the client:

person = client.person.enrich(email="john@example.com")
print(client.request_id)             # unique request ID
print(client.credits_used)           # credits consumed
print(client.credits_remaining)      # credits remaining
print(client.contract_id)            # contract ID
print(client.rate_limit_limit)       # requests quota in current window
print(client.rate_limit_remaining)   # remaining requests in current window
print(client.rate_limit_reset)       # unix timestamp when window resets
print(client.rate_limit_policy)      # rate limit policy (e.g. "100/min")
print(client.retry_after)            # seconds to wait (on 429 responses)
print(client.correlation_id)         # echoed Correlation-ID
print(client.total_count_status)     # search/discover: "exact" | "estimate" | "page"
print(client.search_warning)         # search/discover: why a filter was flagged, or None

On search/discover, total_count_status tells you how the response total was derived: exact (true count), estimate (on broad queries where the exact count runs out of time: the matches counted by then, a lower bound, so read it as "at least"), or page (count unavailable; total is the offset plus the rows returned).

search_warning is set when a search flags one of its filters: for example an industry name that no stored value matches (the page comes back empty without being charged). It says what to change.

Error Handling

from datalegion import (
    DataLegion,
    AuthenticationError,
    InsufficientCreditsError,
    NotFoundError,
    RateLimitError,
    BadRequestError,
    ValidationError,
    APIError,
)

client = DataLegion(api_key="legion_...")

try:
    person = client.person.enrich(email="john@example.com")
except NotFoundError:
    print("No match (no credits used)")
except AuthenticationError as e:
    print(f"Invalid API key: {e.message}")
except InsufficientCreditsError as e:
    print(f"Out of credits: {e.message}")
except RateLimitError as e:
    print(f"Rate limited, retry after {client.retry_after}s: {e.message}")
except (BadRequestError, ValidationError) as e:
    print(f"Invalid request: {e.message}, details: {e.details}")
except APIError as e:
    print(f"API error ({e.status_code}): {e.message}")
Status Exception
400 BadRequestError
401 AuthenticationError
402 InsufficientCreditsError
403 PermissionDeniedError
404 NotFoundError (no match; no credits used)
408 RequestTimeoutError
422 ValidationError
429 RateLimitError
5xx ServerError
other APIError

BadRequestError, PermissionDeniedError, NotFoundError, RequestTimeoutError and ServerError subclass APIError. The client doesn't retry; on a 429, client.retry_after holds the seconds to wait.

All exceptions inherit from DataLegionError and include these attributes:

  • message - Human-readable error message
  • status_code - HTTP status code
  • error - Error type/code from the API
  • details - Additional error details (if any)

Sandbox

Pass sandbox=True to try the SDK without spending credits. Enrichment, Bulk Enrichment, Search and Discover then return sample records (Jane Sandbox, Sandbox Corp) with every field a real record has; the utilities, which are free anyway, call the real API.

client = DataLegion(api_key="legion_...", sandbox=True)
person = client.person.enrich(email="anyone@example.com")
print(person.legion_id)  # "sandbox_person_001"

Sandbox Discover answers only a few fixed example queries; the error lists them.

Configuration

Parameter Default Description
api_key DATALEGION_API_KEY env var Your API key
base_url https://api.datalegion.ai API base URL
timeout 60.0 Request timeout in seconds
sandbox False Return sample records, use no credits
httpx_client None Custom httpx.Client / httpx.AsyncClient

Documentation

For full API documentation, visit https://www.datalegion.ai/docs.

Metadata

Release files for datalegion 0.16.2

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

Source distribution (sdist)

Source distribution for datalegion 0.16.2
File Size Uploaded Provenance Actions
datalegion-0.16.2.tar.gz 27.9 kB Without provenance Details for datalegion-0.16.2.tar.gz

Built distribution (wheel)

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

Total release size: 47.1 kB

Release files / datalegion-0.16.2.tar.gz

Download URL datalegion-0.16.2.tar.gz
Size 27.9 kB
Tags Source
SHA-256 checksum
How to use checksums
14436ca7a345ed66994e283070d55cb4a1c022a1603c0545e3fb57ba15a8df48
BLAKE2b-256 checksum
How to use checksums
63723eaa1b50bee9e56c50901c67def7f514e5c7fb4cdbea29a0d0bf3c07cfeb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / datalegion-0.16.2-py3-none-any.whl

Download URL datalegion-0.16.2-py3-none-any.whl
Size 19.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
32b591752cddf99e72df71da893da427795c4f31e6c40fe6f5867e338b138e6e
BLAKE2b-256 checksum
How to use checksums
538bdea75266f774335bac3eb497a8b2c5516394d207a2a6a31e20e030b66a23
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for datalegion 0.16.2

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