CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-telegraph

Python Telegraph API wrapper for creating and managing Telegraph pages and accounts

Overview
Eval results
Files

low-level-api.mddocs/

Low-level API

Direct Telegraph API access for advanced use cases, custom implementations, and fine-grained control over API requests. The low-level API provides minimal abstraction over the Telegraph REST API.

Capabilities

TelegraphApi Class

Low-level Telegraph API client for direct API method calls.

class TelegraphApi:
    """
    Low-level Telegraph API client.
    
    Parameters:
    - access_token (str, optional): Telegraph access token for authenticated requests
    - domain (str): Telegraph domain, defaults to 'telegra.ph'
    """
    def __init__(self, access_token: str = None, domain: str = 'telegra.ph'):
        pass

Usage example:

from telegraph.api import TelegraphApi

# Create low-level API client
api = TelegraphApi(access_token='your_token')

# Alternative domain
api = TelegraphApi(domain='graph.org')

Direct API Method Calls

Make direct calls to Telegraph API endpoints with custom parameters.

def method(self, method: str, values: dict = None, path: str = '') -> dict:
    """
    Make direct Telegraph API method call.
    
    Parameters:
    - method (str): Telegraph API method name (e.g., 'createPage', 'getPage')
    - values (dict, optional): Method parameters as key-value pairs
    - path (str, optional): Additional path component for methods like getPage
    
    Returns:
    dict: API response data
    
    Raises:
    TelegraphException: API error occurred
    RetryAfterError: Rate limiting with retry timing
    """

Usage examples:

from telegraph.api import TelegraphApi
from telegraph.exceptions import TelegraphException, RetryAfterError

api = TelegraphApi()

# Create account using low-level API
try:
    response = api.method('createAccount', {
        'short_name': 'test-account',
        'author_name': 'Test Author',
        'author_url': 'https://example.com'
    })
    access_token = response['access_token']
    print(f"Account created: {access_token}")
except RetryAfterError as e:
    print(f"Rate limited, retry after {e.retry_after} seconds")
except TelegraphException as e:
    print(f"API error: {e}")

# Get page using path parameter
api = TelegraphApi(access_token=access_token)
page_data = api.method('getPage', path='My-Page-12-31', values={
    'return_content': True
})

# Get account info with custom fields
account_info = api.method('getAccountInfo', {
    'fields': '["short_name", "author_name", "page_count"]'
})

Low-level File Upload

Direct file upload using the unofficial Telegraph upload endpoint.

def upload_file(self, f) -> list:
    """
    Upload file using low-level API (unofficial).
    
    Parameters and behavior identical to high-level Telegraph.upload_file()
    """

Usage example:

api = TelegraphApi()
result = api.upload_file('image.jpg')
file_url = result[0]['src']
print(f"Uploaded to: https://telegra.ph{file_url}")

Advanced Usage Patterns

Custom Domain Support

Use Telegraph mirrors or custom domains:

# Use alternative domain
api = TelegraphApi(domain='graph.org')

# Create account on alternative domain
response = api.method('createAccount', {
    'short_name': 'mirror-account'
})

Raw API Response Handling

Process raw Telegraph API responses without high-level abstractions:

def create_page_raw(api, title, content_json):
    """Create page with raw content JSON."""
    response = api.method('createPage', {
        'title': title,
        'content': content_json,
        'return_content': True
    })
    return response

# Use with pre-serialized content
import json
content_json = json.dumps([
    {'tag': 'p', 'children': ['Raw content']}
], separators=(',', ':'), ensure_ascii=False)

api = TelegraphApi(access_token='your_token')
result = create_page_raw(api, 'Raw Page', content_json)

Custom Error Handling

Implement custom retry logic and error handling:

import time
from telegraph.api import TelegraphApi
from telegraph.exceptions import RetryAfterError, TelegraphException

def api_call_with_retry(api, method, values=None, path='', max_retries=3):
    """Make API call with automatic retry on rate limiting."""
    for attempt in range(max_retries):
        try:
            return api.method(method, values, path)
        except RetryAfterError as e:
            if attempt == max_retries - 1:
                raise  # Re-raise on final attempt
            print(f"Rate limited, waiting {e.retry_after} seconds...")
            time.sleep(e.retry_after)
        except TelegraphException as e:
            print(f"API error on attempt {attempt + 1}: {e}")
            if attempt == max_retries - 1:
                raise  # Re-raise on final attempt
            time.sleep(2 ** attempt)  # Exponential backoff

# Usage
api = TelegraphApi(access_token='your_token')
response = api_call_with_retry(api, 'createPage', {
    'title': 'Retry Test',
    'content': '[{"tag": "p", "children": ["Test content"]}]'
})

Session Management

Access underlying HTTP session for advanced configuration:

api = TelegraphApi()

# Configure session (synchronous API)
api.session.headers.update({'User-Agent': 'Custom Telegraph Client'})
api.session.timeout = 30

# Make API calls with custom session settings
response = api.method('createAccount', {
    'short_name': 'session-test'
})

Comparison with High-level API

High-level API (Telegraph class)

  • Automatic token management
  • Convenient parameter handling
  • Built-in HTML/node conversion
  • Exception wrapping
  • Method-specific validation

Low-level API (TelegraphApi class)

  • Direct API access
  • Manual parameter serialization
  • Raw response handling
  • Minimal abstraction
  • Custom domain support

Example comparison:

# High-level API
from telegraph import Telegraph

telegraph = Telegraph()
response = telegraph.create_page(
    title='High Level',
    html_content='<p>Easy to use</p>'
)

# Low-level API
from telegraph.api import TelegraphApi
import json

api = TelegraphApi()
response = api.method('createPage', {
    'title': 'Low Level',
    'content': json.dumps([{'tag': 'p', 'children': ['More control']}], 
                         separators=(',', ':'), ensure_ascii=False)
})

Use Cases for Low-level API

  1. Custom Telegraph clients with specialized features
  2. Batch operations requiring fine-grained control
  3. Alternative domain support for Telegraph mirrors
  4. Custom retry and error handling strategies
  5. Performance optimization by avoiding high-level abstractions
  6. Integration with existing HTTP clients or session management
  7. Debugging and testing Telegraph API responses

The low-level API provides the foundation for the high-level Telegraph class while offering direct access for advanced use cases.

Install with Tessl CLI

npx tessl i tessl/pypi-telegraph

docs

account-management.md

async-api.md

file-upload.md

html-utilities.md

index.md

low-level-api.md

page-operations.md

tile.json