Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions README_amazon_api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Amazon Product Advertising API Client

A Python script to interact with Amazon's Product Advertising API v5.

## Setup

1. Install uv (if not already installed):

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

2. Get your Amazon API credentials:

- Go to https://affiliate-program.amazon.com/
- Navigate to Tools > Product Advertising API
- Generate or view your credentials

3. Run the setup command:
```bash
uv run amazon_product_api.py setup
```

## Usage

### Search for products:

```bash
uv run amazon_product_api.py search "laptop"
uv run amazon_product_api.py search "python programming books" --count 10
```

### Get details for a specific product:

```bash
uv run amazon_product_api.py get-item B08N5WRWNW
```

## Environment Variables

The script uses these environment variables (stored in `.env`):

- `AMAZON_ACCESS_KEY`: Your API access key
- `AMAZON_SECRET_KEY`: Your API secret key
- `AMAZON_PARTNER_TAG`: Your Amazon Associate ID

## Features

- Search products by keywords
- Get detailed information for specific ASINs
- AWS Signature V4 authentication
- Rich terminal output with tables and formatting
- Simple CLI interface

## Security

- Never commit your `.env` file
- Keep your API credentials secure
- The `.env` file is already in `.gitignore`
124 changes: 124 additions & 0 deletions amazon_api_simple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "python-amazon-paapi",
# "python-dotenv",
# "rich",
# ]
# ///

"""
Simple Amazon Product API client using python-amazon-paapi library
"""

import os
from dotenv import load_dotenv
from amazon_paapi import AmazonApi
from rich.console import Console
from rich.table import Table

load_dotenv()
console = Console()

# Get credentials
ACCESS_KEY = os.getenv("AMAZON_ACCESS_KEY")
SECRET_KEY = os.getenv("AMAZON_SECRET_KEY")
PARTNER_TAG = os.getenv("AMAZON_PARTNER_TAG")
COUNTRY = "US" # Can be US, UK, DE, FR, JP, etc.

# Debug credentials
console.print("[dim]Using credentials:[/dim]")
console.print(f"[dim]Access Key: {ACCESS_KEY}[/dim]")
console.print(
f"[dim]Secret Key: {'*' * 20}...{SECRET_KEY[-4:] if SECRET_KEY else 'None'}[/dim]"
)
console.print(f"[dim]Partner Tag: {PARTNER_TAG}[/dim]")

# Initialize API
try:
amazon = AmazonApi(ACCESS_KEY, SECRET_KEY, PARTNER_TAG, COUNTRY)
console.print("[green]✓ API initialized successfully[/green]")
except Exception as e:
console.print(f"[red]Error initializing API: {e}[/red]")
exit(1)

# Test with one of your ASINs
console.print(
"\n[bold]Testing with ASIN: B0050R67U0 (MagicFiber Microfiber Cleaning Cloth)[/bold]"
)

try:
# Get single item
items = amazon.get_items("B0050R67U0")

if items:
item = items[0]
console.print("\n[green]Success! Found item:[/green]")
console.print(f"Title: {item.item_info.title.display_value}")

# Get price if available
if item.offers and item.offers.listings:
price = item.offers.listings[0].price.display_amount
console.print(f"Price: {price}")

# Get primary image
if item.images and item.images.primary:
console.print(f"Image: {item.images.primary.large.url}")

# Get brand
if item.item_info.by_line_info:
brand = item.item_info.by_line_info.brand.display_value
console.print(f"Brand: {brand}")

console.print(f"URL: {item.detail_page_url}")
else:
console.print("[yellow]No items found[/yellow]")

except Exception as e:
console.print(f"[red]Error: {e}[/red]")

# Test search
console.print("\n[bold]Testing search for 'laptop':[/bold]")

try:
search_result = amazon.search_items(keywords="laptop", item_count=3)

if search_result and search_result.items:
# Create table
table = Table(title="Search Results")
table.add_column("ASIN", style="cyan")
table.add_column("Title", style="green")
table.add_column("Price", style="yellow")

for item in search_result.items[:3]: # Show first 3
asin = item.asin
title = item.item_info.title.display_value[:50] + "..."

price = "N/A"
if item.offers and item.offers.listings:
price = item.offers.listings[0].price.display_amount

table.add_row(asin, title, price)

console.print(table)
else:
console.print("[yellow]No search results[/yellow]")

except Exception as e:
console.print(f"[red]Search error: {e}[/red]")

# Test multiple ASINs from your list
console.print("\n[bold]Testing multiple ASINs from your list:[/bold]")

test_asins = ["B0050R67U0", "B073XS3CHW", "B0737N6LWX"]
try:
items = amazon.get_items(test_asins)

for item in items:
console.print(f"\n{item.asin}: {item.item_info.title.display_value[:60]}...")
if item.offers and item.offers.listings:
console.print(f" Price: {item.offers.listings[0].price.display_amount}")

except Exception as e:
console.print(f"[red]Batch error: {e}[/red]")
127 changes: 127 additions & 0 deletions amazon_official_sdk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "paapi5-python-sdk @ git+https://github.com/amzn/paapi5-python-sdk.git",
# "python-dotenv",
# "rich",
# ]
# ///

"""
Amazon Product API using official SDK
"""

import os
from dotenv import load_dotenv
from rich.console import Console

# Import from the official SDK
from paapi5_python_sdk.api.default_api import DefaultApi
from paapi5_python_sdk.models.get_items_request import GetItemsRequest
from paapi5_python_sdk.models.partner_type import PartnerType
from paapi5_python_sdk.rest import ApiException

load_dotenv()
console = Console()

# Configuration
ACCESS_KEY = os.getenv("AMAZON_ACCESS_KEY")
SECRET_KEY = os.getenv("AMAZON_SECRET_KEY")
PARTNER_TAG = os.getenv("AMAZON_PARTNER_TAG")
HOST = "webservices.amazon.com"
REGION = "us-east-1"

# Initialize the API
default_api = DefaultApi(
access_key=ACCESS_KEY, secret_key=SECRET_KEY, host=HOST, region=REGION
)


def get_items_example():
"""Example of getting items by ASIN"""

# Request for B0050R67U0 (MagicFiber Microfiber Cleaning Cloth)
get_items_request = GetItemsRequest(
partner_tag=PARTNER_TAG,
partner_type=PartnerType.ASSOCIATES,
marketplace="www.amazon.com",
item_ids=["B0050R67U0", "B073XS3CHW"], # Testing 2 ASINs
resources=[
"ItemInfo.Title",
"Offers.Listings.Price",
"Images.Primary.Large",
"ItemInfo.ByLineInfo",
"ItemInfo.Features",
],
)

try:
# Sending the request
console.print("[yellow]Sending GetItems request...[/yellow]")
response = default_api.get_items(get_items_request)

if response.items_result and response.items_result.items:
console.print(
f"[green]Success! Found {len(response.items_result.items)} items[/green]\n"
)

for item in response.items_result.items:
console.print(f"[bold]ASIN:[/bold] {item.asin}")

# Title
if item.item_info and item.item_info.title:
console.print(
f"[bold]Title:[/bold] {item.item_info.title.display_value}"
)

# Price
if (
item.offers
and item.offers.listings
and len(item.offers.listings) > 0
):
listing = item.offers.listings[0]
if listing.price:
console.print(
f"[bold]Price:[/bold] {listing.price.display_amount}"
)

# Brand
if (
item.item_info
and item.item_info.by_line_info
and item.item_info.by_line_info.brand
):
console.print(
f"[bold]Brand:[/bold] {item.item_info.by_line_info.brand.display_value}"
)

# Image
if item.images and item.images.primary and item.images.primary.large:
console.print(
f"[bold]Image:[/bold] {item.images.primary.large.url}"
)

# URL
if item.detail_page_url:
console.print(f"[bold]URL:[/bold] {item.detail_page_url}")

console.print()
else:
console.print("[red]No items found in response[/red]")

except ApiException as exception:
console.print(f"[red]Error: {exception.status}[/red]")
console.print(f"[red]Error Response: {exception.body}[/red]")
console.print(f"[red]Headers: {exception.headers}[/red]")
except Exception as exception:
console.print(f"[red]Exception: {exception}[/red]")


if __name__ == "__main__":
console.print("[bold]Amazon Product Advertising API - Official SDK Test[/bold]\n")
console.print(f"Access Key: {ACCESS_KEY[:10]}...")
console.print(f"Partner Tag: {PARTNER_TAG}\n")

get_items_example()
Loading