Skip to main content

A Python wrapper around the Substack API.

Project description

Python Substack

A Python wrapper around the Substack API for creating, managing, and publishing posts programmatically.

Features

  • 🚀 Create and publish posts to Substack
  • 📝 Support for draft posts
  • 📊 Get subscriber count and analytics
  • 🖼️ Image upload support
  • ⏰ Post scheduling functionality
  • 🔐 Authentication handling
  • 🛡️ Rate limiting protection

Installation

Using Poetry (Recommended)

# Clone the repository
git clone https://github.com/TarunVedula/python-substack.git
cd python-substack

# Install dependencies
poetry install

# Activate the virtual environment
poetry shell

Using pip

pip install python-substack

Development Installation

# Clone the repository
git clone https://github.com/TarunVedula/python-substack.git
cd python-substack

# Install in development mode
pip install -e .

Quick Start

1. Set up Authentication

Create a .env file in your project directory:

EMAIL=your-email@example.com
PASSWORD=your-password
PUBLICATION_URL=https://your-publication.substack.com

2. Basic Usage

from substack import Api
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize the API client
api = Api(
    email=os.getenv("EMAIL"),
    password=os.getenv("PASSWORD"),
    publication_url=os.getenv("PUBLICATION_URL")
)

# Get subscriber count
subscriber_count = api.get_publication_subscriber_count()
print(f"Current subscribers: {subscriber_count}")

# Get published posts
posts = api.get_published_posts(limit=5)
for post in posts:
    print(f"Post: {post['title']}")

Examples

Getting Subscriber Count

from substack import Api

api = Api(
    email="your-email@example.com", 
    password="your-password",
    publication_url="https://your-publication.substack.com"
)

subscriber_count = api.get_publication_subscriber_count()
print(f"You have {subscriber_count} subscribers")

Creating and Publishing a Draft

from substack import Api

api = Api(
    email="your-email@example.com", 
    password="your-password",
    publication_url="https://your-publication.substack.com"
)

# Create a new draft
draft_data = {
    "title": "Hello World",
    "subtitle": "A test post",
    "body": "# Hello World\n\nThis is a test post created with python-substack.",
    "section_id": None
}

draft = api.post_draft(draft_data)
print(f"Draft created: {draft['id']}")

# Publish the draft
published_post = api.publish_draft(draft, send=True)
print(f"Published: {published_post['url']}")

Working with Drafts

# Get all drafts
drafts = api.get_drafts()

# Get a specific draft
draft = api.get_draft(draft_id)

# Update a draft
updated_draft = api.put_draft(draft, title="Updated Title")

# Delete a draft
api.delete_draft(draft_id)

Scheduling Posts

from datetime import datetime

# Schedule a draft for later publication
schedule_time = datetime(2024, 2, 1, 10, 0, 0)  # Feb 1, 2024 at 10 AM
scheduled = api.schedule_draft(draft, schedule_time)

# Unschedule a draft
api.unschedule_draft(draft)

API Reference

Api Class

Methods

  • get_publication_subscriber_count(): Get current subscriber count
  • get_published_posts(offset=0, limit=25, order_by="post_date", order_direction="desc"): Get published posts
  • get_drafts(filter=None, offset=None, limit=None): Get all drafts
  • get_draft(draft_id): Get a specific draft
  • post_draft(body): Create a new draft
  • put_draft(draft, **kwargs): Update a draft
  • publish_draft(draft, send=True, share_automatically=False): Publish a draft
  • schedule_draft(draft, draft_datetime): Schedule a draft for later publication
  • unschedule_draft(draft): Unschedule a draft
  • delete_draft(draft_id): Delete a draft
  • get_user_profile(): Get user profile information
  • get_user_publications(): Get all user publications
  • get_user_primary_publication(): Get the primary publication

Draft Data Structure

draft_data = {
    "title": str,           # Required: Post title
    "subtitle": str,        # Optional: Post subtitle
    "body": str,           # Required: Post content (supports Markdown)
    "section_id": int,     # Optional: Section ID
    "tags": list,          # Optional: List of tags
    "published": bool      # Optional: Whether to publish immediately
}

Configuration

Environment Variables

Authentication Options

You can authenticate in two ways:

  1. Email/Password: Provide email and password directly
  2. Cookies: Save and reuse cookies for persistent sessions
# Using cookies for persistent authentication
api = Api(cookies_path="cookies.json")

# Export cookies for later use
api.export_cookies("cookies.json")

Development

Setting up Development Environment

# Clone the repository
git clone https://github.com/TarunVedula/python-substack.git
cd python-substack

# Install dependencies
pip install -e .

# Install pre-commit hooks
pre-commit install

# Run tests
python -m pytest

Running Tests

python -m pytest

Code Quality

This project uses:

  • Poetry for dependency management
  • pytest for testing
  • pre-commit for code quality hooks
  • GitHub Actions for CI/CD

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Original project by Paolo Mazza
  • Substack API for providing the underlying service

Support

If you encounter any issues or have questions, please:

  1. Check the examples directory for usage examples
  2. Open an issue on GitHub
  3. Review the existing issues for similar problems

Note: This library is not officially affiliated with Substack. Use at your own risk and in accordance with Substack's terms of service.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_substack_tarun-0.1.16.tar.gz (11.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_substack_tarun-0.1.16-py3-none-any.whl (10.8 kB view details)

Uploaded Python 3

File details

Details for the file python_substack_tarun-0.1.16.tar.gz.

File metadata

  • Download URL: python_substack_tarun-0.1.16.tar.gz
  • Upload date:
  • Size: 11.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.11.0 Linux/6.11.0-1015-azure

File hashes

Hashes for python_substack_tarun-0.1.16.tar.gz
Algorithm Hash digest
SHA256 44db7d5c6af07d198d90e1129f70ba4c92c8aaec8e0afbb63060d2e34dc4010e
MD5 35e433365d821470a712ddc20f39ac40
BLAKE2b-256 3b36d05ec627f05785992b0132753d65553e23dae605282712986770a7a6e6d2

See more details on using hashes here.

File details

Details for the file python_substack_tarun-0.1.16-py3-none-any.whl.

File metadata

File hashes

Hashes for python_substack_tarun-0.1.16-py3-none-any.whl
Algorithm Hash digest
SHA256 bbc5dcf1f69dd7ff93e2a9693528fd064f4d2149a3f08b7107e554f4f337f42f
MD5 e7d40f01630832d2949af67922114568
BLAKE2b-256 1922a2647f387b13d997c2c5719116ac0a4be2b41078ce513590d8b1093af08a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page