Metadata-Version: 2.5
Name: skrap-ai
Version: 0.1.0
Summary: Official Python SDK for the Skrap.ai API: email verification, email finder, enrichment, bulk jobs, lists and webhooks.
Project-URL: Homepage, https://skrap.ai
Project-URL: Documentation, https://skrap.ai/docs/api
Project-URL: Repository, https://github.com/skrapai/skrap-python
Project-URL: Issues, https://github.com/skrapai/skrap-python/issues
Project-URL: Changelog, https://github.com/skrapai/skrap-python/blob/main/CHANGELOG.md
Author-email: "Infralyon Technology (Skrap.ai)" <contact@skrap.ai>
License-Expression: MIT
License-File: LICENSE
Keywords: api,b2b,email finder,email verification,email verifier,enrichment,sdk,skrap
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.23
Description-Content-Type: text/markdown

# Skrap.ai Python SDK

The official Python library for the [Skrap.ai API](https://skrap.ai/docs/api). Use it to verify email addresses, find work emails, enrich people and companies, run bulk jobs, manage lists and receive webhooks.

- Sync (`Skrap`) and async (`AsyncSkrap`) clients
- One dependency: [`httpx`](https://www.python-httpx.org/)
- Type hints throughout, with `TypedDict` models for every response (`py.typed`)
- Automatic retries with exponential backoff that honour `Retry-After`
- Typed errors that carry the HTTP status, error code and retry hints

## Install

```bash
pip install skrap-ai
```

Requires Python 3.9 or later. The package installs as `skrap-ai` and you import it as `skrap`. You need an API key: create one in the app under **Settings → API keys & MCP** (paid plans).

## Quick start

```python
from skrap import Skrap

client = Skrap(api_key="sk_...")  # or set SKRAP_API_KEY and call Skrap()

# Verify an address
result = client.verify_email("jane@example.com")
print(result["status"])  # valid | risky | invalid | unknown

# Find a work email
found = client.find_email(first_name="Jane", last_name="Doe", domain="example.com")
print(found["emails"][0]["email"] if found["emails"] else "not found")
```

Responses are plain `dict`s that keep the API's own keys (`riskReasons`, `requestId`, ...). Their types are described in `skrap.types`, so editors and type checkers know the fields. Keep API keys on the server.

## Async

```python
import asyncio
from skrap import AsyncSkrap


async def main() -> None:
    async with AsyncSkrap() as client:
        result = await client.verify_email("jane@example.com")
        print(result["status"])


asyncio.run(main())
```

`AsyncSkrap` has the same methods as `Skrap`; you `await` each one, and `iter_results` becomes an `async for`. To cancel a call, cancel its task, for example with `asyncio.wait_for`.

## Configuration

```python
client = Skrap(
    api_key="sk_...",  # default: SKRAP_API_KEY
    base_url="https://api.skrap.ai",  # default: SKRAP_BASE_URL, then https://api.skrap.ai
    timeout=120,  # seconds per attempt (verify and find can take about a minute)
    max_retries=2,  # retries after the first attempt; 0 turns retries off
    max_retry_delay=60,  # longest Retry-After (seconds) the client will wait for
    default_headers={"x-my-trace": "abc"},
    http_client=None,  # your own httpx.Client (proxies, transports); not closed by close()
)
```

You can use the client as a context manager (`with Skrap() as client:`) or call `client.close()` when done. Every method also takes per-request overrides:

```python
client.verify_email(
    "jane@example.com", request_options={"timeout": 30, "max_retries": 0, "headers": {"x-my-trace": "abc"}}
)
```

## Credits

Lookups that come back invalid, unknown or not found are free. If you repeat a verify or find that you already paid for, it is also free while inside your plan's repeat window, and the answer then carries `repeat: {"free": True, "firstChargedAt": ...}`. See [pricing](https://skrap.ai/pricing) and the [credit table](https://skrap.ai/docs/api).

## Methods

### Verify an email

Costs 1 credit when the result is valid or risky.

```python
r = client.verify_email("jane@example.com")
r["status"]  # 'valid' | 'risky' | 'invalid' | 'unknown'
r["retryable"]  # True: unknown for a temporary reason, try again later
r["score"]  # 95 valid, 10-70 risky, 0 invalid, None unknown
r["checks"]  # syntax, mxFound, smtp, catchAll, disposable, roleAccount, freeProvider
r["riskReasons"]  # risky only: catch_all, catch_all_unconfirmed, role_account, disposable
r["didYouMean"]  # typo hint or None
```

### Find a work email

Costs 1 credit when a valid or risky email is found. Give a domain when you have one (best results). Otherwise give a company name.

```python
r = client.find_email(
    first_name="Jane",
    last_name="Doe",  # or full_name="Jane Doe"
    domain="example.com",  # or company="Example Inc" (+ optional location="Austin")
)
r["emails"]  # [{"email": ..., "status": ...}]
r["domainStatus"]
r["requestId"]
```

Some mail servers answer slowly. In that case the first answer has `pendingRefinement: True` and is not charged yet. Wait for the final answer like this:

```python
if r.get("pendingRefinement"):
    final = client.wait_for_find_refinement(r["requestId"], interval=2, timeout=120)
    final["email"], final["status"]
# or poll yourself:
state = client.get_find_refinement(r["requestId"])  # {"ready": bool, "email"?, "status"?, ...}
```

Sometimes a company name matches several companies. Then the answer has `needsCompanyConfirmation: True` and `suggestions` (name, domain, employeeCount). Resend with the domain you mean.

### Enrichment

You are charged only when something is found. Each account can spend up to 5,000 credits a day on enrichment, and the limit resets at midnight UTC. Over the limit, you get a `RateLimitError` with code `ENRICH_DAILY_LIMIT`.

```python
# Who is behind a work email. 2 credits when found (+1 with include_company when the profile is found).
who = client.enrich.reverse_email("jane.doe@example.com", include_company=True)
who["person"]["fullName"]
who["company"]  # the person's current company: name, domain, linkedinUrl
who["companyProfile"]  # full company profile, only with include_company=True

# A LinkedIn profile, plus the work email at the current employer when on record. 1 credit (+1 with email).
p = client.enrich.person("https://www.linkedin.com/in/jane-doe", include_email=True)
p["person"], p["workEmail"]  # workEmail: {"address", "status"} or None

# A company from its domain or LinkedIn page. 1 credit (+1 with include_breakdown).
c = client.enrich.company(domain="example.com", include_breakdown=True)
c["company"]["industry"], c["headcountBreakdown"]["departments"]

# People at a company. 1 credit per person returned (emails included).
team = client.enrich.company_contacts(
    domain="example.com",
    seniority=["vp", "director"],
    department=["sales"],
    country=["US"],
    limit=10,
    page=1,
)
for person in team["people"]:
    print(person["fullName"], person["title"], (person["email"] or {}).get("address"))
```

Every enrichment answer carries `creditsCharged` and `requestId`.

### Bulk jobs

A bulk job takes up to 25,000 rows and runs in the background. Each verify row is charged once, when it settles as valid or risky.

```python
job = client.bulk.verify(["jane@example.com", "john@example.org"], list_name="Q2")
job2 = client.bulk.find(
    [
        {"first_name": "Jane", "last_name": "Doe", "domain": "example.com"},
        {"first_name": "Li", "company": "Acme"},
    ]
)

task = client.tasks.get(job["taskId"])  # status + progress
# poll until completed, failed, cancelled or paused
done = client.tasks.wait(
    job["taskId"],
    interval=5,
    on_progress=lambda t: print(t["progress"]["percentage"]),
)

page = client.tasks.results(job["taskId"], offset=0, limit=50)  # one page
for row in client.tasks.iter_results(job["taskId"]):  # every row
    print(row["email"], row["status"])

csv_text = client.tasks.download(job["taskId"])["csv"]  # results CSV
link = client.tasks.download_url(job["taskId"])["downloadUrl"]  # signed link to the stored file

client.tasks.pause(job["taskId"])
client.tasks.resume(job["taskId"])
client.tasks.cancel(job["taskId"])  # rows already processed stay charged; nothing else is
```

A job also pauses itself when credits run out (`metadata.pauseReason == "insufficient_credits"`). Resume it after a top-up. While a job has no results yet, `tasks.download()` raises a `SkrapError` with code `TASK_PROCESSING` (status 202). Results are kept for 30 days. After that, results and downloads fail with status 410 and code `RESULTS_EXPIRED`. You can also subscribe to the `bulk_job.completed` webhook instead of polling.

### Lists

```python
lists = client.lists.list(kind="prospect")["lists"]  # id, name, kind, leadCount
new = client.lists.create("Q2 outbound", kind="prospect")["list"]  # "prospect" or "company"

client.lists.add_lead(
    new["id"],
    {
        "id": "lead-123",  # your id, unique in the list
        "name": "Jane Doe",
        "company": "Example Inc",
        "email": "jane@example.com",  # required on prospect (people) lists
        "email_status": "valid",  # snake_case or camelCase keys
        "job_role": "CTO",
        "domain": "example.com",
    },
)

client.lists.transfer_leads(new["id"], target_list_id="other-list-id", lead_ids=["lead-123"], mode="move")

export = client.lists.export(ids=[new["id"]], kind="prospect")  # ids defaults to "all"
export["csv"], export["suppressed"]  # do-not-contact leads are left out unless include_suppressed=True
```

Adding a lead whose id or email is already in the list raises `ConflictError` (409).

### Account

```python
me = client.account.get()  # id, email, plan, credits, team, apiKey
```

This call is free, so it works well as a connection test.

### Webhooks

```python
hook = client.webhooks.create("https://example.com/skrap-webhook", ["bulk_job.completed", "credits.low"])
hook["secret"]  # signing secret, returned only once: store it

client.webhooks.list()["webhooks"]
client.webhooks.delete(hook["id"])
client.webhooks.sample("bulk_job.completed")  # example payload (list of one)
```

The events are `bulk_job.completed`, `bulk_job.failed`, `credits.low` and `list.lead_added`. Webhooks are available on paid plans. On a team, only owners and admins can subscribe or remove them.

#### Verify webhook signatures

Pass the raw request body as bytes, exactly as received:

```python
from skrap import WebhookSignatureError, construct_webhook_event


@app.post("/skrap-webhook")  # Flask
def skrap_webhook():
    try:
        event = construct_webhook_event(request.get_data(), request.headers.get("Skrap-Signature"), SECRET)
    except WebhookSignatureError:
        return "bad signature", 400
    # de-duplicate with the Skrap-Event-Id header, then handle event["type"] / event["data"]
    return "ok", 200
```

`verify_webhook_signature(raw_body, header, secret)` returns a bool instead of raising. Both functions reject signatures older than 5 minutes by default; change that with `tolerance=`.

## Errors

Every failure raises a `SkrapError`. Specific cases use these subclasses:

| Class | HTTP | Typical `code` |
| --- | --- | --- |
| `ValidationError` | 400 | `VALIDATION_ERROR`, `UNSUPPORTED_EMAIL` |
| `AuthenticationError` | 401 | `INVALID_API_KEY`, `API_KEY_EXPIRED` |
| `InsufficientCreditsError` | 402 | `INSUFFICIENT_CREDITS`, `MEMBER_CREDIT_LIMIT`, `OVERAGE_LIMIT`, `OVERAGE_BLOCKED` |
| `PermissionDeniedError` | 403 | `PLAN_REQUIRED`, `IP_NOT_ALLOWED`, `FEATURE_NOT_AVAILABLE`, `ACCESS_DENIED`, `AUTHORIZATION_ERROR` |
| `NotFoundError` | 404 | `NOT_FOUND`, `TASK_NOT_FOUND` |
| `ConflictError` | 409 | (duplicate list or lead) |
| `RateLimitError` | 429 | `RATE_LIMITED`, `RATE_LIMIT_EXCEEDED`, `ENRICH_DAILY_LIMIT`, `FREE_ENRICH_LIMIT` |
| `ServerError` | 5xx | `INTERNAL_ERROR`, `ENRICH_UNAVAILABLE`, `CREDIT_CONTENTION` |
| `APIConnectionError` | none | `CONNECTION_ERROR` |
| `APITimeoutError` | none | `TIMEOUT` |

Other statuses, such as 410 `RESULTS_EXPIRED`, raise the base `SkrapError`.

```python
from skrap import InsufficientCreditsError, RateLimitError, SkrapError

try:
    client.verify_email("jane@example.com")
except InsufficientCreditsError as e:
    print(e.details)  # {"required": ..., "available": ..., "shortfall": ...}
except RateLimitError as e:
    print(f"retry in {e.retry_after}s", e.body)  # plan, planName, limitPerMinute, upgrade
except SkrapError as e:
    print(e.status, e.code, e.message, e.retryable, e.request_id)
```

Every `SkrapError` has these fields:

- `status`: the HTTP status, or `None` when no response arrived.
- `code`: the API's error code. Some endpoints, such as list errors, send no code, so it can be `None`.
- `message`
- `retryable`: the API's `retryable` flag when it sends one. Otherwise it is true for 429, 5xx, connection errors and timeouts.
- `retry_after`: in seconds.
- `details`, `body` and `headers`
- `request_id`: currently `None` for most errors, because error responses do not carry a request id.

## Retries

The client retries automatically (2 times by default):

- **429, 500 and 503:** always retried. The API did no work and charged nothing.
- **502, 504, network errors and timeouts:** retried only for calls that are safe to repeat. These are verify, find (a repeat is free) and all reads. Bulk job creation, enrichment, list writes, webhook changes and task controls are not retried after an unknown outcome, so they never run twice.
- **Waiting:** the client waits the `Retry-After` header (or `retryAfterSec`) when the API sends one. Otherwise it backs off exponentially with jitter, from 0.5 s up to 8 s.
- **Long waits:** if the API asks to wait longer than `max_retry_delay` (60 s by default), the client raises right away with `retry_after` set. This happens with the daily enrichment limit, for example.
- **No retry:** a response with `retryable: false` is never retried.

Plan rate limits are per key: Free 30, Professional 120 and Enterprise 600 requests a minute.

## Response details

```python
from skrap import response_meta

r = client.verify_email("jane@example.com")
meta = response_meta(r)
meta.status  # 200
meta.request_id  # x-request-id header, else the body's requestId (find and enrichment), else None
meta.rate_limit  # RateLimitInfo(limit, remaining, reset) from the RateLimit headers, or None
meta.headers
```

## Examples

- [`examples/verify_then_find.py`](examples/verify_then_find.py): verify, then find, with error handling
- [`examples/bulk_verify_async.py`](examples/bulk_verify_async.py): async bulk job, wait, results, CSV
- [`examples/webhook_server.py`](examples/webhook_server.py): receive webhooks and check their signatures

## Documentation

- API reference: https://skrap.ai/docs/api
- Webhooks: https://skrap.ai/docs/webhooks
- OpenAPI: https://skrap.ai/openapi.json

## License

MIT. See [LICENSE](LICENSE).
