← Back to Agent API
Python Code Examples
Practical examples for interacting with the Abba Baba API using Python.
This guide provides several code examples to help you get started with the Abba Baba API in Python. The most popular library for making HTTP requests in Python is `requests`. If you don't have it installed, you can add it to your project:
pip install requestsExample 1: Basic Semantic Search
A simple function to perform a search query and print the titles of the resulting products.
import requests
import os
# It's best practice to load your API key from environment variables
API_KEY = os.environ.get("ABBA_BABA_API_KEY")
API_URL = "https://api.abbababa.com/v1/search"
def find_products(query_text):
"""Performs a basic search and prints product titles."""
if not API_KEY:
print("Error: ABBA_BABA_API_KEY environment variable not set.")
return
headers = {
"X-API-Key": API_KEY,
"Content-Type": "application/json"
}
payload = {"query": query_text}
try:
response = requests.post(API_URL, headers=headers, json=payload)
response.raise_for_status() # Raises an exception for bad status codes (4xx or 5xx)
data = response.json()
products = data.get('data', [])
print(f"Found {len(products)} products for '{query_text}':")
for product in products:
print(f"- {product.get('title')} (${product.get('price')})")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
# --- Usage Example ---
find_products("eco-friendly yoga mat")Example 2: Search with Filtering
This example builds on the first by adding several filters to narrow down the search results.
import requests
import os
API_KEY = os.environ.get("ABBA_BABA_API_KEY")
API_URL = "https://api.abbababa.com/v1/search"
def filtered_search(query_text, min_price=None, max_price=None, brand=None):
"""Performs a search with optional price and brand filters."""
if not API_KEY:
print("Error: ABBA_BABA_API_KEY environment variable not set.")
return
headers = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
payload = {
"query": query_text,
"filters": {}
}
if min_price:
payload["filters"]["min_price"] = min_price
if max_price:
payload["filters"]["max_price"] = max_price
if brand:
payload["filters"]["attributes"] = {"brand": brand}
try:
response = requests.post(API_URL, headers=headers, json=payload)
response.raise_for_status()
# ... (error handling and printing results as in Example 1) ...
print(response.json())
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
# --- Usage Example ---
filtered_search(
query_text="men's running shoes",
min_price=100,
max_price=150,
brand="Brooks"
)Example 3: Handling Pagination
If you need to retrieve more than the default number of results, you can use the `offset` parameter to paginate through the entire result set.
import requests
import os
# ... (API_KEY and API_URL setup) ...
def get_all_results(query_text, limit=100):
"""Paginates through all results for a query."""
all_products = []
offset = 0
total_results = -1
while total_results == -1 or len(all_products) < total_results:
payload = {"query": query_text, "limit": limit, "offset": offset}
try:
response = requests.post(API_URL, headers=headers, json=payload)
response.raise_for_status()
data = response.json()
products = data.get('data', [])
if not products:
break # Exit loop if no more products are returned
all_products.extend(products)
if total_results == -1:
total_results = data.get('metadata', {}).get('total_results', 0)
offset += limit
print(f"Retrieved {len(all_products)} of {total_results} products...")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
break
return all_products
# --- Usage Example ---
all_shoes = get_all_results("shoes")
print(f"
Finished. Total products retrieved: {len(all_shoes)}")