npm package: @sharpapi/sharpapi-node-product-categories
Description: SharpAPI.com Node.js SDK for generating product categories
Author: Dawid Makowski
Latest version: 1.0.1

![SharpAPI GitHub cover](https://sharpapi.com/sharpapi-github-php-bg.jpg "SharpAPI Node.js Client")

# Product Categorization API for Node.js

## 🏪 Automatically categorize products with AI — powered by SharpAPI.

[![npm version](https://img.shields.io/npm/v/@sharpapi/sharpapi-node-product-categories.svg)](https://www.npmjs.com/package/@sharpapi/sharpapi-node-product-categories)
[![License](https://img.shields.io/npm/l/@sharpapi/sharpapi-node-product-categories.svg)](https://github.com/sharpapi/sharpapi-node-client/blob/master/LICENSE.md)

**SharpAPI Product Categorization** uses advanced AI to automatically assign accurate categories and subcategories to products based on their names and descriptions. Perfect for e-commerce, inventory management, and product organization.

---

## 📋 Table of Contents

1. [Requirements](#requirements)
2. [Installation](#installation)
3. [Usage](#usage)
4. [API Documentation](#api-documentation)
5. [Examples](#examples)
6. [License](#license)

---

## Requirements

- Node.js >= 16.x
- npm or yarn

---

## Installation

### Step 1. Install the package via npm:

```bash
npm install @sharpapi/sharpapi-node-product-categories
```

### Step 2. Get your API key

Visit [SharpAPI.com](https://sharpapi.com/) to get your API key.

---

## Usage

```javascript
const { SharpApiProductCategoriesService } = require('@sharpapi/sharpapi-node-product-categories');

const apiKey = process.env.SHARP_API_KEY; // Store your API key in environment variables
const service = new SharpApiProductCategoriesService(apiKey);

const productName = 'Wireless Bluetooth Headphones with Noise Cancellation';

async function categorizeProduct() {
  try {
    // Submit categorization job
    const statusUrl = await service.categorizeProduct(productName);
    console.log('Job submitted. Status URL:', statusUrl);

    // Fetch results (polls automatically until complete)
    const result = await service.fetchResults(statusUrl);
    const categories = result.getResultJson();

    console.log('Suggested categories:', categories);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

categorizeProduct();
```

---

## API Documentation

### Methods

#### `categorizeProduct(productName: string, maxCategories?: number): Promise<string>`

Assigns categories to a product based on its name and description.

**Parameters:**
- `productName` (string, required): The product name or description to categorize
- `maxCategories` (number, optional): Maximum number of categories to return (default: 5)

**Returns:**
- Promise<string>: Status URL for polling the job result

**Example:**
```javascript
const statusUrl = await service.categorizeProduct(
  'Organic Green Tea 100 Bags Premium Quality',
  3
);
const result = await service.fetchResults(statusUrl);
```

### Response Format

The API returns categories with confidence scores:

```json
{
  "categories": [
    {
      "name": "Electronics > Audio > Headphones",
      "weight": 10,
      "subcategories": ["Wireless Headphones", "Noise-Canceling Headphones", "Bluetooth Audio"]
    },
    {
      "name": "Electronics > Consumer Electronics",
      "weight": 8,
      "subcategories": ["Audio Devices", "Wireless Technology"]
    }
  ]
}
```

---

## Examples

### Basic Product Categorization

```javascript
const { SharpApiProductCategoriesService } = require('@sharpapi/sharpapi-node-product-categories');

const service = new SharpApiProductCategoriesService(process.env.SHARP_API_KEY);

const product = 'Professional DSLR Camera with 24MP Sensor';

service.categorizeProduct(product)
  .then(statusUrl => service.fetchResults(statusUrl))
  .then(result => {
    const categories = result.getResultJson();
    console.log('📂 Product Categories:');
    categories.forEach((cat, index) => {
      console.log(`${index + 1}. ${cat.name} (weight: ${cat.weight})`);
      if (cat.subcategories) {
        console.log(`   Subcategories: ${cat.subcategories.join(', ')}`);
      }
    });
  })
  .catch(error => console.error('Categorization failed:', error));
```

### Batch Product Categorization

```javascript
const service = new SharpApiProductCategoriesService(process.env.SHARP_API_KEY);

const products = [
  'Organic Cotton T-Shirt Men\'s Size L',
  'Stainless Steel Water Bottle 750ml',
  'Yoga Mat with Carrying Strap',
  'Wireless Gaming Mouse RGB LED'
];

const categorized = await Promise.all(
  products.map(async (product) => {
    const statusUrl = await service.categorizeProduct(product, 3);
    const result = await service.fetchResults(statusUrl);
    const categories = result.getResultJson();

    return {
      product,
      primary_category: categories[0]?.name,
      all_categories: categories.map(c => c.name)
    };
  })
);

console.log('Categorized products:', categorized);
```

### E-commerce Integration

```javascript
const service = new SharpApiProductCategoriesService(process.env.SHARP_API_KEY);

async function processNewProduct(productData) {
  const productDescription = `${productData.name} ${productData.description}`;

  const statusUrl = await service.categorizeProduct(productDescription);
  const result = await service.fetchResults(statusUrl);
  const categories = result.getResultJson();

  // Get primary category (highest weight)
  const primaryCategory = categories.sort((a, b) => b.weight - a.weight)[0];

  return {
    ...productData,
    category: primaryCategory.name,
    subcategories: primaryCategory.subcategories,
    all_categories: categories.map(c => c.name),
    categorization_confidence: primaryCategory.weight
  };
}

const newProduct = {
  id: 12345,
  name: 'Smart Fitness Tracker Watch',
  description: 'Heart rate monitor, GPS, waterproof'
};

const enrichedProduct = await processNewProduct(newProduct);
console.log('Product with categories:', enrichedProduct);
```

---

## Use Cases

- **E-commerce Platforms**: Automatically categorize new product listings
- **Inventory Management**: Organize products into logical categories
- **Search Optimization**: Improve product discoverability with accurate categories
- **Product Feeds**: Generate properly categorized product feeds for marketplaces
- **Data Migration**: Recategorize products during platform migrations
- **Marketplace Integration**: Map products to marketplace-specific categories
- **Product Recommendations**: Enable category-based product recommendations

---

## Category Structure

The system recognizes hierarchical categories:

**Top-Level Categories:**
- Electronics
- Clothing & Fashion
- Home & Garden
- Sports & Outdoors
- Health & Beauty
- Books & Media
- Food & Beverages
- Toys & Games
- And many more...

**Subcategories:**
- Each top-level category has multiple subcategories
- Subcategories can have further sub-levels
- Weight scores indicate confidence (0-10)

---

## API Endpoint

**POST** `/ecommerce/product_categories`

For detailed API specifications, refer to:
- [Postman Documentation](https://documenter.getpostman.com/view/31106842/2sBXVeGsVq)
- [Product Page](https://sharpapi.com/en/catalog/ai/e-commerce/product-categorization)

---

## Related Packages

- [@sharpapi/sharpapi-node-product-intro](https://www.npmjs.com/package/@sharpapi/sharpapi-node-product-intro) - Product introductions
- [@sharpapi/sharpapi-node-product-description](https://www.npmjs.com/package/@sharpapi/sharpapi-node-product-description) - Product descriptions
- [@sharpapi/sharpapi-node-generate-keywords](https://www.npmjs.com/package/@sharpapi/sharpapi-node-generate-keywords) - Keyword generation
- [@sharpapi/sharpapi-node-client](https://www.npmjs.com/package/@sharpapi/sharpapi-node-client) - Full SharpAPI SDK

---

## License

This project is licensed under the MIT License. See the [LICENSE.md](LICENSE.md) file for details.

---

## Support

- **Documentation**: [SharpAPI.com Documentation](https://sharpapi.com/documentation)
- **Issues**: [GitHub Issues](https://github.com/sharpapi/sharpapi-node-client/issues)
- **Email**: contact@sharpapi.com

---

**Powered by [SharpAPI](https://sharpapi.com/) - AI-Powered API Workflow Automation**