### Install Perigon SDK Source: https://github.com/goperigon/perigon-python/blob/main/examples/README.md Command to install the Perigon SDK using pip. ```bash pip install perigon ``` -------------------------------- ### Run Basic Example Source: https://github.com/goperigon/perigon-python/blob/main/examples/README.md Command to execute the basic Python example script. ```bash python examples/basic.py ``` -------------------------------- ### Run Advanced Example Source: https://github.com/goperigon/perigon-python/blob/main/examples/README.md Command to execute the advanced Python example script. ```bash python examples/advanced.py ``` -------------------------------- ### Basic Example Output Source: https://github.com/goperigon/perigon-python/blob/main/examples/README.md Example output from the basic Python script, showing search results for articles, companies, and journalists. ```text 🚀 Initializing Perigon API client... 📰 Searching for technology news... Found 1247 articles 1. OpenAI Announces GPT-5 with Revolutionary Capabilities Source: techcrunch.com Published: 2024-12-09T14:30:00Z 🏢 Searching for companies... Found 2 companies - Apple Inc. ID: 12345 Description: Technology company that designs, develops, and sells consumer electronics... 👤 Searching for journalists... Found 2 journalists - John Smith ID: 67890 Bio: Technology journalist covering AI and machine learning developments... ✅ Basic example completed! ``` -------------------------------- ### Example: Get All Topics Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Fetches all available topics from the Perigon taxonomy. ```python # Fetch all available topics topics = api.search_topics(size=1000) print(f"Total topics available: {topics.num_results}") for topic in topics.topics: print(f"- {topic.name} (ID: {topic.id})") ``` -------------------------------- ### Query Syntax Examples Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Search-Methods.md Examples demonstrating various query syntaxes for the search_articles method. ```python # Boolean queries api.search_articles(q="(AI OR artificial intelligence) AND (neural OR deep learning)") # Exact phrases api.search_articles(q='"machine learning" AND "neural networks"') # Wildcards api.search_articles(q="artif*") # Matches artificial, etc. # Multiple filters create AND logic api.search_articles( q="technology", language=["en"], # AND English language country=["US"] # AND US-related ) # Lists create OR logic within parameter api.search_articles( source=["bbc.com", "cnn.com", "nytimes.com"] # OR any of these sources ) # Exclude creates AND-exclude api.search_articles( q="politics", exclude_source=["tabloid1.com", "tabloid2.com"] # NOT from any exclude source ) ``` -------------------------------- ### Advanced Example Output Source: https://github.com/goperigon/perigon-python/blob/main/examples/README.md Example output from the advanced Python script, demonstrating date-filtered searches, vector search, summarization, and async operations. ```text 🚀 Initializing Perigon API client... 📅 Searching articles with date filters... Found 234 articles from the last 7 days 1. Tech Industry Adapts to New AI Regulations Source: techcrunch.com Published: 2024-12-08T09:15:00Z Summary: New regulations are reshaping how tech companies develop AI... 🔍 Using vector search for semantic similarity... Found 3 semantically similar articles 1. Renewable Energy Revolution Accelerates Climate Goals Relevance Score: 0.89 Source: wired.com 📝 Generating article summaries... Generated summary (10 articles analyzed): Artificial intelligence is transforming healthcare through diagnostic tools... 🔄 Running async operations... Running concurrent async searches... ✓ Async articles search: 2 articles ✓ Async companies search: 1 companies ✓ Async journalists search: 1 journalists ✅ Advanced example completed! ``` -------------------------------- ### Table of Actions and Code Examples Source: https://github.com/goperigon/perigon-python/blob/main/README.md Provides a quick reference for common actions and their corresponding code examples. ```python api.search_articles(source=["nytimes.com"]) ``` ```python api.search_articles(q="business", var_from="2025-04-01", to="2025-04-08") ``` ```python api.search_companies(name="Apple", size=5) ``` ```python api.search_summarizer(summary_body=SummaryBody(prompt="Key points"), q="renewable energy", size=20) ``` ```python api.vector_search_articles(article_search_params=ArticleSearchParams(prompt="advancements in AI", size=5)) ``` ```python api.search_topics(size=10) ``` ```python api.search_wikipedia(q="machine learning", size=3, sort_by="relevance") ``` ```python api.vector_search_wikipedia(wikipedia_search_params=WikipediaSearchParams(prompt="artificial intelligence", size=3)) ``` -------------------------------- ### Asynchronous search_articles_async example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Example of using the asynchronous search_articles_async method. ```python import asyncio async def fetch_articles(): results = await api.search_articles_async( q="blockchain", size=10 ) return results results = asyncio.run(fetch_articles()) ``` -------------------------------- ### Example - Custom Summary Prompt Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Example of using a custom prompt to focus the summary on specific aspects. ```python from perigon.models.summary_body import SummaryBody # Custom prompt for specific aspects result = api.search_summarizer( q="artificial intelligence", summary_body=SummaryBody( prompt="What are the main concerns and risks mentioned?" ), size=50 ) print(result.summary) ``` -------------------------------- ### Installation Source: https://github.com/goperigon/perigon-python/blob/main/README.md Install the Perigon Python SDK using pip, poetry, or pipx. ```bash pip install perigon # poetry add perigon # pipx install perigon ``` -------------------------------- ### GET /v1/articles/all Response Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for the GET /v1/articles/all endpoint. ```json { "status": 200, "numResults": 1500, "articles": [ { "url": "https://example.com/article", "title": "Article Title", "description": "Article description...", "content": "Full article content...", "pubDate": "2025-01-15T10:30:00Z", "source": { "name": "Example News", "domain": "example.com" }, "language": "en", "sentiment": { "positive": 0.8, "neutral": 0.1, "negative": 0.1 }, "topics": [ { "name": "Artificial Intelligence", "id": "topic-ai" } ], "companies": [ { "name": "OpenAI", "id": "company-123" } ] } ] } ``` -------------------------------- ### search_sources example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Search-Methods.md Example of searching for news sources/publishers by domain. ```python sources = api.search_sources( domain="example.com", size=10 ) for source in sources.sources: print(f"{source.name} - {source.domain}") ``` -------------------------------- ### Example - Basic Summarization Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Basic example of using the search_summarizer endpoint with a simple query and prompt. ```python from perigon.models.summary_body import SummaryBody # Simple summary with default prompt result = api.search_summarizer( q="renewable energy", summary_body=SummaryBody(prompt="Key developments"), size=20 ) print(result.summary) print(f"Summary based on {result.articles_used} articles") ``` -------------------------------- ### SummaryBody Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/types.md Example usage of SummaryBody. ```python from perigon.models.summary_body import SummaryBody body = SummaryBody( prompt="Key developments in renewable energy" ) result = api.search_summarizer( summary_body=body, q="renewable energy", size=20 ) ``` -------------------------------- ### Exact phrase Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of searching for an exact phrase. ```python results = api.search_articles( q="climate change" ) ``` -------------------------------- ### CreateWatchlistParams Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/types.md Example usage of CreateWatchlistParams to create a watchlist. ```python from perigon.models.create_watchlist_params import CreateWatchlistParams from perigon.models.watchlist_person import WatchlistPerson from perigon.models.watchlist_company import WatchlistCompany params = CreateWatchlistParams( name="Tech Leaders", display_name="Technology Executives", people=[ WatchlistPerson(name="Elon Musk"), WatchlistPerson(name="Satya Nadella") ], companies=[ WatchlistCompany(name="Tesla"), WatchlistCompany(name="Microsoft") ] ) api.create_watchlist(create_watchlist_params=params) ``` -------------------------------- ### Example - Entity-Specific Summary Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Example of generating a summary from articles mentioning specific companies. ```python from perigon.models.summary_body import SummaryBody # Summary of articles mentioning specific companies result = api.search_summarizer( q="quarterly earnings", company_id=["apple_id", "microsoft_id"], summary_body=SummaryBody(prompt="Key earnings highlights"), size=25 ) print(result.summary) ``` -------------------------------- ### Async Support Example Source: https://github.com/goperigon/perigon-python/blob/main/README.md Demonstrates how to use the asynchronous counterparts of the API methods for concurrent calls. ```python import asyncio from perigon import V1Api, ApiClient async def main(): api = V1Api(ApiClient(api_key="YOUR_API_KEY")) # Concurrent API calls articles_task = api.search_articles_async(q="technology", size=5) journalist_task = api.get_journalist_by_id_async(id="123456") # Gather results articles, journalist = await asyncio.gather(articles_task, journalist_task) return articles, journalist # Run the async function articles, journalist = asyncio.run(main()) ``` -------------------------------- ### FastAPI Web Service Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md An example of integrating the Perigon SDK into a FastAPI web service to search for articles. ```python from fastapi import FastAPI from perigon import V1Api, ApiClient app = FastAPI() api = V1Api(ApiClient(api_key="your_key")) @app.get("/search") async def search_articles(query: str, limit: int = 10): results = await api.search_articles_async( q=query, size=limit ) return { "total": results.num_results, "articles": [ { "title": a.title, "source": a.source.name, "published": a.pub_date } for a in results.articles ] } ``` -------------------------------- ### Example: Topic Discovery Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Illustrates discovering and organizing topics by name prefix. ```python # Discover all available topics for filtering topics = api.search_topics(size=500) # Group topics by name prefix (if available) topic_groups = {} for topic in topics.topics: prefix = topic.name.split()[0] if topic.name else "Other" if prefix not in topic_groups: topic_groups[prefix] = [] topic_groups[prefix].append(topic.name) # Display organized topics for prefix, names in sorted(topic_groups.items()): print(f"\n{prefix}:") for name in sorted(names): print(f" - {name}") ``` -------------------------------- ### Story/Cluster Search Response Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for the GET /v1/stories/all endpoint, showing search results for related article clusters. ```json { "status": 200, "numResults": 50, "stories": [ { "id": "story-123", "title": "Major AI Breakthrough", "description": "Multiple articles about new AI...", "numArticles": 156, "latestPubDate": "2025-01-15T15:45:00Z", "earliestPubDate": "2025-01-14T08:00:00Z" } ] } ``` -------------------------------- ### Search Stories Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Demonstrates how to search for news stories and iterate through the results. ```python stories = api.search_stories(q="artificial intelligence", size=5) for story in stories.stories: print(f"Story: {story.id}") ``` -------------------------------- ### Pagination Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md Demonstrates how to retrieve the second page of search results. ```python # Get second page of results results = api.search_articles(q="tech", page=1, size=50) # Page 0 = first page, size = results per page ``` -------------------------------- ### Asynchronous Cleanup Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of asynchronous resource cleanup using `aclose()` for async clients. ```python import asyncio from perigon import ApiClient, V1Api async def main(): client = ApiClient(api_key="key") api = V1Api(client) try: results = await api.search_articles_async(q="test") # Process results finally: await client.aclose() # Close async client asyncio.run(main()) ``` -------------------------------- ### get_story_counts Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Search-Methods.md Example of how to use the get_story_counts method to retrieve article count statistics. ```python stats = api.get_story_counts( q="technology", var_from="2025-01-01", to="2025-02-01" ) print(f"Story statistics: {stats}") ``` -------------------------------- ### Search by name Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Example of searching for companies by name. ```python # Search by name companies = api.search_companies(name="Apple", size=5) for company in companies.companies: print(f"{company.name}: {company.description}") ``` -------------------------------- ### search_wikipedia basic example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Search-Methods.md Basic example of searching for Wikipedia pages. ```python # Basic search results = api.search_wikipedia(q="machine learning", size=5) ``` -------------------------------- ### Multiple languages (OR) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of using list parameters for multiple languages, creating an OR filter. ```python # Multiple languages (OR) results = api.search_articles( language=["en", "es", "fr"] ) # Returns articles in English OR Spanish OR French ``` -------------------------------- ### ArticleSearchParams Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/types.md Example usage of ArticleSearchParams. ```python from perigon.models.article_search_params import ArticleSearchParams params = ArticleSearchParams( prompt="Latest advancements in artificial intelligence", size=10, page=0 ) results = api.vector_search_articles(article_search_params=params) ``` -------------------------------- ### Country-level Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of filtering articles by country. ```python # Country-level results = api.search_articles( country=["US", "GB", "CA"] ) ``` -------------------------------- ### Authentication Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md Shows how to authenticate with the Perigon API using an API key, either directly or from an environment variable. ```python import os from perigon import ApiClient, V1Api # From environment variable api_key = os.environ["PERIGON_API_KEY"] api = V1Api(ApiClient(api_key=api_key)) ``` -------------------------------- ### Search by domain Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Example of searching for companies by domain. ```python # Search by domain companies = api.search_companies(domain=["github.com", "microsoft.com"]) ``` -------------------------------- ### get_story_history Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Search-Methods.md Example of how to use the get_story_history method to retrieve historical data about story clusters. ```python history = api.get_story_history( q="election", var_from="2024-11-01", to="2025-01-31" ) for record in history.records: print(f"Date: {record.date}, Articles: {record.num_articles}") ``` -------------------------------- ### search_people example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Search-Methods.md Example of searching for people entities mentioned in news articles. ```python people = api.search_people(name=["Elon Musk"], size=5) for person in people.people: print(f"{person.name} - {person.organization}") ``` -------------------------------- ### Wildcards in domain filters Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of using wildcards in domain filters to match subdomains. ```python results = api.search_articles( source=["*.cnn.com"] # Match cnn.com and all subdomains ) ``` -------------------------------- ### Example - Summarize Specific Timeframe Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Example of summarizing articles from a specific time range. ```python from perigon.models.summary_body import SummaryBody from datetime import datetime, timedelta # Summarize recent articles past_week = datetime.now() - timedelta(days=7) result = api.search_summarizer( q="climate policy", var_from=past_week, summary_body=SummaryBody(prompt="Recent policy changes"), size=30 ) print(result.summary) ``` -------------------------------- ### Synchronous Cleanup Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of synchronous resource cleanup by closing the API client. ```python from perigon import ApiClient, V1Api client = ApiClient(api_key="key") api = V1Api(client) try: results = api.search_articles(q="test") # Process results finally: client.close() # Always close ``` -------------------------------- ### Make calls (sync and async) Source: https://github.com/goperigon/perigon-python/blob/main/README.md Example of making synchronous and asynchronous calls to search articles and retrieve journalist information. ```python # 🔍 Search recent news articles (sync) articles = api.search_articles(q="artificial intelligence", size=5) print(articles.num_results, articles.articles[0].title) # 👤 Look up a journalist by ID (sync) journalist = api.get_journalist_by_id(id="123456") print(journalist.name) # 🔄 Use async variant for async applications import asyncio async def fetch_data(): # Search articles asynchronously articles = await api.search_articles_async(q="technology", size=5) # Look up journalist asynchronously journalist = await api.get_journalist_by_id_async(id="123456") return articles, journalist # Run in async context articles, journalist = asyncio.run(fetch_data()) ``` -------------------------------- ### Set API Key Environment Variable Source: https://github.com/goperigon/perigon-python/blob/main/examples/README.md Command to set the Perigon API key as an environment variable. ```bash export PERIGON_API_KEY="your-api-key-here" ``` -------------------------------- ### NotFoundException (HTTP 404) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Example of handling a request for a resource that does not exist. ```python from perigon.exceptions import NotFoundException try: journalist = api.get_journalist_by_id(id="nonexistent_id") except NotFoundException as e: print(f"Journalist not found: {e.body}") ``` -------------------------------- ### State-level (US) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of filtering articles by US state. ```python # State-level (US) results = api.search_articles( state=["CA", "NY", "TX"] ) ``` -------------------------------- ### Generate News Summary Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md Generates an AI summary of recent articles related to quantum computing. ```python from perigon.models.summary_body import SummaryBody # Get AI summary of recent articles summary = api.search_summarizer( q="quantum computing", summary_body=SummaryBody(prompt="Latest breakthroughs"), size=50 ) print(summary.summary) ``` -------------------------------- ### Vector Search Articles Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Shows how to perform a semantic vector search on articles using natural language prompts. ```python from perigon.models.article_search_params import ArticleSearchParams results = api.vector_search_articles( article_search_params=ArticleSearchParams( prompt="Latest advancements in artificial intelligence", size=5 ) ) for article in results.articles: print(f"{article.title}") ``` -------------------------------- ### City-level filtering Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of filtering articles by city. ```python # City-level filtering results = api.search_articles( city=["New York", "Los Angeles"] ) ``` -------------------------------- ### Exclude sources (AND remove) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of using exclude parameters to create AND filters, removing articles matching any of the excluded values. ```python # Exclude sources (AND remove) results = api.search_articles( exclude_source=["tabloid1.com", "tabloid2.com"] ) # Returns articles NOT from either tabloid ``` -------------------------------- ### Example: Paginated Topic Retrieval Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Retrieves topics from the Perigon taxonomy in pages. ```python # Get topics in pages all_topics = [] page = 0 page_size = 50 while True: result = api.search_topics(page=page, size=page_size) all_topics.extend(result.topics) if len(result.topics) < page_size: break # No more pages page += 1 print(f"Loaded {len(all_topics)} topics") ``` -------------------------------- ### OpenApiException Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Base exception class for all Perigon SDK exceptions. ```python from perigon.exceptions import OpenApiException try: results = api.search_articles(q="test") except OpenApiException as e: print(f"Perigon API error: {e}") ``` -------------------------------- ### Search by stock symbol Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Example of searching for companies by stock symbol. ```python # Search by stock symbol companies = api.search_companies(symbol=["AAPL", "MSFT"]) ``` -------------------------------- ### Example: Generate multiple summaries concurrently Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Demonstrates how to use search_summarizer_async to generate multiple summaries concurrently using asyncio. ```python import asyncio from perigon.models.summary_body import SummaryBody async def get_summaries(): """Generate multiple summaries concurrently.""" tasks = [ api.search_summarizer_async( q="renewable energy", summary_body=SummaryBody(prompt="Key developments"), size=20 ), api.search_summarizer_async( q="electric vehicles", summary_body=SummaryBody(prompt="Market trends"), size=20 ), ] return await asyncio.gather(*tasks) results = asyncio.run(get_summaries()) for i, result in enumerate(results): print(f"Summary {i+1}:") print(result.summary) print() ``` -------------------------------- ### Example: Using Topics in Article Search Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Demonstrates how to use retrieved topics to filter article searches. ```python # Get available topics topics_result = api.search_topics(size=1000) # Find topics of interest interesting_topics = [ t for t in topics_result.topics if "crypto" in t.name.lower() or "blockchain" in t.name.lower() ] topic_ids = [t.id for t in interesting_topics] # Search articles with those topics results = api.search_articles( q="innovation", topic=topic_ids, size=50 ) print(f"Articles with crypto/blockchain topics: {results.num_results}") ``` -------------------------------- ### Error Handling Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md Demonstrates how to handle various exceptions that may occur during API calls. ```python from perigon.exceptions import ( BadRequestException, UnauthorizedException, ForbiddenException, ServiceException ) try: results = api.search_articles(q="test") except UnauthorizedException: print("Invalid API key") except BadRequestException as e: print(f"Bad query: {e}") except ForbiddenException: print("Feature not available in your plan") except ServiceException: print("API temporarily unavailable, retrying...") import time time.sleep(5) results = api.search_articles(q="test") ``` -------------------------------- ### Get Journalist by ID Response Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for the GET /v1/journalists/{id} endpoint, providing detailed information for a specific journalist. ```json { "id": "jid-123", "name": "Kevin Smith", "organization": "TechNews Daily", "email": "kevin@technewsdaily.com", "phone": "+1-555-0100", "beat": "Technology", "bio": "Senior technology correspondent...", "twitter": "@kevinsmith", "linkedin": "in/kevinsmith", "verified": true } ``` -------------------------------- ### Batch Operations: Create Source Groups Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Example of creating multiple source groups in a batch operation. ```python # Create multiple source groups source_configs = [ ("mainstream_news", ["bbc.com", "cnn.com", "nytimes.com"]), ("tech_news", ["techcrunch.com", "arstechnica.com"]), ("finance_news", ["bloomberg.com", "reuters.com"]) ] for name, sources in source_configs: params = CreateSourceGroupParams( name=name, sources=sources ) api.create_source_group(create_source_group_params=params) ``` -------------------------------- ### Create Watchlist Response Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for a successful watchlist creation. ```json { "id": 123, "name": "Tech Leaders", "status": "created" } ``` -------------------------------- ### Using Source Groups in Searches Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Example of searching articles from specific source groups. ```python # Search articles from specific source groups results = api.search_articles( q="technology", source_group=["tech_sources", "finance_news"] ) ``` -------------------------------- ### Journalist Search Response Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for the GET /v1/journalists/all endpoint, detailing journalist search results. ```json { "status": 200, "numResults": 150, "journalists": [ { "id": "jid-123", "name": "Kevin Smith", "organization": "TechNews Daily", "email": "kevin@technewsdaily.com", "beat": "Technology", "twitter": "@kevinsmith", "linkedin": "in/kevinsmith" } ] } ``` -------------------------------- ### Using Watchlists in Searches (Option 1) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Example of using a watchlist name directly in a search query. ```python # Option 1: Use watchlist name directly results = api.search_articles( q="company news", watchlist=["tech_executives"] ) ``` -------------------------------- ### Company Search Response Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for the GET /v1/companies/all endpoint, showing structured company data. ```json { "status": 200, "numResults": 1, "companies": [ { "id": "company-123", "name": "Apple Inc.", "domains": ["apple.com", "www.apple.com"], "industry": "Technology", "sector": "Hardware & Software", "description": "Apple Inc. designs, manufactures...", "ceo": "Tim Cook", "fullTimeEmployees": 161000, "yearFounded": 1976, "country": "US", "symbols": [ { "symbol": "AAPL", "exchange": "NASDAQ" } ] } ] } ``` -------------------------------- ### Instantiate the client Source: https://github.com/goperigon/perigon-python/blob/main/README.md Create a client instance with your API key. The API key can be provided directly, via an environment variable, or a callable function. ```python from perigon import V1Api, ApiClient # Create client with API key api = V1Api(ApiClient(api_key="YOUR_API_KEY")) # Alternative: environment variable or callable # api = V1Api(ApiClient(api_key=os.environ["PERIGON_API_KEY"])) # api = V1Api(ApiClient(api_key=lambda: get_api_key_from_vault())) ``` -------------------------------- ### Get journalist by ID Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Example of retrieving journalist details by ID. ```python journalist = api.get_journalist_by_id(id="some_journalist_id") print(f"Name: {journalist.name}") print(f"Organization: {journalist.organization}") print(f"Email: {journalist.email}") ``` -------------------------------- ### ConflictException (HTTP 409) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Example of handling a conflict when attempting to create a resource with a name that already exists. ```python from perigon.exceptions import ConflictException try: api.create_watchlist( create_watchlist_params=CreateWatchlistParams( name="Existing Watchlist" # Already exists ) ) except ConflictException as e: print(f"Resource already exists: {e.body}") ``` -------------------------------- ### Monitor Specific Companies Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md Creates a watchlist of tech companies and then searches for articles mentioning them. ```python # Create watchlist of companies from perigon.models.create_watchlist_params import CreateWatchlistParams from perigon.models.watchlist_company import WatchlistCompany watchlist = CreateWatchlistParams( name="tech_giants", companies=[ WatchlistCompany(name="Apple"), WatchlistCompany(name="Microsoft"), WatchlistCompany(name="Google"), ] ) api.create_watchlist(create_watchlist_params=watchlist) # Search articles mentioning these companies results = api.search_articles( q="earnings", watchlist=["tech_giants"] ) ``` -------------------------------- ### BadRequestException Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Raised when the request contains invalid parameters or malformed query. ```python from perigon.exceptions import BadRequestException try: # Example: invalid parameter value results = api.search_articles( positive_sentiment_from=2.0 # Must be 0-1 ) except BadRequestException as e: print(f"Bad request: {e.body}") # Parse error message from e.body to understand what's wrong ``` -------------------------------- ### Search Wikipedia Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Illustrates searching Wikipedia pages with various filters like query, size, sort order, and minimum page views. ```python results = api.search_wikipedia( q="machine learning", size=3, sort_by="relevance", pageviews_from=100 ) for page in results.wiki_pages: print(f"{page.title}") ``` -------------------------------- ### Coordinate-based (within distance from point) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of filtering articles based on geographic coordinates and distance. ```python # Coordinate-based (within distance from point) results = api.search_articles( lat=40.7128, # NYC latitude lon=-74.0060, # NYC longitude max_distance=50 # Within 50 km ) ``` -------------------------------- ### WikipediaSearchParams Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/types.md Example usage of WikipediaSearchParams. ```python from perigon.models.wikipedia_search_params import WikipediaSearchParams params = WikipediaSearchParams( prompt="artificial intelligence and neural networks", pageviews_from=100, size=5 ) results = api.vector_search_wikipedia(wikipedia_search_params=params) ``` -------------------------------- ### Using Watchlists in Searches (Option 2) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Example of resolving a watchlist name to its ID before using it in a search query. ```python # Option 2: Resolve name to ID first resolved = api.resolve_watchlists(name=["tech_executives"]) watchlist_id = resolved["tech_executives"] results = api.search_articles( q="company news", watchlist=[watchlist_id] ) ``` -------------------------------- ### Vector Search Wikipedia Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Demonstrates performing a semantic vector search on Wikipedia using natural language prompts and filters. ```python from perigon.models.wikipedia_search_params import WikipediaSearchParams results = api.vector_search_wikipedia( wikipedia_search_params=WikipediaSearchParams( prompt="artificial intelligence and neural networks", size=3, pageviews_from=100 ) ) ``` -------------------------------- ### Batch Processing Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Demonstrates how to fetch all articles for a query using pagination and batching to handle large-scale operations. ```python def fetch_all_articles(api, query, batch_size=100): """Fetch all articles for a query with pagination.""" all_articles = [] page = 0 while True: results = api.search_articles( q=query, size=batch_size, page=page ) all_articles.extend(results.articles) if len(results.articles) < batch_size: break # No more pages page += 1 return all_articles ``` -------------------------------- ### Semantic/Vector Search Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md Uses a natural language prompt to perform a semantic search for articles. ```python from perigon.models.article_search_params import ArticleSearchParams # Use natural language instead of keywords params = ArticleSearchParams( prompt="Companies investing heavily in renewable energy", size=20 ) results = api.vector_search_articles(article_search_params=params) ``` -------------------------------- ### Companies – fetch structured company data (`/v1/companies`) Source: https://github.com/goperigon/perigon-python/blob/main/README.md Example of searching for companies by name. ```python results = api.search_companies(name="Apple", size=5) ``` -------------------------------- ### ApiException Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Base class for HTTP-related exceptions. Includes status code, reason, body, and headers. ```python from perigon.exceptions import ApiException try: results = api.search_articles(q="test") except ApiException as e: print(f"HTTP Status: {e.status}") print(f"Reason: {e.reason}") print(f"Response Body: {e.body}") print(f"Response Data: {e.data}") print(f"Headers: {e.headers}") ``` -------------------------------- ### Article Deserialization and Serialization Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/types.md Example of deserializing from an API response and serializing back to JSON using the Article model. ```python from perigon.models.article import Article # Deserialize from API response (uses camelCase aliases) article_data = { "title": "Breaking News", "pubDate": "2025-01-15T10:30:00", "articleId": "123456" } article = Article.from_dict(article_data) print(article.pub_date) # Works with both pub_date and pubDate # Serialize back to JSON json_str = article.to_json() ``` -------------------------------- ### OR filter - articles from ANY of these sources Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Demonstrates how list parameters create OR filters by default, including articles matching any of the specified sources. ```python # OR filter - articles from ANY of these sources results = api.search_articles( source=["bbc.com", "theguardian.com", "nytimes.com"] ) # Returns articles from BBC OR Guardian OR Times ``` -------------------------------- ### Stories – discover related article clusters (`/v1/stories`) Source: https://github.com/goperigon/perigon-python/blob/main/README.md Example of searching for related article clusters based on a query. ```python stories = api.search_stories(q="climate change", size=5) ``` -------------------------------- ### UnauthorizedException (HTTP 401) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Example of handling an API authentication failure due to a missing or invalid API key. ```python from perigon.exceptions import UnauthorizedException try: api = V1Api(ApiClient(api_key="invalid_key")) results = api.search_articles(q="test") except UnauthorizedException as e: print("API key is missing or invalid") # Refresh authentication new_key = get_fresh_api_key() api.api_client.api_key = new_key ``` -------------------------------- ### Example - Sentiment-Filtered Summary Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Summarizer-and-Topics.md Example of summarizing only articles with a positive sentiment. ```python from perigon.models.summary_body import SummaryBody # Summarize only positive sentiment articles result = api.search_summarizer( q="tech innovation", positive_sentiment_from=0.7, summary_body=SummaryBody(prompt="Positive developments"), size=20 ) print(result.summary) ``` -------------------------------- ### Basic Usage Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/README.md Initialize the V1Api client and perform a basic article search. ```python from perigon import V1Api, ApiClient # Initialize client with API key api = V1Api(ApiClient(api_key="your_api_key")) # Search articles results = api.search_articles( q="artificial intelligence", size=10, language=["en"] ) print(f"Found {results.num_results} articles") for article in results.articles: print(f"- {article.title}") print(f" Source: {article.source.name}") print(f" Published: {article.pub_date}") ``` -------------------------------- ### search_wikipedia advanced example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Search-Methods.md Example of searching Wikipedia pages with filtering by popularity and sorting. ```python # Filter by popularity and sort results = api.search_wikipedia( q="artificial intelligence", pageviews_from=1000, sort_by="relevance", size=10 ) for page in results.wiki_pages: print(f"{page.title} ({page.pageviews} views)") print(f" {page.summary}") ``` -------------------------------- ### Connection Timeout Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Demonstrates configuring the connection timeout for API client. ```python # Short timeout for quick checks client = ApiClient(api_key="key", timeout=5.0) try: results = api.search_articles(q="test", size=1) except Exception as e: print(f"Timeout or other error: {e}") # Long timeout for comprehensive searches client = ApiClient(api_key="key", timeout=180.0) results = api.search_articles( q="comprehensive search", size=100, show_num_results=True ) ``` -------------------------------- ### Multiple Clients with Different Configurations Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Instantiate multiple ApiClient instances with different configurations for various use cases. ```python from perigon import ApiClient, V1Api # Fast client for simple searches fast_client = ApiClient( api_key="api_key_1", timeout=10.0 ) fast_api = V1Api(fast_client) # Slow client for comprehensive searches slow_client = ApiClient( api_key="api_key_2", timeout=120.0 ) slow_api = V1Api(slow_client) # Use appropriately quick_results = fast_api.search_articles(q="tech", size=5) comprehensive_results = slow_api.search_articles(q="tech", size=100, show_num_results=True) ``` -------------------------------- ### Concurrent Requests Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Shows how to use async methods for making concurrent API calls to fetch articles for multiple queries simultaneously. ```python import asyncio from perigon import ApiClient, V1Api async def fetch_multiple(api, queries): """Fetch articles for multiple queries concurrently.""" tasks = [ api.search_articles_async(q=query, size=10) for query in queries ] return await asyncio.gather(*tasks) client = ApiClient(api_key="key") api = V1Api(client) queries = ["AI", "blockchain", "climate change"] results = asyncio.run(fetch_multiple(api, queries)) ``` -------------------------------- ### Search journalists by name Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Example of searching for journalists by name. ```python results = api.search_journalists(name="Kevin", size=10) for journalist in results.journalists: print(f"{journalist.name} - {journalist.organization}") ``` -------------------------------- ### Context Manager Pattern (Python 3.10+) Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Demonstrates using a context manager for safer asynchronous resource management of the API client. ```python from contextlib import asynccontextmanager from perigon import ApiClient, V1Api @asynccontextmanager async def perigon_client(api_key: str): client = ApiClient(api_key=api_key) api = V1Api(client) try: yield api finally: await client.aclose() # Usage async def main(): async with perigon_client("your_api_key") as api: results = await api.search_articles_async(q="test") return results import asyncio results = asyncio.run(main()) ``` -------------------------------- ### Authentication Header Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example of Bearer token authentication header. ```text Authorization: Bearer {api_key} ``` -------------------------------- ### Summarization Response Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for article summarization. ```json { "status": 200, "summary": "In recent developments, companies are focusing on...", "articlesUsed": 15 } ``` -------------------------------- ### Wrap API Client for Monitoring Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md This example shows how to create a custom API client that wraps the default client to add error handling logic. It defines a `MonitoredV1Api` class that inherits from `V1Api` and includes an `on_error` callback function to handle `ServiceException`. ```python from perigon.exceptions import ServiceException from perigon import V1Api, ApiClient class MonitoredV1Api(V1Api): def __init__(self, api_client, on_error=None): super().__init__(api_client) self.on_error = on_error def search_articles(self, **kwargs): try: return super().search_articles(**kwargs) except ServiceException as e: if self.on_error: self.on_error("search_articles", e) raise def error_handler(method_name, error): # Send alert, update metrics, etc. print(f"Error in {method_name}: {error.status}") api = MonitoredV1Api( ApiClient(api_key="key"), on_error=error_handler ) ``` -------------------------------- ### Mixed/nuanced coverage Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of filtering for articles with mixed or nuanced sentiment. ```python # Mixed/nuanced coverage results = api.search_articles( q="controversial topic", positive_sentiment_from=0.3, positive_sentiment_to=0.7, negative_sentiment_from=0.3, negative_sentiment_to=0.7 ) ``` -------------------------------- ### Neutral coverage Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of filtering for articles with neutral sentiment coverage. ```python # Neutral coverage results = api.search_articles( q="politics", neutral_sentiment_from=0.6, positive_sentiment_to=0.4, negative_sentiment_to=0.4 ) ``` -------------------------------- ### Get Watchlist Async Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Asynchronous version of the get_watchlist method. ```python async def get_watchlist_async(self, id: int) -> dict: pass ``` -------------------------------- ### create_watchlist_async Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Asynchronous variant of `create_watchlist`. ```python async def create_watchlist_async( self, create_watchlist_params: CreateWatchlistParams, ) -> dict: ... import asyncio async def setup_watchlist(): params = CreateWatchlistParams( name="watchlist", people=[WatchlistPerson(name="Alice")], companies=[] ) return await api.create_watchlist_async(create_watchlist_params=params) result = asyncio.run(setup_watchlist()) ``` -------------------------------- ### Strong positive sentiment Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Example of filtering for articles with strong positive sentiment. ```python # Strong positive sentiment results = api.search_articles( q="technology", positive_sentiment_from=0.8 ) ``` -------------------------------- ### Articles – search and filter news (`/v1/all`) Source: https://github.com/goperigon/perigon-python/blob/main/README.md Examples of searching articles with different parameters, including simple queries, date ranges, and source restrictions. ```python # Simple query articles = api.search_articles(q="technology", size=5) # With date range articles = api.search_articles( q="business", var_from="2025-04-01", # Note: 'from' is a reserved keyword in Python to="2025-04-08" ) # Restrict to specific sources articles = api.search_articles(source=["nytimes.com"]) ``` -------------------------------- ### Get Watchlist Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Retrieves detailed information about a specific watchlist by its ID. ```python def get_watchlist(self, id: int) -> dict: pass watchlist = api.get_watchlist(id=123) print(f"Name: {watchlist['name']}") print(f"People: {watchlist.get('people', [])}") print(f"Companies: {watchlist.get('companies', [])}") ``` -------------------------------- ### Pagination Parameters Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Control pagination for search results using 'page' and 'size' parameters. ```python # page: int - Page number (starts at 0) # size: int - Number of results per page results = api.search_articles( q="technology", page=0, # First page size=50 # 50 results per page ) # Navigate to next page next_page = api.search_articles( q="technology", page=1, size=50 ) ``` -------------------------------- ### Delete Source Group Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/Resource-Management.md Example of permanently deleting a source group from the organization. ```python result = api.delete_source_group(id=456) print("Source group deleted") ``` -------------------------------- ### Topics Taxonomy Response Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/endpoints.md Example JSON response for listing available topics. ```json { "status": 200, "numResults": 450, "topics": [ { "id": "topic-markets", "name": "Markets", "score": 1.0 }, { "id": "topic-crypto", "name": "Cryptocurrency", "score": 0.95 } ] } ``` -------------------------------- ### ApiAttributeError Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Raised when accessing a non-existent attribute or invalid field. ```python from perigon.exceptions import ApiAttributeError try: article = results.articles[0] # Access non-existent field invalid_field = article.nonexistent_field except ApiAttributeError as e: print(f"Attribute error: {e}") ``` -------------------------------- ### ApiClient Constructor Parameters Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md The ApiClient constructor takes optional parameters for API key, base URL, and timeout. ```python ApiClient( api_key: Optional[str] = None, base_url: str = "https://api.perigon.io", timeout: Optional[float] = None, ) -> ApiClient ``` -------------------------------- ### ApiValueError Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Raised when a value is invalid or outside acceptable range. ```python from perigon.exceptions import ApiValueError try: # Example: value outside valid range api.search_articles(size=10000) # Max size might be 100 except ApiValueError as e: print(f"Value error: {e}") print(f"Path: {e.path_to_item}") ``` -------------------------------- ### V1Api Constructor Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/api-reference/V1Api.md Instantiates the V1Api client, optionally with a pre-configured ApiClient. ```python from perigon import V1Api, ApiClient # Create with explicit client client = ApiClient(api_key="your_api_key") api = V1Api(client) # Or use default client api = V1Api() api.api_client.api_key = "your_api_key" ``` -------------------------------- ### ApiTypeError Example Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/errors.md Raised when a value has an incorrect type during request validation. ```python from perigon.exceptions import ApiTypeError try: # Example: passing wrong type to parameter api.search_articles(size="not_an_int") # Should be int except ApiTypeError as e: print(f"Type error: {e}") print(f"Path: {e.path_to_item}") print(f"Expected types: {e.valid_classes}") ``` -------------------------------- ### Search Result Formatting - Highlighted Terms Source: https://github.com/goperigon/perigon-python/blob/main/_autodocs/configuration.md Highlight specific search terms in the results using 'show_highlighting' and 'highlight_q'. ```python # Include highlighted search terms results = api.search_articles( q="artificial intelligence", show_highlighting=True, highlight_q="neural networks" # Highlight different terms ) ```