truaddress 1.0.0
Official TruAddress SDK - Address validation, autocomplete, and geocoding
License: MIT
Requires Python: >=3.8
Keywords: address, validation, autocomplete, geocoding, usps

# TruAddress Python SDK

Official Python SDK for [TruAddress](https://truaddress.net) - Address validation, autocomplete, and geocoding API.

## Installation

```bash
pip install truaddress
```

## Quick Start

```python
from truaddress import TruAddress

client = TruAddress(api_key="YOUR_API_KEY")

# Validate a US address
results = client.us_street(
    street="1600 Pennsylvania Ave NW",
    city="Washington",
    state="DC",
    zipcode="20500"
)

if results and TruAddress.is_deliverable(results[0]):
    print("Valid address:", results[0]["delivery_line_1"])
```

## Available Methods

### US Endpoints

#### `us_street()` - US Street Address Validation

```python
results = client.us_street(
    street="350 5th Avenue",
    city="New York",
    state="NY",
    zipcode="10118"
)

print(results[0]["analysis"]["dpv_match_code"])  # 'Y' = Deliverable
print(results[0]["metadata"]["latitude"])        # 40.748535
```

**DPV Match Codes:**
- `Y` - Confirmed deliverable
- `S` - Secondary (apt/suite) missing
- `D` - Secondary invalid
- `N` - Not deliverable

#### `us_zipcode()` - ZIP Code Lookup

```python
# By ZIP code
result = client.us_zipcode(zipcode="90210")
print(result[0]["city_states"][0]["city"])  # 'Beverly Hills'

# By city/state
result = client.us_zipcode(city="Austin", state="TX")
```

#### `us_autocomplete()` - Address Autocomplete

```python
result = client.us_autocomplete(
    search="350 5th Ave",
    max_results=5,
    state_filter=["NY"]
)

for s in result["suggestions"]:
    print(f"{s['street_line']}, {s['city']}, {s['state']} {s['zipcode']}")
```

#### `us_extract()` - Extract Addresses from Text

```python
result = client.us_extract("Ship to: 350 5th Avenue, New York, NY 10118. Thanks!")

print(result["meta"]["address_count"])      # 1
print(result["addresses"][0]["verified"])   # True
```

#### `us_reverse_geo()` - Reverse Geocoding

```python
result = client.us_reverse_geo(
    latitude=40.748535,
    longitude=-73.9856571
)

for r in result["results"]:
    print(f"{r['address']['street']} ({r['distance']:.0f}m away)")
```

### International Endpoints

#### `intl_street()` - International Address Validation

```python
results = client.intl_street(
    country="GBR",
    freeform="10 Downing Street, London"
)

print(results[0]["components"]["postal_code"])  # 'SW1A 2AB'
print(TruAddress.is_verified(results[0]))       # True
```

#### `intl_autocomplete()` - International Autocomplete

```python
result = client.intl_autocomplete(
    search="Champs Elysees",
    country="FRA",
    max_results=5
)
```

### Core Endpoints

#### `validate()` - Global Address Validation

```python
results = client.validate(
    country="US",
    address1="350 5th Avenue",
    locality="New York",
    administrative_area="NY",
    postal_code="10118"
)
```

#### `correct()` - Address Correction

```python
results = client.correct(freeform="1600 pennsylvania ave washington dc 20500")
print(results[0]["address1"])  # Corrected address
```

#### `autocomplete()` - Global Autocomplete

```python
result = client.autocomplete(q="Buckingham Palace London", limit=5)
```

## Helper Methods

```python
# Check if US address is deliverable
TruAddress.is_deliverable(result)  # DPV code = 'Y'

# Check if US address is a mail drop (CMRA)
TruAddress.is_cmra(result)

# Check if US address is vacant
TruAddress.is_vacant(result)

# Check if international address is verified
TruAddress.is_verified(result)

# Format addresses as strings
TruAddress.format_us_address(result)    # "350 5th Ave, New York NY 10118"
TruAddress.format_intl_address(result)  # "10 Downing Street, London, SW1A 2AB"
```

## Error Handling

```python
from truaddress import TruAddress, TruAddressError

try:
    results = client.us_street(street="123 Main St")
except TruAddressError as e:
    print(f"Error: {e.message}")
    print(f"Status code: {e.status_code}")
```

## Configuration

```python
client = TruAddress(
    api_key="YOUR_API_KEY",
    base_url="https://truaddress.net"  # Optional: custom base URL
)
```

## Django Integration

```python
# settings.py
TRUADDRESS_API_KEY = os.environ.get("TRUADDRESS_API_KEY")

# views.py
from django.conf import settings
from truaddress import TruAddress

client = TruAddress(api_key=settings.TRUADDRESS_API_KEY)

def validate_address(request):
    results = client.us_street(
        street=request.POST["street"],
        city=request.POST["city"],
        state=request.POST["state"],
        zipcode=request.POST["zipcode"]
    )
    return JsonResponse({"valid": len(results) > 0 and TruAddress.is_deliverable(results[0])})
```

## Flask Integration

```python
from flask import Flask, request, jsonify
from truaddress import TruAddress

app = Flask(__name__)
client = TruAddress(api_key=os.environ["TRUADDRESS_API_KEY"])

@app.route("/validate", methods=["POST"])
def validate():
    data = request.json
    results = client.us_street(**data)
    return jsonify({"valid": len(results) > 0})
```

## Requirements

- Python 3.8+
- requests >= 2.25.0

## License

MIT