Skip to main content

A Python package for consistent API error monitoring and tracking.

Project description

api-error-monitor

A Python package for consistent and trackable error monitoring across your API integrations.

Table of Contents

Installation

pip install api-error-monitor

Importing

After installation, you can import the main classes and decorators in your Python code:

from api_error_monitor import ApiErrorMonitor, monitor_errors

Adding to requirements.txt

To ensure this package is installed automatically in your environment, add the following line to your requirements.txt file:

pip install api-error-monitor

Then install all requirements as usual:

pip install -r requirements.txt

Overview

When working with external APIs, consistent error monitoring and tracking are essential for:

  • Debugging integration issues quickly
  • Identifying patterns in API failures
  • Improving reliability through better error insights

This package provides tools for tracking, logging, and monitoring API integration errors in a standardized way.

API Error Monitoring

Basic Error Monitoring

from api_error_monitor import ApiErrorMonitor
import requests

# Create a monitor for a specific integration
salesforce_monitor = ApiErrorMonitor("salesforce", version="2.0")

try:
    response = requests.get("https://api.salesforce.com/v2/contacts")
    response.raise_for_status()
    # ...use response...
except requests.exceptions.RequestException as e:
    # Capture detailed error information
    salesforce_monitor.capture_http_error(
        exception=e,
        endpoint="/v2/contacts", 
        context={"operation": "list_contacts"}
    )
    raise

Using the Monitor Decorator

from api_error_monitor import monitor_errors

@monitor_errors('stripe', endpoint='create_payment')
def process_stripe_payment(amount, customer_id):
    # Integration code here
    response = stripe.Payment.create(amount=amount, customer=customer_id)
    return response
    # Any errors will be automatically captured with context

Best Use Cases for the Monitor Decorator

The monitor_errors decorator is particularly valuable in these scenarios:

  1. API Client Methods: Decorate methods that communicate with external APIs to automatically track all failures.

    class TwitterClient:
        @monitor_errors('twitter', endpoint='get_tweets')
        def get_user_tweets(self, user_id, count=20):
            return self.client.get_user_timeline(user_id=user_id, count=count)
    
  2. Scheduled Integration Jobs: Add monitoring to automated processes that sync with external systems.

    @monitor_errors('salesforce', endpoint='daily_sync')
    def run_daily_salesforce_sync():
        fetch_new_records()
        process_records()
        update_local_database()
    
  3. Using Context Providers: Automatically extract relevant parameters for error context.

    def payment_context(payment_id, amount, **kwargs):
        return {
            "payment_id": payment_id,
            "amount": amount,
            "currency": kwargs.get('currency', 'USD')
        }
    
    @monitor_errors(
        'payment_processor', 
        endpoint='process_payment',
        context_provider=payment_context
    )
    def process_payment(payment_id, amount, currency='USD'):
        return payment_gateway.charge(payment_id, amount, currency)
    
  4. Multiple Integration Points: Track errors across different systems in complex workflows.

    def process_order(order_id):
        inventory = check_inventory(order_id)
        payment = process_payment(order_id)
        shipping = create_shipment(order_id)
        return {"status": "success", "order_id": order_id}
        
    @monitor_errors('inventory_system', endpoint='check')
    def check_inventory(order_id):
        pass
        
    @monitor_errors('payment_gateway', endpoint='charge')
    def process_payment(order_id):
        pass
        
    @monitor_errors('shipping_provider', endpoint='create')
    def create_shipment(order_id):
        pass
    

The decorator excels when you need consistent error tracking across many API integration points, want to minimize boilerplate try/except blocks, and need detailed error context for debugging.

Wrapping API Requests

from api_error_monitor import ApiErrorMonitor
import requests

def get_github_repo_info(repo_name):
    monitor = ApiErrorMonitor("github")
    response = monitor.wrap_request(
        lambda: requests.get(f"https://api.github.com/repos/{repo_name}"),
        endpoint=f"/repos/{repo_name}",
        context={"repo": repo_name},
        request_data={"headers": {"Accept": "application/vnd.github.v3+json"}}
    )
    return response.json()

Integration Examples

from api_error_monitor import ApiErrorMonitor, monitor_errors

class SalesforceIntegration:
    def __init__(self):
        self.client = SalesforceClient()
        self.monitor = ApiErrorMonitor(
            integration_name="salesforce",
            version="2.0",
            context={"org_id": self.client.org_id}
        )
    
    @monitor_errors('salesforce', endpoint='get_contact')
    def get_contact(self, contact_id):
        response = self.monitor.wrap_request(
            lambda: self.client.get(f"/contacts/{contact_id}"),
            endpoint=f"/contacts/{contact_id}",
            context={"contact_id": contact_id}
        )
        return response.json()

API Reference

ApiErrorMonitor

Core monitoring class for API integrations.

Parameters:

  • integration_name (str): Name of the API integration
  • version (str, optional): Version of the integration
  • context (dict, optional): Global context for all errors

Methods:

  • capture_error(message, error_type="GENERAL_ERROR", endpoint=None, status_code=None, request_data=None, response_data=None, exception=None, context=None): Record error details with rich context
  • capture_http_error(exception, endpoint, context=None, request_data=None): Specialized method for HTTP request exceptions
  • wrap_request(request_func, endpoint, context=None, request_data=None): Wrapper for HTTP requests that automatically captures errors
  • get_all_errors(): Get all errors for the current execution

monitor_errors decorator

Decorator that monitors functions for errors and captures details.

Parameters:

  • integration_name (str): Name of the API integration
  • endpoint (str, optional): API endpoint being accessed
  • context_provider (callable, optional): Function to extract context from arguments

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.

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

api_error_monitor-1.0.3.tar.gz (19.1 kB view details)

Uploaded Source

Built Distribution

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

api_error_monitor-1.0.3-py3-none-any.whl (19.6 kB view details)

Uploaded Python 3

File details

Details for the file api_error_monitor-1.0.3.tar.gz.

File metadata

  • Download URL: api_error_monitor-1.0.3.tar.gz
  • Upload date:
  • Size: 19.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.12

File hashes

Hashes for api_error_monitor-1.0.3.tar.gz
Algorithm Hash digest
SHA256 85170d7115741bcbd96438f9c590f8d5a86d31940f6a48d95ccdbe7017c6c567
MD5 9d1f3ef3d9d7d9537fa43b7cce715702
BLAKE2b-256 b4b1084dbdcbae8bd2a0ab263e6ea96f606ab80bec2b97bc1a0cb56e7fc844b2

See more details on using hashes here.

File details

Details for the file api_error_monitor-1.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for api_error_monitor-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 8d6288d5d34c472748a11df907c734e9b40d8e6d1989f58bd21f71e7b06d0b51
MD5 6541b7ebcb5f69302babacf8254b4257
BLAKE2b-256 0d847f57917d56481031f49f04998558053518f9b6be59ca80312f692531e81e

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