import hashlib
import json
import requests
from typing import Optional, Dict, List, Union, Any
from enum import Enum
class CountryCode(str, Enum):
NL = "NL"
DE = "DE"
class ImageSize(str, Enum):
TINY = "tiny"
SMALL = "small"
MEDIUM = "medium"
LARGE = "large"
EXTRA_LARGE = "extra-large"
class PicnicClient:
def __init__(self,
country_code: str = "NL",
api_version: str = "15",
auth_key: Optional[str] = None,
url: Optional[str] = None):
"""
Initialize the Picnic API client.
Args:
country_code: The country code for requests (NL or DE)
api_version: API version for requests
auth_key: Authentication key for requests
url: Custom API endpoint URL
"""
self.country_code = country_code
self.api_version = api_version
self.auth_key = auth_key
self.url = url or f"https://storefront-prod.{country_code.lower()}.picnicinternational.com/api/{api_version}"
async def login(self, username: str, password: str) -> Dict[str, Any]:
"""
Login to Picnic API.
Args:
username: Picnic account username/email
password: Picnic account password
Returns:
Dict containing auth key and login status
"""
secret = hashlib.md5(password.encode('utf-8')).hexdigest()
response = requests.post(
f"{self.url}/user/login",
headers={"Content-Type": "application/json"},
json={
"key": username,
"secret": secret,
"client_id": 30100
}
)
if not response.ok:
error_data = response.json()
raise Exception(f"Login failed: {error_data.get('error', {}).get('message', response.reason)}")
data = response.json()
self.auth_key = response.headers.get('x-picnic-auth')
if not self.auth_key:
raise Exception("Login failed: No auth key received.")
return {
"auth_key": self.auth_key,
"second_factor_authentication_required": data.get("second_factor_authentication_required"),
"show_second_factor_authentication_intro": data.get("show_second_factor_authentication_intro"),
"user_id": data.get("user_id")
}
def _get_headers(self, include_picnic_headers: bool = False) -> Dict[str, str]:
"""Generate request headers."""
headers = {
"User-Agent": "okhttp/3.12.2",
"Content-Type": "application/json; charset=UTF-8"
}
if self.auth_key:
headers["x-picnic-auth"] = self.auth_key
if include_picnic_headers:
headers.update({
"x-picnic-agent": "30100;1.15.232-15154",
"x-picnic-did": "[Redacted InternationalBankingAccountNumber]"
})
return headers
def send_request(self,
method: str,
path: str,
data: Optional[Dict] = None,
include_picnic_headers: bool = False,
is_image_request: bool = False) -> Union[Dict, bytes]:
"""
Send a request to the Picnic API.
Args:
method: HTTP method (GET, POST, etc)
path: API endpoint path
data: Request payload
include_picnic_headers: Whether to include Picnic specific headers
is_image_request: Whether the response is an image
Returns:
JSON response or binary data for images
"""
headers = self._get_headers(include_picnic_headers)
response = requests.request(
method=method,
url=f"{self.url}{path}",
headers=headers,
json=data if data else None
)
if not response.ok:
try:
error_data = response.json()
raise Exception(f"{error_data.get('error', {}).get('message', response.reason)}")
except:
raise Exception(f"{response.status_code} {response.reason}")
return response.content if is_image_request else response.json()
def search(self, query: str) -> List[Dict]:
"""Search Picnic products."""
raw_results = self.send_request(
"GET",
f"/pages/search-page-results?search_term={query}",
include_picnic_headers=True
)
final_results = []
try:
for child1 in raw_results["body"]["children"]:
for child2 in child1["children"]:
if child2.get("content", {}).get("selling_unit"):
# Extract sole_article_id from PML
pml_str = json.dumps(child2["pml"])
import re
sole_article_id = re.findall(r'sole_article_id=([0-9]+)', pml_str)[0]
result = child2["content"]["selling_unit"]
result["sole_article_id"] = sole_article_id
final_results.append(result)
except:
raise Exception(
"Failed to parse search results. API response format may have changed."
)
return final_results
# Add other methods following similar pattern...