### Substack CLI Usage Examples Source: https://github.com/nhagar/substack_api/blob/master/docs/installation.md Examples of how to use the `substack` command-line tool after installation. Refer to the CLI Guide for comprehensive documentation. ```bash substack --help ``` ```bash substack quickstart ``` -------------------------------- ### Quickstart guide Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Prints a concise reference guide that covers all available CLI commands and options. ```bash substack quickstart ``` -------------------------------- ### Run Quickstart Guide via CLI Source: https://github.com/nhagar/substack_api/blob/master/README.md Run the quickstart guide for a full command reference of the Substack API CLI. ```bash substack quickstart ``` -------------------------------- ### Other Commands Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Utility commands including handle resolution, quickstart guide, and version information. ```APIDOC ## Other Commands ### Resolve a renamed handle ```bash substack resolve-handle ``` Checks if a Substack user handle has been renamed and returns the new handle. ### Quickstart ```bash substack quickstart ``` Prints a concise reference guide covering all CLI commands and options. ### Version ```bash substack version ``` ``` -------------------------------- ### Install Substack API Library Source: https://github.com/nhagar/substack_api/blob/master/README.md Install the substack-api library using pip or uv. ```bash pip install substack-api ``` ```bash uv add substack-api ``` -------------------------------- ### Install Substack API from PyPI Source: https://github.com/nhagar/substack_api/blob/master/docs/installation.md Use this command to install the library using pip. This is the recommended method for most users. ```bash pip install substack-api ``` -------------------------------- ### Get Author Profile Setup Date Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Access the 'profile_set_up_at' attribute of an author object to find out when their profile was created. This requires an author object to be selected. ```python author.profile_set_up_at ``` -------------------------------- ### Install Substack API from Source Source: https://github.com/nhagar/substack_api/blob/master/docs/installation.md Install the library directly from its source code repository. This is useful for development or when you need the latest unreleased changes. ```bash git clone https://github.com/nhagar/substack_api.git cd substack_api pip install -e . ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/nhagar/substack_api/blob/master/README.md Installs the necessary development dependencies for the project using pip. This command is used to set up the environment for testing and development. ```bash # Install dev dependencies pip install -e ".[dev]" ``` -------------------------------- ### Get Basic User Information Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Access core user profile attributes like ID, name, and profile setup date directly from the User object. ```python # Get basic user information print(f"User ID: {user.id}") print(f"Name: {user.name}") print(f"Profile created: {user.profile_set_up_at}") ``` -------------------------------- ### Get user info Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Fetches the complete user profile data for a given username. ```bash substack user info ``` -------------------------------- ### Profile Setup Date Property Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Retrieve the date when the user's profile was initially set up. ```APIDOC ## Profile Set Up Date ### Description Get the date when the user's profile was set up. ### Property `profile_set_up_at` -> str ``` -------------------------------- ### Get CLI version Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Displays the current version of the substack CLI. ```bash substack version ``` -------------------------------- ### Initialize and Use Newsletter Object Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Demonstrates how to create a Newsletter object and retrieve recent posts, search for posts, get podcasts, authors, and recommendations. ```python from substack_api import Newsletter # Create a newsletter object newsletter = Newsletter("https://example.substack.com") # Get recent posts recent_posts = newsletter.get_posts(limit=10) # Search for posts on a specific topic search_results = newsletter.search_posts("artificial intelligence") # Get podcast episodes podcasts = newsletter.get_podcasts() # Get newsletter authors authors = newsletter.get_authors() # Get recommended newsletters recommendations = newsletter.get_recommendations() ``` -------------------------------- ### Get user subscriptions Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Lists all newsletters a given user is subscribed to. ```bash substack user subscriptions ``` -------------------------------- ### Substack API Quick Start Source: https://github.com/nhagar/substack_api/blob/master/docs/index.md Demonstrates basic usage for fetching newsletter posts, user subscriptions, post content, and newsletters by category. Authentication is required for paywalled content. ```python from substack_api import Newsletter, User, Post, Category, SubstackAuth # Get information about a newsletter newsletter = Newsletter("https://example.substack.com") posts = newsletter.get_posts(limit=5) # Get information about a user user = User("username") subscriptions = user.get_subscriptions() # Get information about a post post = Post("https://example.substack.com/p/post-slug") content = post.get_content() # Browse newsletters by category tech_category = Category(name="Technology") tech_newsletters = tech_category.get_newsletters() # Access paywalled content with authentication auth = SubstackAuth(cookies_path="cookies.json") authenticated_post = Post("https://example.substack.com/p/paywalled-post", auth=auth) paywalled_content = authenticated_post.get_content() ``` -------------------------------- ### Get newsletter recommendations Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Returns a list of newsletter URLs that are recommended by the specified newsletter. ```bash substack newsletter recs ``` -------------------------------- ### Get post content Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Retrieves the HTML body content and URL for a given post. ```bash substack post content ``` -------------------------------- ### Get User Subscriptions via CLI Source: https://github.com/nhagar/substack_api/blob/master/README.md Look up a user's Substack subscriptions using the CLI. ```bash substack user subscriptions username ``` -------------------------------- ### Authenticated GET Request Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/auth.md Make an authenticated GET request to a given URL. ```APIDOC ## Authenticated GET Request ### Description Make an authenticated GET request to a given URL. ### Method ```python get(url: str, **kwargs) -> requests.Response ``` ### Parameters #### Path Parameters - **url** (str) - Required - The URL to request - **kwargs** - Optional - Additional arguments passed to requests.get #### Returns - `requests.Response`: The response object ### Request Example ```python response = auth.get("https://example.substack.com/api/v1/posts/123") data = response.json() ``` ``` -------------------------------- ### Get Recommended Newsletters Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Fetch a list of recommended publications related to the current newsletter. ```python # Get recommended newsletters recommendations = newsletter.get_recommendations() for rec in recommendations: print(f"Recommended: {rec.url}") ``` -------------------------------- ### Get Recommendations Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Retrieves a list of recommended publications associated with the current newsletter. ```APIDOC ## get_recommendations ### Description Get recommended publications for this newsletter. ### Method Newsletter.get_recommendations ### Returns - `List[Newsletter]`: List of recommended Newsletter objects ``` -------------------------------- ### Get Post Metadata via CLI Source: https://github.com/nhagar/substack_api/blob/master/README.md Fetch metadata for a specific Substack post using the CLI. Use --pretty for human-readable output. ```bash substack post metadata https://example.substack.com/p/my-post --pretty ``` -------------------------------- ### Check Paywall Status and Get Content Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/post.md Determine if a post is paywalled and retrieve its HTML content. For paywalled posts, authentication is necessary. ```python # Check if the post is paywalled if post.is_paywalled(): print("This post is paywalled") # Set up authentication to access paywalled content auth = SubstackAuth(cookies_path="cookies.json") authenticated_post = Post("https://example.substack.com/p/post-slug", auth=auth) content = authenticated_post.get_content() else: # Public content - no authentication needed content = post.get_content() print(f"Content length: {len(content) if content else 0}") ``` -------------------------------- ### Run Tests Source: https://github.com/nhagar/substack_api/blob/master/README.md Executes the project's test suite using pytest. Ensure development dependencies are installed before running this command. ```bash # Run tests pytest ``` -------------------------------- ### Get Post Content Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb This snippet demonstrates how to retrieve the full content of a selected post using the `get_content()` method. ```python print(post.get_content()) ``` -------------------------------- ### Get Podcasts Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Retrieves podcast posts from the newsletter, with an option to limit the number of results. ```APIDOC ## get_podcasts ### Description Get podcast posts from the newsletter. ### Method Newsletter.get_podcasts ### Parameters #### Query Parameters - **limit** (Optional[int]) - Optional - Maximum number of podcast posts to return ### Returns - `List[Post]`: List of Post objects representing podcast posts ``` -------------------------------- ### Get Newest Newsletter Posts via CLI Source: https://github.com/nhagar/substack_api/blob/master/README.md Retrieve the 5 newest posts from a Substack newsletter using the CLI. ```bash substack newsletter posts https://example.substack.com --limit 5 ``` -------------------------------- ### Get newsletter podcasts Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Retrieves podcast URLs from a newsletter. Supports limiting the number of results. ```bash substack newsletter podcasts [--limit N] ``` -------------------------------- ### Get Newsletter Recommendations Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Fetches a list of recommended newsletters. This is useful for discovering new content or for integration into recommendation systems. ```python finance_newsletter.get_recommendations() ``` -------------------------------- ### Get post metadata Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Fetches the complete metadata dictionary for a specific post URL. The `--pretty` option can be used for formatted JSON output. ```bash substack post metadata ``` ```bash substack post metadata https://example.substack.com/p/my-post --pretty ``` -------------------------------- ### Get Posts Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Retrieves posts from a Substack newsletter, with options for sorting and limiting the results. ```APIDOC ## get_posts ### Description Get posts from the newsletter with specified sorting. ### Method Newsletter.get_posts ### Parameters #### Query Parameters - **sorting** (str) - Required - Sorting order for the posts ("new", "top", "pinned", or "community") - **limit** (Optional[int]) - Optional - Maximum number of posts to return ### Returns - `List[Post]`: List of Post objects ``` -------------------------------- ### Get Podcast Episodes Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Fetch a list of podcast episodes from a newsletter. The limit parameter specifies the maximum number of podcasts to retrieve. ```python # Get podcast episodes podcasts = newsletter.get_podcasts(limit=2) for podcast in podcasts: metadata = podcast.get_metadata() print(f"Podcast: {metadata['title']}") ``` -------------------------------- ### Get User Subscriptions Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Retrieve a list of newsletters that the user is subscribed to, including publication domain information. ```python # Get the user's subscriptions subscriptions = user.get_subscriptions() ``` -------------------------------- ### Handle Authentication Errors Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/auth.md Implement error handling for SubstackAuth initialization, specifically checking the `authenticated` status and catching potential exceptions during setup. This helps diagnose issues with the cookies file or other configuration problems. ```python from substack_api import SubstackAuth try: auth = SubstackAuth(cookies_path="cookies.json") if not auth.authenticated: print("Authentication failed - check your cookies file") except Exception as e: print(f"Error setting up authentication: {e}") ``` -------------------------------- ### Manually Resolve User Handle Redirects Source: https://github.com/nhagar/substack_api/blob/master/README.md Provides an example of using the `resolve_handle_redirect` function to manually find the current handle for a potentially renamed user account. ```python from substack_api import resolve_handle_redirect new_handle = resolve_handle_redirect("oldhandle") if new_handle: print(f"Handle was renamed to: {new_handle}") ``` -------------------------------- ### Get Post Metadata Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/post.md Retrieve metadata for a post, such as title and publication date. The `force_refresh` parameter can be used to bypass the cache. ```python # Get post metadata metadata = post.get_metadata() print(f"Title: {metadata['title']}") print(f"Published: {metadata['post_date']}") ``` -------------------------------- ### Get Raw Author Data Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Retrieves the raw data associated with an author. This is useful for inspecting all available details about an author. ```python author.get_raw_data() ``` -------------------------------- ### Access Paywalled Posts with Authentication Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Use an authenticated Newsletter object to retrieve and access content from paywalled posts. This requires prior authentication setup. ```python # Example: Using authentication with newsletter to access paywalled posts # from substack_api import Newsletter # authenticated_newsletter = Newsletter("https://example.substack.com", auth=auth) # paywalled_posts = authenticated_newsletter.get_posts(limit=5) # for post in paywalled_posts: # if post.is_paywalled(): # content = post.get_content() # Now accessible with auth # print(f"Paywalled content length: {len(content) if content else 0}") ``` -------------------------------- ### Get Raw User Data Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Retrieves the complete raw user data for a given user. Allows forcing a data refresh. ```APIDOC ## Get Raw User Data ### Description Get the complete raw user data. ### Method `get_raw_data(force_refresh: bool = False) -> Dict[str, Any]` ### Parameters #### Query Parameters - `force_refresh` (bool) - Optional - Whether to force a refresh of the data, ignoring the cache ### Returns - `Dict[str, Any]` - Full user profile data ``` -------------------------------- ### Chat Error Handling Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/chat.md Provides an example of how to handle common exceptions that may occur when interacting with the chat API, such as authentication issues, access denial, or not found errors. ```python from substack_api import Chat, SubstackAuth from substack_api.chat import ( ChatAuthenticationRequired, ChatAccessDenied, ChatNotFound, ThreadNotFound, ) auth = SubstackAuth(cookies_path="cookies.json") chat = Chat(4906951, auth=auth) try: threads = chat.get_threads() except ChatAuthenticationRequired: print("Authentication required - check your cookies") except ChatAccessDenied: print("You don't have access to this chat") except ChatNotFound: print("Publication not found") ``` -------------------------------- ### Get Author Subscriptions Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Retrieve a list of all publications an author is subscribed to. This method returns a list of dictionaries, each containing publication details. ```python author.get_subscriptions() ``` -------------------------------- ### Initialize and Use Post Object Source: https://github.com/nhagar/substack_api/blob/master/README.md Shows how to initialize a Post object and retrieve its metadata and HTML content. ```python from substack_api import Post # Initialize a post by its URL post = Post("https://example.substack.com/p/post-slug") # Get post metadata metadata = post.get_metadata() # Get the post's HTML content content = post.get_content() ``` -------------------------------- ### Read Messages within Chat Threads Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Demonstrates how to retrieve threads from a publication's chat and then read individual messages within a specific thread. Requires prior authentication setup. ```python from substack_api import Chat, SubstackAuth auth = SubstackAuth(cookies_path="cookies.json") chat = Chat(4906951, auth=auth) # Get threads and read messages threads = chat.get_threads(limit=1) if threads: thread = threads[0] messages = thread.get_messages() for msg in messages: print(f"[{msg.created_at}] {msg.author['name']}: {msg.body[:60]}...") ``` -------------------------------- ### Get Raw User Data Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Fetch the complete, unprocessed user profile data from the API. This method can optionally force a refresh, bypassing the cache. ```python # Get raw user data user_data = user.get_raw_data() ``` -------------------------------- ### Get Post Metadata with Python Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Use the `get_metadata()` method on a post object to retrieve detailed information about a specific post. This includes details like canonical URL, publication date, title, and more. ```python post.get_metadata() ``` -------------------------------- ### Initialize and Use User Object Source: https://github.com/nhagar/substack_api/blob/master/README.md Shows how to initialize a User object by username and retrieve profile information, user ID, name, and subscriptions. ```python from substack_api import User # Initialize a user by their username user = User("username") # Get user profile information profile_data = user.get_raw_data() # Get user ID and name user_id = user.id name = user.name # Get user's subscriptions subscriptions = user.get_subscriptions() ``` -------------------------------- ### Get Threads from Chat Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/chat.md Retrieves threads from a publication's chat. Use 'limit' to control the number of threads and 'force_refresh' to fetch new data. ```python get_threads(limit: Optional[int] = None, force_refresh: bool = False) -> List[ChatThread] ``` -------------------------------- ### Make Manual Authenticated Requests Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/auth.md Utilize the `get` and `post` methods of the SubstackAuth object for making direct authenticated HTTP requests to Substack API endpoints. Pass any necessary parameters or JSON data. ```python from substack_api import SubstackAuth auth = SubstackAuth(cookies_path="cookies.json") # Make authenticated GET request response = auth.get("https://example.substack.com/api/v1/posts/123") data = response.json() # Make authenticated POST request response = auth.post( "https://example.substack.com/api/v1/some-endpoint", json={"key": "value"} ) ``` -------------------------------- ### Initialize Post with Authentication Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/post.md Create a Post object directly with authentication details for accessing paywalled content. This approach works for both public and paywalled posts. ```python # Alternative: Create post with authentication from the start auth = SubstackAuth(cookies_path="cookies.json") authenticated_post = Post("https://example.substack.com/p/paywalled-post", auth=auth) content = authenticated_post.get_content() # Works for both public and paywalled content ``` -------------------------------- ### Get Authors Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Retrieves a list of authors for the newsletter. ```APIDOC ## get_authors ### Description Get authors of the newsletter. ### Method Newsletter.get_authors ### Returns - `List[User]`: List of User objects representing the authors ``` -------------------------------- ### Get Newsletter Authors Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Retrieve a list of authors associated with the newsletter. ```python # Get newsletter authors authors = newsletter.get_authors() for author in authors: print(f"Author: {author.name}") ``` -------------------------------- ### Initialize and Use Newsletter Object Source: https://github.com/nhagar/substack_api/blob/master/README.md Demonstrates initializing a Newsletter object and fetching recent posts, top posts, search results, podcasts, recommendations, and authors. ```python from substack_api import Newsletter # Initialize a newsletter by its URL newsletter = Newsletter("https://example.substack.com") # Get recent posts (returns Post objects) recent_posts = newsletter.get_posts(limit=5) # Get posts sorted by popularity top_posts = newsletter.get_posts(sorting="top", limit=10) # Search for posts search_results = newsletter.search_posts("machine learning", limit=3) # Get podcast episodes podcasts = newsletter.get_podcasts(limit=5) # Get recommended newsletters recommendations = newsletter.get_recommendations() # Get newsletter authors authors = newsletter.get_authors() ``` -------------------------------- ### Initialize Post Object Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/post.md Instantiate a Post object with the URL of the Substack post. Authentication is optional and required for paywalled content. ```python from substack_api import Post, SubstackAuth # Create a post object post = Post("https://example.substack.com/p/post-slug") ``` -------------------------------- ### Get Newsletters Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/category.md Retrieves a list of Newsletter objects for all newsletters within this category. ```APIDOC ## get_newsletters() -> List[Newsletter] ### Description Get Newsletter objects for all newsletters in this category. ### Returns - `List[Newsletter]`: List of Newsletter objects ``` -------------------------------- ### Instantiate User Object Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Create a User object to access profile information. By default, it follows handle redirects. Set `follow_redirects` to False to disable this behavior. ```python from substack_api import User # Create a user object (automatically handles redirects) user = User("username") # Create a user object without redirect handling user_no_redirect = User("username", follow_redirects=False) ``` -------------------------------- ### Create and Use User Object Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Instantiate a User object to access user information. The `follow_redirects` parameter can be set to `False` if a handle has been renamed and you do not want to follow the redirect. ```python from substack_api import User # Create a user object user = User("username") # Create a user object without redirect handling (if a handle has been renamed) user = User("username", follow_redirects=False) # Get basic user information user_id = user.id name = user.name # Get the user's subscriptions subscriptions = user.get_subscriptions() # Get raw user data user_data = user.get_raw_data() # Check if the user was redirected (handle was renamed) if user.was_redirected: print(f"Original handle '{user.original_username}' was redirected to '{user.username}'") ``` -------------------------------- ### Get newsletter authors Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Retrieves a list of usernames for the authors of a given newsletter. ```bash substack newsletter authors ``` -------------------------------- ### List and Create Categories Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Demonstrates how to list all available categories and create Category objects by name or ID. Used for discovering newsletters. ```python from substack_api import Category # List all available categories from substack_api.category import list_all_categories categories = list_all_categories() # Create a category object category = Category(name="Technology") # Or by ID category = Category(id=12) # Get newsletters in this category newsletters = category.get_newsletters() # Get full metadata for newsletters in this category newsletter_metadata = category.get_newsletter_metadata() ``` -------------------------------- ### Get Newsletter URLs Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/category.md Retrieves a list of URLs for all newsletters belonging to this category. ```APIDOC ## get_newsletter_urls() -> List[str] ### Description Get only the URLs of newsletters in this category. ### Returns - `List[str]`: List of newsletter URLs ``` -------------------------------- ### Authenticate and Access Paywalled Content Source: https://github.com/nhagar/substack_api/blob/master/README.md Demonstrates setting up authentication using session cookies and accessing paywalled content for both newsletters and individual posts. Also shows how to check if a post is paywalled. ```python from substack_api import Newsletter, Post, SubstackAuth # Set up authentication with your cookies auth = SubstackAuth(cookies_path="path/to/your/cookies.json") # Use authentication with newsletters newsletter = Newsletter("https://example.substack.com", auth=auth) posts = newsletter.get_posts(limit=5) # Can now access paywalled posts # Use authentication with individual posts post = Post("https://example.substack.com/p/paywalled-post", auth=auth) content = post.get_content() # Can now access paywalled content # Check if a post is paywalled if post.is_paywalled(): print("This post requires a subscription") ``` -------------------------------- ### Initialize Newsletter Object Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Instantiate the Newsletter class with the publication URL. Authentication is optional for accessing paywalled content. ```python from substack_api import Newsletter, SubstackAuth # Create a newsletter object newsletter = Newsletter("https://example.substack.com") # Use with authentication for paywalled content auth = SubstackAuth(cookies_path="cookies.json") authenticated_newsletter = Newsletter("https://example.substack.com", auth=auth) ``` -------------------------------- ### Get Newsletter Metadata Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/category.md Retrieves detailed metadata for all newsletters in this category as a list of dictionaries. ```APIDOC ## get_newsletter_metadata() -> List[Dict[str, Any]] ### Description Get full metadata for all newsletters in this category. ### Returns - `List[Dict[str, Any]]`: List of newsletter metadata dictionaries ``` -------------------------------- ### Authenticated access to paywalled content Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Demonstrates how to use the `--cookies` option to authenticate CLI commands for accessing paywalled content. Ensure the cookies file path is correctly specified. ```bash substack --cookies cookies.json post content https://example.substack.com/p/paid-post ``` ```bash substack --cookies cookies.json newsletter posts https://example.substack.com ``` -------------------------------- ### Post Class Initialization Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/post.md Initialize a Post object with the URL of the Substack post. Authentication can be optionally provided for paywalled content. ```APIDOC ## Post Class Definition ```python Post(url: str, auth: Optional[SubstackAuth] = None) ``` ### Parameters - `url` (str): The URL of the Substack post - `auth` (Optional[SubstackAuth]): Authentication handler for accessing paywalled content ``` -------------------------------- ### Create and Use Post Object Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Instantiate a Post object using a post URL to retrieve its content and metadata. You can check if a post is paywalled using the `is_paywalled` method. ```python from substack_api import Post # Create a post object post = Post("https://example.substack.com/p/post-slug") # Get post content content = post.get_content() # Get post metadata metadata = post.get_metadata() # Check if post is paywalled if post.is_paywalled(): print("This post requires a subscription") ``` -------------------------------- ### Get Subscriptions Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Retrieves a list of newsletters that the user is subscribed to, including publication domain information. ```APIDOC ## Get Subscriptions ### Description Get newsletters the user has subscribed to. ### Method `get_subscriptions() -> List[Dict[str, Any]]` ### Returns - `List[Dict[str, Any]]` - List of publications the user subscribes to with domain info ``` -------------------------------- ### Set Up Authentication with SubstackAuth Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Initialize SubstackAuth with a path to your cookies file to enable authentication for accessing paywalled content. This auth object can then be passed to other classes like Newsletter or Post. ```python from substack_api import SubstackAuth # Set up authentication auth = SubstackAuth(cookies_path="cookies.json") # Use with any class that supports authentication newsletter = Newsletter("https://example.substack.com", auth=auth) post = Post("https://example.substack.com/p/paywalled-post", auth=auth) ``` -------------------------------- ### Handle User Account Renames with Automatic Redirects Source: https://github.com/nhagar/substack_api/blob/master/README.md Demonstrates how the User object automatically follows handle redirects by default when a username has changed. It also shows how to check if a redirect occurred. ```python from substack_api import User # This will automatically follow redirects if the handle has changed user = User("oldhandle") # Will find the user even if they renamed to "newhandle" # Check if a redirect occurred if user.was_redirected: print(f"User was renamed from {user.original_username} to {user.username}") ``` -------------------------------- ### Set up Substack API Authentication Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Initialize Substack authentication by providing a path to your cookies.json file. Ensure the cookies file contains valid session cookies. ```python # Example: Setting up authentication (uncomment and provide your own cookies file) # from substack_api import SubstackAuth # auth = SubstackAuth(cookies_path="cookies.json") # print(f"Authentication successful: {auth.authenticated}") ``` -------------------------------- ### Initialize SubstackAuth Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/auth.md Instantiate the SubstackAuth class with the path to your session cookies JSON file. Check the `authenticated` property to verify successful loading. ```python from substack_api import SubstackAuth # Initialize with cookies file auth = SubstackAuth(cookies_path="my_cookies.json") # Check if authentication succeeded if auth.authenticated: print("Successfully authenticated!") else: print("Authentication failed") ``` -------------------------------- ### Check Paywall Status and Authenticate Source: https://github.com/nhagar/substack_api/blob/master/docs/authentication.md First, create a Post object without authentication to check if it's paywalled. If it is, create a new Post object with authentication to access its content. ```python from substack_api import Post # Create post object (no auth needed to check paywall status) post = Post("https://example.substack.com/p/some-post") # Check if authentication is required if post.is_paywalled(): print("This post requires authentication to access full content") # Now add authentication to access content from substack_api import SubstackAuth auth = SubstackAuth(cookies_path="cookies.json") authenticated_post = Post(post.url, auth=auth) content = authenticated_post.get_content() else: # Public content - no authentication needed content = post.get_content() ``` -------------------------------- ### Access Publication Chats with Authentication Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Shows how to set up authentication using cookies and access a publication's chat to retrieve recent threads. Authentication is required for chat access. ```python from substack_api import Chat, SubstackAuth # Set up authentication (required for chat access) auth = SubstackAuth(cookies_path="cookies.json") # Access a publication's chat using its publication ID chat = Chat(4906951, auth=auth) # Get recent threads threads = chat.get_threads(limit=5) for thread in threads: print(f"Thread: {thread.body[:80]}...") print(f" By: {thread.author['name']} on {thread.created_at}") print(f" {thread.comment_count} messages") ``` -------------------------------- ### Get Authors of a Newsletter Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Retrieve a list of authors associated with a specific newsletter. This requires the newsletter object to be previously selected. ```python authors = finance_newsletter.get_authors() ``` -------------------------------- ### Create and Use Category Object Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/category.md Demonstrates how to create a Category object using its name and then retrieve newsletters and metadata associated with that category. This involves initializing the object and calling its methods to fetch related data. ```python from substack_api import Category # Create a category object by name tech_category = Category(name="Technology") print(f"Selected category: {tech_category}") # Get newsletters in this category newsletters = tech_category.get_newsletters() print(f"Found {len(newsletters)} newsletters in {tech_category.name} category") # Print the first 5 newsletters for i, newsletter in enumerate(newsletters[:5]): print(f"{i+1}. {newsletter.url}") # Get detailed metadata metadata = tech_category.get_newsletter_metadata() for entry in metadata[:3]: print(f"Newsletter ID: {entry['id']}") print(f"Description: {entry.get('description', 'No description')[:100]}...") print("-" * 40) ``` -------------------------------- ### Get Messages from ChatThread Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/chat.md Retrieves messages from a chat thread. Supports limiting the number of messages and forcing a data refresh from the API. ```python get_messages(limit: Optional[int] = None, force_refresh: bool = False) -> List[ChatMessage] ``` -------------------------------- ### Create SubstackAuth Object Source: https://github.com/nhagar/substack_api/blob/master/docs/authentication.md Initialize the SubstackAuth object with the path to your cookies file. Check the authentication status to ensure it was successful. ```python from substack_api import SubstackAuth # Initialize with path to your cookies file auth = SubstackAuth(cookies_path="path/to/your/cookies.json") # Check if authentication was successful if auth.authenticated: print("Authentication successful!") else: print("Authentication failed - check your cookies file") ``` -------------------------------- ### Get Author Name Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Access the 'name' attribute of an author object to retrieve their display name. This requires an author object to be selected. ```python author.name ``` -------------------------------- ### Authentication Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Instructions on how to use cookies for authenticated access to paywalled content. ```APIDOC ## Authentication To access paywalled content from the CLI, pass `--cookies` before the command: ```bash substack --cookies cookies.json post content https://example.substack.com/p/paid-post substack --cookies cookies.json newsletter posts https://example.substack.com ``` See the [Authentication Guide](authentication.md) for details on obtaining cookies. ``` -------------------------------- ### User Class Initialization Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/user.md Initializes a User object to access Substack user profiles. It can optionally follow redirects for renamed handles. ```APIDOC ## User Class ### Description Provides access to Substack user profiles and handles renamed Substack handles by following redirects. ### Method `User(username: str, follow_redirects: bool = True)` ### Parameters #### Path Parameters - `username` (str) - Required - The Substack username - `follow_redirects` (bool) - Optional - Whether to follow redirects when a handle has been renamed (default: True) ``` -------------------------------- ### Get Recent Posts Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/newsletter.md Retrieve a list of recent posts from a newsletter. The limit parameter controls the maximum number of posts returned. ```python # Get recent posts recent_posts = newsletter.get_posts(limit=5) for post in recent_posts: metadata = post.get_metadata() print(f"Post: {metadata['title']}") ``` -------------------------------- ### Use Authentication with Post Objects Source: https://github.com/nhagar/substack_api/blob/master/docs/authentication.md Create an authenticated Post object by providing the SubstackAuth instance. This enables fetching content for paywalled posts. ```python from substack_api import Post, SubstackAuth # Set up authentication auth = SubstackAuth(cookies_path="cookies.json") # Create authenticated post post = Post("https://example.substack.com/p/paywalled-post", auth=auth) # Check if post is paywalled if post.is_paywalled(): print("This post is paywalled") # Get content (will use authentication if needed) content = post.get_content() ``` -------------------------------- ### Global Options Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Global options that can be applied to most substack CLI commands. ```APIDOC # Global Options | Option | Description | |--------|-------------| | `--pretty` | Pretty-print JSON output with indentation | | `--cookies PATH` | Path to a cookies JSON file for authenticated access to paywalled content | ``` -------------------------------- ### Browse Categories via CLI Source: https://github.com/nhagar/substack_api/blob/master/README.md Browse Substack categories and newsletters within a category using the CLI. ```bash substack categories ``` ```bash substack category newsletters --name Technology ``` -------------------------------- ### Get Specific Thread by ID Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/chat.md Retrieves a specific chat thread using its unique UUID. This method is useful for accessing individual conversation threads. ```python get_thread(thread_id: str) -> ChatThread ``` -------------------------------- ### Select a Post Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb This snippet shows how to select a specific post from a collection, likely for further processing. ```python post = posts[0] ``` -------------------------------- ### Post Commands Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Commands for interacting with individual Substack posts, including fetching metadata, content, and checking paywall status. ```APIDOC ## Post Commands ### Get metadata ```bash substack post metadata ``` Returns the full metadata dictionary for a post. ### Get content ```bash substack post content ``` Returns the post URL and its HTML body content. ### Check paywall status ```bash substack post paywalled ``` Returns whether the post is paywalled. ``` -------------------------------- ### Git Workflow for Contributions Source: https://github.com/nhagar/substack_api/blob/master/README.md Standard Git commands for contributing to the project. This includes forking the repository, creating a feature branch, committing changes, and pushing to the remote branch to open a Pull Request. ```bash # Fork the repository # Create your feature branch (git checkout -b feature/amazing-feature) # Commit your changes (git commit -m 'Add some amazing feature') # Push to the branch (git push origin feature/amazing-feature) # Open a Pull Request ``` -------------------------------- ### Get newsletter posts Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Retrieves a list of post URLs from a given newsletter URL. Supports sorting by new, top, pinned, or community posts, and limiting the number of results. ```bash substack newsletter posts [--sort new|top|pinned|community] [--limit N] ``` ```bash # Get the 5 newest posts substack newsletter posts https://example.substack.com --limit 5 ``` ```bash # Get top posts substack newsletter posts https://example.substack.com --sort top --limit 10 ``` -------------------------------- ### SubstackAuth Initialization Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/auth.md Initialize the SubstackAuth class with the path to your session cookies file. ```APIDOC ## SubstackAuth Initialization ### Description Initialize the `SubstackAuth` class with the path to your session cookies file. ### Method ```python SubstackAuth(cookies_path: str) ``` ### Parameters #### Path Parameters - **cookies_path** (str) - Required - Path to the JSON file containing session cookies ### Request Example ```python from substack_api import SubstackAuth auth = SubstackAuth(cookies_path="my_cookies.json") ``` ``` -------------------------------- ### Get newsletters in a category Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Retrieves newsletter URLs within a specified category, identified by name or ID. The `--metadata` flag can be used to fetch full newsletter metadata instead. ```bash substack category newsletters --name [--metadata] ``` ```bash substack category newsletters --id [--metadata] ``` ```bash # By name substack category newsletters --name Technology ``` ```bash # By ID with full metadata substack category newsletters --id 42 --metadata --pretty ``` -------------------------------- ### Handle Chat Errors with Specific Exceptions Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Illustrates how to use try-except blocks to handle specific exceptions that may occur when accessing publication chats, such as authentication issues or not found errors. ```python from substack_api import Chat, SubstackAuth from substack_api.chat import ChatAuthenticationRequired, ChatAccessDenied, ChatNotFound auth = SubstackAuth(cookies_path="cookies.json") chat = Chat(4906951, auth=auth) try: threads = chat.get_threads() except ChatAuthenticationRequired: print("Authentication required - check your cookies") except ChatAccessDenied: print("You don't have access to this chat") except ChatNotFound: print("Publication not found") ``` -------------------------------- ### Reading Messages in a Thread Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/chat.md Shows how to retrieve the first chat thread and then iterate through its messages. It also demonstrates how to check for media attachments within messages. ```python from substack_api import Chat, SubstackAuth auth = SubstackAuth(cookies_path="cookies.json") chat = Chat(4906951, auth=auth) # Get threads and read messages threads = chat.get_threads(limit=1) if threads: thread = threads[0] messages = thread.get_messages() for msg in messages: print(f"[{msg.created_at}] {msg.author['name']}: {msg.body[:60]}...") # Check for media attachments if msg.media_attachments: print(f" Attachments: {len(msg.media_attachments)}") ``` -------------------------------- ### Basic Chat Usage Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/chat.md Demonstrates how to authenticate and retrieve recent chat threads from a publication. Ensure you have a valid `cookies.json` file for authentication. ```python from substack_api import Chat, SubstackAuth # Set up authentication (required for chat access) auth = SubstackAuth(cookies_path="cookies.json") # Access a publication's chat (using publication ID) chat = Chat(4906951, auth=auth) # Get recent threads threads = chat.get_threads(limit=5) for thread in threads: print(f"Thread: {thread.body[:80]}...") print(f" By: {thread.author['name']} on {thread.created_at}") print(f" {thread.comment_count} messages") ``` -------------------------------- ### Access Paywalled Content with Authentication Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md To access paywalled content, you must provide authentication using `SubstackAuth`. This involves specifying the path to your cookies file. ```python from substack_api import Post, SubstackAuth # Set up authentication auth = SubstackAuth(cookies_path="cookies.json") # Create authenticated post post = Post("https://example.substack.com/p/paywalled-post", auth=auth) # Now you can access paywalled content content = post.get_content() ``` -------------------------------- ### Error Handling for Authentication Source: https://github.com/nhagar/substack_api/blob/master/docs/authentication.md Implement a try-except block to handle potential FileNotFoundError if the cookies file is missing. If authentication fails, proceed with public access. ```python from substack_api import SubstackAuth, Post try: # Attempt to load authentication auth = SubstackAuth(cookies_path="cookies.json") if not auth.authenticated: print("Warning: Authentication failed, using public access only") auth = None # Use authentication if available post = Post("https://example.substack.com/p/some-post", auth=auth) content = post.get_content() if content is None and post.is_paywalled(): print("This content is paywalled and requires authentication") except FileNotFoundError: print("Cookies file not found - using public access only") post = Post("https://example.substack.com/p/some-post") content = post.get_content() ``` -------------------------------- ### User Commands Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Commands for retrieving information about Substack users and their subscriptions. ```APIDOC ## User Commands ### Get user info ```bash substack user info ``` Returns the full user profile data. ### Get subscriptions ```bash substack user subscriptions ``` Returns the list of newsletters the user is subscribed to. ``` -------------------------------- ### Access Publication Chats with Authentication Source: https://github.com/nhagar/substack_api/blob/master/README.md Demonstrates how to access publication subscriber chats, requiring authentication. It shows fetching threads and messages within a thread. ```python from substack_api import Chat, SubstackAuth # Set up authentication (required for chat access) auth = SubstackAuth(cookies_path="cookies.json") # Access a publication's chat using its publication ID chat = Chat(4906951, auth=auth) # Get recent threads threads = chat.get_threads(limit=5) for thread in threads: print(f"Thread: {thread.body[:80]}...") print(f" By: {thread.author['name']} on {thread.created_at}") print(f" {thread.comment_count} messages") # Get messages in thread for msg in thread.get_messages(): print(f" [{msg.created_at}] {msg.author['name']}: {msg.body[:60]}...") ``` -------------------------------- ### Select an Author Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Select the first author from the list of authors. This is useful for examining a specific author's details. ```python author = authors[0] ``` -------------------------------- ### Access Paywalled Content with Authentication Source: https://github.com/nhagar/substack_api/blob/master/docs/user-guide.md Shows how to authenticate with the Substack API using cookies to access paywalled newsletter content. Ensure your cookies.json file is correctly set up. ```python from substack_api import Newsletter, SubstackAuth # Set up authentication auth = SubstackAuth(cookies_path="cookies.json") # Create authenticated newsletter newsletter = Newsletter("https://example.substack.com", auth=auth) # All retrieved posts will use authentication posts = newsletter.get_posts(limit=10) # Access content from paywalled posts for post in posts: if post.is_paywalled(): content = post.get_content() # Now accessible with auth print(f"Paywalled content: {content[:100]}...") ``` -------------------------------- ### Category Class Initialization Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/category.md Initializes a Category object, optionally by providing a category name or ID. ```APIDOC ## Category(name: Optional[str] = None, id: Optional[int] = None) ### Description Represents a Substack newsletter category. ### Parameters - `name` (Optional[str]): The name of the category - `id` (Optional[int]): The ID of the category ### Raises - `ValueError`: If neither name nor id is provided, or if the provided name/id is not found ``` -------------------------------- ### Use Authentication with Newsletter Objects Source: https://github.com/nhagar/substack_api/blob/master/docs/authentication.md Create an authenticated Newsletter object by passing the SubstackAuth instance. This allows access to paywalled posts when retrieving them. ```python from substack_api import Newsletter, SubstackAuth # Set up authentication auth = SubstackAuth(cookies_path="cookies.json") # Create authenticated newsletter newsletter = Newsletter("https://example.substack.com", auth=auth) # All posts retrieved will use authentication posts = newsletter.get_posts(limit=10) # Access paywalled content for post in posts: if post.is_paywalled(): content = post.get_content() # Now accessible with auth print(f"Paywalled content: {content[:100]}...") ``` -------------------------------- ### List All Substack Categories Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Import and use the `list_all_categories` function to retrieve a list of all available categories on Substack. Each category is returned as a tuple of its name and ID. ```python from substack_api import Category from substack_api.category import list_all_categories ``` ```python categories = list_all_categories() print(categories) ``` -------------------------------- ### Select a Finance Newsletter Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Select the first newsletter from a list of newsletters. This is useful for focusing on a specific publication. ```python finance_newsletter = newsletters[0] ``` -------------------------------- ### Check post paywall status Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Determines whether a specific post is paywalled. ```bash substack post paywalled ``` -------------------------------- ### List All Newsletters Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb This snippet shows how to retrieve a list of all available newsletters using the Substack API. Ensure the 'newsletters' object is properly initialized before execution. ```python newsletters ``` -------------------------------- ### Access Paywalled Posts Directly with Authentication Source: https://github.com/nhagar/substack_api/blob/master/examples/usage_walkthrough.ipynb Authenticate individual Post objects to access their content, even if paywalled. This method allows for targeted access to specific posts. ```python # Example: Using authentication with individual posts # from substack_api import Post # post_url = "https://example.substack.com/p/some-paywalled-post" # # # Check if post is paywalled without auth # post = Post(post_url) # print(f"Is paywalled: {post.is_paywalled()}") # # # Access with authentication # authenticated_post = Post(post_url, auth=auth) # content = authenticated_post.get_content() # print(f"Content accessible: {content is not None}") ``` -------------------------------- ### Load Cookies Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/auth.md Load session cookies from the specified file. ```APIDOC ## Load Cookies ### Description Load session cookies from the specified file. ### Method ```python load_cookies() -> bool ``` #### Returns - `bool`: True if cookies were loaded successfully, False otherwise ``` -------------------------------- ### List all categories Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Returns a list of all available newsletter categories, including their names and IDs. ```bash substack categories ``` -------------------------------- ### Use SubstackAuth with Newsletter and Post Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/auth.md Integrate SubstackAuth with Newsletter and Post classes for authenticated access to newsletter content and specific posts. Ensure the auth object is passed during initialization. ```python from substack_api import Newsletter, Post, SubstackAuth # Set up authentication auth = SubstackAuth(cookies_path="cookies.json") # Use with Newsletter newsletter = Newsletter("https://example.substack.com", auth=auth) posts = newsletter.get_posts(limit=5) # Use with Post post = Post("https://example.substack.com/p/paywalled-post", auth=auth) content = post.get_content() ``` -------------------------------- ### Chat Class Definition Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/chat.md Defines the Chat class constructor, which requires a publication ID and an authentication handler. ```python Chat(publication_id: Union[str, int], auth: SubstackAuth) ``` -------------------------------- ### Newsletter Commands Source: https://github.com/nhagar/substack_api/blob/master/docs/cli.md Commands for interacting with Substack newsletters, including fetching posts, searching posts, retrieving podcasts, recommendations, and authors. ```APIDOC ## Newsletter Commands ### Get posts ```bash substack newsletter posts [--sort new|top|pinned|community] [--limit N] ``` Returns a list of post URLs from the newsletter. ### Search posts ```bash substack newsletter search [--limit N] ``` ### Get podcasts ```bash substack newsletter podcasts [--limit N] ``` ### Get recommendations ```bash substack newsletter recs ``` Returns URLs of newsletters recommended by the given newsletter. ### Get authors ```bash substack newsletter authors ``` Returns usernames of the newsletter's authors. ``` -------------------------------- ### get_content Source: https://github.com/nhagar/substack_api/blob/master/docs/api-reference/post.md Retrieves the HTML content of the post. Returns None if the content is not available (e.g., paywalled content without authentication). Data can be refreshed if necessary. ```APIDOC ### `get_content(force_refresh: bool = False) -> Optional[str]` Get the HTML content of the post. #### Parameters - `force_refresh` (bool): Whether to force a refresh of the data, ignoring the cache #### Returns - `Optional[str]`: HTML content of the post, or None if not available (e.g., for paywalled content without authentication) ```