Hey there, fellow developer! Ready to dive into the world of Digistore24 API integration? You're in for a treat. This guide will walk you through creating a robust Python integration with Digistore24's API, allowing you to tap into a wealth of e-commerce data and functionality. Whether you're looking to automate sales reports or track affiliate performance, we've got you covered.
Before we jump in, make sure you've got:
requests
libraryLet's get our workspace ready:
pip install requests
Now, let's set up our API credentials:
import os os.environ['DIGISTORE24_API_KEY'] = 'your_api_key_here' os.environ['DIGISTORE24_API_SECRET'] = 'your_api_secret_here'
Time to create our base API client:
import requests import os class Digistore24API: BASE_URL = 'https://www.digistore24.com/api/call/' def __init__(self): self.api_key = os.environ['DIGISTORE24_API_KEY'] self.api_secret = os.environ['DIGISTORE24_API_SECRET'] def make_request(self, endpoint, method='GET', params=None): url = f"{self.BASE_URL}{endpoint}" headers = { 'X-DS-API-KEY': self.api_key, 'X-DS-API-SECRET': self.api_secret } response = requests.request(method, url, headers=headers, params=params) response.raise_for_status() return response.json()
Let's add some methods to our Digistore24API
class:
def get_product(self, product_id): return self.make_request(f'products/{product_id}') def get_order(self, order_id): return self.make_request(f'orders/{order_id}') def get_affiliates(self): return self.make_request('affiliates')
Now, let's beef up our make_request
method with some error handling and rate limiting:
import time from requests.exceptions import RequestException def make_request(self, endpoint, method='GET', params=None, max_retries=3): for attempt in range(max_retries): try: response = requests.request(method, f"{self.BASE_URL}{endpoint}", headers=self.headers, params=params) response.raise_for_status() return response.json() except RequestException as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff
Here's a quick example of how you might process and store order data:
import sqlite3 def store_order(order_data): conn = sqlite3.connect('orders.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, customer_name TEXT, total REAL)''') c.execute("INSERT INTO orders VALUES (?, ?, ?)", (order_data['id'], order_data['customer_name'], order_data['total'])) conn.commit() conn.close() api = Digistore24API() order = api.get_order('12345') store_order(order)
Let's create a simple sales report:
from datetime import datetime, timedelta def generate_sales_report(days=30): api = Digistore24API() end_date = datetime.now() start_date = end_date - timedelta(days=days) params = { 'start_date': start_date.strftime('%Y-%m-%d'), 'end_date': end_date.strftime('%Y-%m-%d') } sales_data = api.make_request('sales', params=params) total_sales = sum(order['total'] for order in sales_data['orders']) print(f"Total sales in the last {days} days: ${total_sales:.2f}") generate_sales_report()
Don't forget to test your code! Here's a simple unit test:
import unittest from unittest.mock import patch from your_module import Digistore24API class TestDigistore24API(unittest.TestCase): @patch('your_module.requests.request') def test_get_product(self, mock_request): mock_request.return_value.json.return_value = {'id': '123', 'name': 'Test Product'} api = Digistore24API() product = api.get_product('123') self.assertEqual(product['name'], 'Test Product') if __name__ == '__main__': unittest.main()
To optimize your API usage, consider implementing caching:
from functools import lru_cache class Digistore24API: # ... other methods ... @lru_cache(maxsize=100) def get_product(self, product_id): return self.make_request(f'products/{product_id}')
This will cache the results of the last 100 product requests, significantly reducing API calls for frequently accessed products.
And there you have it! You've just built a solid foundation for integrating with the Digistore24 API. Remember, this is just the beginning. There's a whole world of possibilities out there. Why not try implementing webhook support next, or diving into more advanced reporting features?
Keep exploring, keep coding, and most importantly, have fun with it!
Happy coding!