Metadata-Version: 2.4
Name: dnsaudit
Version: 1.0.0
Summary: Official Python SDK for the DNSAudit API
Home-page: https://github.com/dnsauditio/dnsaudit-python-sdk
Author: Esteban Borges
Author-email: esteban@dnsaudit.io
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Security
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.24.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# DNSAudit Python SDK

The official Python SDK for the [DNSAudit.io](https://dnsaudit.io) API. 

Seamlessly perform comprehensive DNS security audits, detect misconfigurations, bypass caching, and export detailed PDF/JSON reports directly from your Python applications. Built with modern `httpx`, this SDK provides both **Synchronous** and **Asynchronous** execution!

## Installation

You can install the package directly via pip:

```bash
pip install dnsaudit
```

*Requires Python 3.8+*

## Authentication

The SDK requires a DNSAudit API Key. The easiest and most secure way is to set it as an environment variable. The SDK will automatically detect it:

```bash
export DNSAUDIT_API_KEY="your-api-key"
```

Alternatively, you can pass it directly into the Client:
```python
from dnsaudit import Client

client = Client(api_key="your-api-key")
```

## Examples

We provide ready-to-run sample scripts inside the `examples/` directory. If you are new to the SDK, we highly recommend checking out `examples/basic_scan.py` to see how a complete script is structured!

---

## Complete Usage Guide (Synchronous)

The standard `Client` provides a smooth, blocking interface (similar to `requests`). It automatically manages connection pools, so using a `with` block is highly recommended!

### 1. Basic Scanning & Bypassing Cache
By default, the DNSAudit API caches results for 24 hours. You can force a fresh scan by passing `no_cache=True`.

```python
from dnsaudit import Client

with Client() as client:
    # 1. Run a fresh scan (bypasses the 24-hour cache)
    print("Initiating fresh scan...")
    result = client.scan("example.com", no_cache=True)
    
    # The result is a raw Python dictionary containing the full JSON response
    grade = result['grade']['grade']
    score = result['grade']['score']
    print(f"Result for example.com: Grade {grade} (Score: {score})")
```

### 2. Exporting PDF & JSON Reports
You can download full reports programmatically.

```python
from dnsaudit import Client

with Client() as client:
    # Export a beautiful PDF report and save it to your disk
    pdf_bytes = client.export_pdf("example.com")
    with open("security_report.pdf", "wb") as f:
        f.write(pdf_bytes)
    print("Saved security_report.pdf!")

    # Or export the raw JSON data dump
    json_dump = client.export_json("example.com")
    print(f"Total issues found: {len(json_dump.get('issues', []))}")
```

### 3. Viewing Account Scan History
Easily retrieve your past scans.

```python
from dnsaudit import Client

with Client() as client:
    # Fetch the 5 most recent scans on your account
    history = client.get_history(limit=5)
    
    print("Recent Scans:")
    for scan in history.get('scans', []):
        print(f"- {scan['domain']} (Grade: {scan['grade']})")
```

---

## High-Performance Asynchronous Execution

If you are building an async application (e.g., FastAPI, a Discord bot, or a mass-scanning tool), you can use the non-blocking `AsyncClient` to achieve massive concurrency. 

```python
import asyncio
from dnsaudit import AsyncClient

async def mass_scan(domains):
    async with AsyncClient() as client:
        # Create a list of concurrent async tasks
        tasks = [client.scan(domain, no_cache=True) for domain in domains]
        
        # Execute them all simultaneously
        results = await asyncio.gather(*tasks)
        
        for res in results:
            print(f"{res['domain']}: {res['grade']['grade']}")

if __name__ == "__main__":
    target_domains = ["example.com", "github.com", "google.com"]
    asyncio.run(mass_scan(target_domains))
```

---

## Intelligent Rate Limiting

The DNSAudit API strictly enforces daily quotas and burst limits. The Python SDK **automatically handles burst limits (HTTP 429) for you**. 

If you send too many requests too quickly, the SDK will intercept the API's `Retry-After` payload, automatically pause your script for the exact right number of seconds, and seamlessly retry the request. You do not need to write any manual retry logic or `time.sleep()` loops!

## Error Handling

The SDK provides robust custom exception classes so you can easily catch and handle specific errors:

```python
from dnsaudit import Client, AuthenticationError, RateLimitError, APIError, DNSAuditError

try:
    with Client(api_key="invalid-key") as client:
        client.scan("example.com")
        
except AuthenticationError as e:
    print(f"Authentication Failed: Ensure your API key is correct. ({e})")
except RateLimitError as e:
    print(f"Daily quota exceeded! ({e})")
except APIError as e:
    print(f"The server returned an error: {e}")
except DNSAuditError as e:
    print(f"A general SDK error occurred: {e}")
```
