Python SDK

PyPI version Python versions License: MIT

Per-endpoint request and response samples are in the API reference.

Installation

Install the package using pip:

pip install neuwo-api

Requirements

Quick Start

REST API Client

from neuwo_api import NeuwoRestClient

# Initialize client
client = NeuwoRestClient(
    token="your-rest-api-token",
    base_url="https://custom.api.com",
)

# Analyze text content
response = client.get_ai_topics(
    content="Cats make wonderful pets for modern households.",
    document_id="article-123",
    headline="Why Cats Make Great Pets"
)

# Access results
print(f"Tags: {len(response.tags)}")
for tag in response.tags:
    print(f"  - {tag.value} (score: {tag.score})")

print(f"Brand Safe: {response.brand_safety.is_safe}")
print(f"IAB Categories: {len(response.marketing_categories.iab_tier_1)}")

EDGE API Client

from neuwo_api import NeuwoEdgeClient

# Initialize client
client = NeuwoEdgeClient(
    token="your-edge-api-token",
    base_url="https://custom.api.com",
    default_origin="https://yourwebsite.com"  # Optional: default origin for requests
)

# Analyze article by URL
response = client.get_ai_topics(url="https://example.com/article")

# Or wait for analysis to complete (with automatic retry)
response = client.get_ai_topics_wait(
    url="https://example.com/article",
    max_retries=10,
    retry_interval=6
)

print(f"Found {len(response.tags)} tags for the article")

Configuration

REST Client Parameters

Parameter Type Default Description
token str Required REST API authentication token
base_url str Required Base URL for the API
timeout int 60 Request timeout in seconds

Example:

client = NeuwoRestClient(
    token="your-token",
    base_url="https://custom.api.com",
    timeout=120
)

EDGE Client Parameters

Parameter Type Default Description
token str Required EDGE API authentication token
base_url str Required Base URL for the API
timeout int 60 Request timeout in seconds
default_origin str None Default Origin header for requests

Example:

client = NeuwoEdgeClient(
    token="your-token",
    base_url="https://custom.api.com",
    default_origin="https://yoursite.com",
    timeout=90
)

API Methods

REST API

Get AI Topics

response = client.get_ai_topics(
    content="Text to analyze",            # Required
    document_id="doc123",                 # Optional: save to database
    lang="en",                            # Optional: ISO 639-1 code
    publication_id="pub1",                # Optional
    headline="Article Headline",          # Optional
    tag_limit=15,                         # Optional: max tags (default: 15)
    tag_min_score=0.1,                    # Optional: min score (default: 0.1)
    marketing_limit=None,                 # Optional
    marketing_min_score=0.3,              # Optional (default: 0.3)
    include_in_sim=True,                  # Optional (default: True)
    article_url="https://example.com"     # Optional
)

Get Similar Articles

articles = client.get_similar(
    document_id="doc123",                 # Required
    max_rows=10,                          # Optional: limit results
    past_days=30,                         # Optional: limit by date
    publication_ids=["pub1", "pub2"]      # Optional: filter by publication
)

Update Article

from datetime import date

article = client.update_article(
    document_id="doc123",                 # Required
    published=date(2024, 1, 15),          # Optional
    headline="Updated Headline",          # Optional
    writer="Author Name",                 # Optional
    category="News",                      # Optional
    content="Updated content",            # Optional
    summary="Summary",                    # Optional
    publication_id="pub1",                # Optional
    article_url="https://example.com",    # Optional
    include_in_sim=True                   # Optional
)

Train AI Topics

training_tags = client.train_ai_topics(
    document_id="doc123",                 # Required
    tags=["tag1", "tag2", "tag3"],        # Required
)

EDGE API

Get AI Topics (Single URL)

response = client.get_ai_topics(
    url="https://example.com/article",    # Required
    origin="https://yoursite.com"         # Optional: override default origin
)

Get AI Topics with Auto-Retry

response = client.get_ai_topics_wait(
    url="https://example.com/article",    # Required
    origin="https://yoursite.com",        # Optional
    max_retries=10,                       # Optional (default: 10)
    retry_interval=6,                     # Optional (default: 6s)
    initial_delay=2                       # Optional (default: 2s)
)

Raw Response Methods

All methods have _raw variants that return the raw requests.Response object:

# REST
raw_response = client.get_ai_topics_raw(content="Text")
print(raw_response.status_code)
print(raw_response.text)

# EDGE
raw_response = client.get_ai_topics_raw(url="https://example.com")
print(raw_response.json())

Error Handling

The SDK provides specific exceptions for different error scenarios:

from neuwo_api import (
    NeuwoRestClient,
    ValidationError,
    AuthenticationError,
    NoDataAvailableError,
    ContentNotAvailableError,
    NetworkError
)

client = NeuwoRestClient(
    token="your-token",
    base_url="https://custom.api.com",
)

try:
    response = client.get_ai_topics(content="Your content here")
except ValidationError as e:
    print(f"Invalid input: {e}")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except NoDataAvailableError as e:
    print(f"Data not yet available: {e}")
except ContentNotAvailableError as e:
    print(f"Content could not be analyzed: {e}")
except NetworkError as e:
    print(f"Network error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

Exception Hierarchy

Logging

The SDK uses Python's standard logging module. Enable logging to see detailed API communication:

from neuwo_api import setup_logger
import logging

# Enable debug logging
setup_logger(level=logging.DEBUG)

# Or just warnings and errors (default)
setup_logger(level=logging.WARNING)

# Disable logging
from neuwo_api import disable_logger
disable_logger()

Custom logging configuration:

import logging
from neuwo_api import get_logger

# Get the SDK logger
logger = get_logger()

# Add custom handler
handler = logging.FileHandler('neuwo_api.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)