{P}

SDK Examples

Copy-paste client code for Python, JavaScript/TypeScript, PHP, and Go.

Python

Install

pip install httpx

Basic client

import httpx
import os

API_KEY = os.environ["PP_API_KEY"]

def parse_product(url: str, hint: str | None = None) -> dict:
    with httpx.Client(
        base_url="https://api.productparse.dev",
        headers={"Authorization": f"Bearer {API_KEY}"},
        timeout=30,
    ) as client:
        response = client.post(
            "/v1/parse",
            json={"url": url, "extractionHint": hint},
        )
        response.raise_for_status()
        return response.json()

# Usage
product = parse_product(
    "https://example.com/products/widget-pro",
    hint="Include all colour variants and return shipping ETA",
)
print(product["title"], product["price"]["amount"])

Batch extraction with concurrency

import asyncio
import httpx
import os

API_KEY = os.environ["PP_API_KEY"]

async def parse_batch(urls: list[str]) -> list[dict]:
    async with httpx.AsyncClient(
        base_url="https://api.productparse.dev",
        headers={"Authorization": f"Bearer {API_KEY}"},
        timeout=60,
    ) as client:
        r = await client.post("/v1/parse", json={"urls": urls})
        r.raise_for_status()
        return r.json()["results"]

urls = [
    "https://example.com/products/a",
    "https://example.com/products/b",
    "https://example.com/products/c",
]

results = asyncio.run(parse_batch(urls))
for r in results:
    if r["success"]:
        print(r["title"], r["price"]["amount"])
    else:
        print(f"Failed: {r['url']}{r.get('error')}")

JavaScript / TypeScript

Install

npm install node-fetch  # or use native fetch in Node 18+

Client class

interface ParseOptions {
  extractionHint?: string
  includeScreenshot?: boolean | 'full-height'
  forceRefresh?: boolean
  strategies?: string[]
}

interface ParseResult {
  title: string
  brand: string | null
  sku: string | null
  price: { amount: number; currency: string }
  availability: string
  images: string[]
  source: { type: string; method: string; confidence: number }
}

class ProductParseClient {
  private baseUrl = 'https://api.productparse.dev'

  constructor(private apiKey: string) {}

  async parse(url: string, options: ParseOptions = {}): Promise<ParseResult> {
    const res = await fetch(`${this.baseUrl}/v1/parse`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ url, ...options }),
    })

    if (!res.ok) {
      const err = await res.json()
      throw new Error(`[${err.code}] ${err.message}`)
    }

    return res.json()
  }

  async parseBatch(urls: string[], options: ParseOptions = {}) {
    const res = await fetch(`${this.baseUrl}/v1/parse`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ urls, ...options }),
    })
    if (!res.ok) throw new Error(`Batch failed: ${res.status}`)
    return res.json()
  }
}

// Usage
const client = new ProductParseClient(process.env.PP_API_KEY!)

const product = await client.parse('https://example.com/product', {
  extractionHint: 'Return quantity break pricing table',
  includeScreenshot: true,
})

console.log(product.title, product.price.amount)

PHP

Install

composer require guzzlehttp/guzzle

Client

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class ProductParseClient
{
    private Client $http;

    public function __construct(string $apiKey)
    {
        $this->http = new Client([
            'base_uri' => 'https://api.productparse.dev',
            'headers'  => [
                'Authorization' => "Bearer {$apiKey}",
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ],
            'timeout' => 30,
        ]);
    }

    public function parse(string $url, array $options = []): array
    {
        try {
            $response = $this->http->post('/v1/parse', [
                'json' => array_merge(['url' => $url], $options),
            ]);
            return json_decode($response->getBody()->getContents(), true);
        } catch (ClientException $e) {
            $err = json_decode($e->getResponse()->getBody()->getContents(), true);
            throw new \RuntimeException("[{$err['code']}] {$err['message']}");
        }
    }
}

// Usage
$client = new ProductParseClient($_ENV['PP_API_KEY']);

$product = $client->parse(
    'https://example.com/products/widget',
    ['extractionHint' => 'Include all storage variants']
);

echo $product['title'] . ' — ' . $product['price']['amount'];

Go

package productparse

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type Client struct {
    apiKey  string
    baseURL string
    http    *http.Client
}

type ParseRequest struct {
    URL            string   `json:"url"`
    ExtractionHint string   `json:"extractionHint,omitempty"`
    Strategies     []string `json:"strategies,omitempty"`
}

type Price struct {
    Amount   float64 `json:"amount"`
    Currency string  `json:"currency"`
}

type ParseResult struct {
    Title        string  `json:"title"`
    Brand        string  `json:"brand"`
    SKU          string  `json:"sku"`
    Price        Price   `json:"price"`
    Availability string  `json:"availability"`
    Images       []string `json:"images"`
}

func NewClient(apiKey string) *Client {
    return &Client{
        apiKey:  apiKey,
        baseURL: "https://api.productparse.dev",
        http:    &http.Client{Timeout: 30 * time.Second},
    }
}

func (c *Client) Parse(req ParseRequest) (*ParseResult, error) {
    body, _ := json.Marshal(req)

    httpReq, _ := http.NewRequest("POST", c.baseURL+"/v1/parse", bytes.NewReader(body))
    httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
    httpReq.Header.Set("Content-Type", "application/json")

    resp, err := c.http.Do(httpReq)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    if resp.StatusCode != 200 {
        var errResp map[string]interface{}
        json.NewDecoder(resp.Body).Decode(&errResp)
        return nil, fmt.Errorf("[%v] %v", errResp["code"], errResp["message"])
    }

    var result ParseResult
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return nil, err
    }
    return &result, nil
}

// Usage
// client := productparse.NewClient(os.Getenv("PP_API_KEY"))
// product, err := client.Parse(productparse.ParseRequest{
//     URL:            "https://example.com/product",
//     ExtractionHint: "Include all colour options",
// })

Unofficial community libraries

Have you built a library in another language? Open a PR to have it listed here.