Python Examples
Complete code examples for using the TakeTheme API with Python.
Setup
Using Requests
pip install requests
import os
import requests
from typing import Optional, Dict, Any, Iterator
API_KEY = os.environ.get('TAKETHEME_API_KEY')
BASE_URL = 'https://api.taketheme.com/api/v1'
class TakeThemeClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.session = requests.Session()
self.session.headers.update({
'tt-api-key': f'{api_key}',
'Content-Type': 'application/json'
})
def request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
response = self.session.request(
method,
f'{BASE_URL}{endpoint}',
**kwargs
)
if not response.ok:
error = response.json()['error']
raise TakeThemeError(error)
return response.json()
def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[str, Any]:
return self.request('GET', endpoint, params=params)
def post(self, endpoint: str, data: Dict) -> Dict[str, Any]:
return self.request('POST', endpoint, json=data)
def patch(self, endpoint: str, data: Dict) -> Dict[str, Any]:
return self.request('PATCH', endpoint, json=data)
def delete(self, endpoint: str) -> None:
self.request('DELETE', endpoint)
class TakeThemeError(Exception):
def __init__(self, error: Dict):
self.message = error.get('message', 'Unknown error')
self.code = error.get('code')
self.status = error.get('status')
self.details = error.get('details', [])
super().__init__(self.message)
# Initialize client
client = TakeThemeClient(API_KEY)
Products
List All Products
# Using requests
response = client.get('/products', params={'limit': 25})
products = response['data']
pagination = response['pagination']
print(f"Found {pagination['total_count']} products")
for product in products:
print(f"- {product['title']} (${product['price']})")
Get a Single Product
product = client.get('/products/prod_abc123')['data']
print(f"{product['title']}: {product['description']}")
Create a Product
new_product = client.post('/products', {
'title': 'Premium Hoodie',
'description': 'Warm and comfortable hoodie',
'price': 59.99,
'currency': 'USD',
'status': 'active',
'variants': [
{'title': 'Small', 'sku': 'HOODIE-S', 'price': 59.99, 'inventory_quantity': 50},
{'title': 'Medium', 'sku': 'HOODIE-M', 'price': 59.99, 'inventory_quantity': 75},
{'title': 'Large', 'sku': 'HOODIE-L', 'price': 59.99, 'inventory_quantity': 60},
],
'images': [
{'src': 'https://example.com/hoodie.jpg', 'alt': 'Premium Hoodie'}
]
})['data']
print(f"Created product: {new_product['id']}")
Update a Product
updated = client.patch('/products/prod_abc123', {
'price': 64.99,
'tags': ['featured', 'winter-collection']
})['data']
Delete a Product
client.delete('/products/prod_abc123')