1688API 接口终极宝典:列表、详情全掌握,图片搜索攻略助你一臂之力

133 阅读5分钟

1688API 接口终极宝典:列表、详情全掌握,图片搜索攻略助你一臂之力

一、1688 API 概述

1688作为阿里巴巴旗下的B2B电商平台,提供了丰富的API接口供开发者使用,帮助商家和开发者实现商品数据获取、订单管理、物流跟踪等功能。本宝典将重点介绍商品列表、商品详情和图片搜索三大核心API的使用方法。

二、API接入准备

1. 申请开发者账号

2. 创建应用

  • 在控制台创建新应用
  • 获取App Key和App Secret

3. 授权设置

  • 设置回调地址
  • 申请所需API权限

4. 获取访问令牌(Access Token)

python

复制

下载

import requests

def get_access_token(app_key, app_secret):
    url = "https://gw.open.1688.com/auth/requestToken"
    params = {
        "client_id": app_key,
        "client_secret": app_secret,
        "grant_type": "authorization_code",
        "code": "您的授权码",
        "redirect_uri": "您的回调地址"
    }
    response = requests.get(url, params=params)
    return response.json().get("access_token")

三、商品列表API详解

1. 基础商品搜索API

python

复制

下载

def search_products(access_token, keywords, page=1, page_size=20):
    url = "https://gw.open.1688.com/openapi/param2/1/com.alibaba.product/alibaba.product.search"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    params = {
        "keywords": keywords,
        "pageNo": page,
        "pageSize": page_size
    }
    response = requests.get(url, headers=headers, params=params)
    return response.json()

2. 高级筛选参数

  • categoryId: 按类目筛选
  • priceStart/priceEnd: 价格区间
  • minQuantity: 起订量
  • isFreeShip: 是否包邮
  • highQuality: 是否实力商家
  • sort: 排序方式(price_asc/price_desc/volume_desc)

3. 分页处理技巧

python

复制

下载

def get_all_products(access_token, keywords, max_pages=10):
    all_products = []
    for page in range(1, max_pages + 1):
        result = search_products(access_token, keywords, page=page)
        if not result.get("products"):
            break
        all_products.extend(result["products"])
    return all_products

四、商品详情API深度解析

1. 基础商品详情获取

python

复制

下载

def get_product_detail(access_token, product_id):
    url = "https://gw.open.1688.com/openapi/param2/1/com.alibaba.product/alibaba.product.get"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    params = {
        "productId": product_id
    }
    response = requests.get(url, headers=headers, params=params)
    return response.json()

2. 关键数据字段说明

  • productInfo: 基础信息(标题、类目、属性等)
  • skuInfo: SKU信息(价格、库存、规格等)
  • imageInfo: 图片信息
  • description: 商品详情描述
  • supplierInfo: 供应商信息
  • tradeInfo: 交易信息(起订量、发货期等)

3. 批量获取商品详情

python

复制

下载

def batch_get_product_details(access_token, product_ids):
    url = "https://gw.open.1688.com/openapi/param2/1/com.alibaba.product/alibaba.product.batchGet"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    params = {
        "productIds": ",".join(product_ids)
    }
    response = requests.get(url, headers=headers, params=params)
    return response.json()

五、图片搜索API实战攻略

1. 图片搜索基础API

python

复制

下载

def image_search(access_token, image_url):
    url = "https://gw.open.1688.com/openapi/param2/1/com.alibaba.product/alibaba.product.imageSearch"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    params = {
        "imageUrl": image_url
    }
    response = requests.get(url, headers=headers, params=params)
    return response.json()

2. 本地图片上传搜索

python

复制

下载

def local_image_search(access_token, image_path):
    url = "https://gw.open.1688.com/openapi/param2/1/com.alibaba.product/alibaba.product.imageSearch"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    files = {
        'image': open(image_path, 'rb')
    }
    response = requests.post(url, headers=headers, files=files)
    return response.json()

3. 图片搜索高级技巧

  • 图片预处理(裁剪、增强、去背景)
  • 多图片结果比对
  • 结合关键词提升准确率

六、API使用最佳实践

1. 请求频率控制

  • 遵守1688 API调用频率限制
  • 实现请求队列和延迟机制

python

复制

下载

import time
from queue import Queue
from threading import Thread

class APIClient:
    def __init__(self, access_token, max_requests_per_second=5):
        self.access_token = access_token
        self.queue = Queue()
        self.max_rps = max_requests_per_second
        self._start_worker()
    
    def _start_worker(self):
        def worker():
            while True:
                func, args, kwargs, future = self.queue.get()
                start_time = time.time()
                
                try:
                    result = func(*args, **kwargs)
                    future.set_result(result)
                except Exception as e:
                    future.set_exception(e)
                
                processing_time = time.time() - start_time
                delay = max(0, 1/self.max_rps - processing_time)
                time.sleep(delay)
                
                self.queue.task_done()
        
        Thread(target=worker, daemon=True).start()
    
    def request(self, func, *args, **kwargs):
        from concurrent.futures import Future
        future = Future()
        self.queue.put((func, args, kwargs, future))
        return future

2. 错误处理与重试机制

python

复制

下载

import time
from requests.exceptions import RequestException

def robust_request(func, max_retries=3, initial_delay=1):
    def wrapper(*args, **kwargs):
        retries = 0
        delay = initial_delay
        last_exception = None
        
        while retries < max_retries:
            try:
                return func(*args, **kwargs)
            except RequestException as e:
                last_exception = e
                retries += 1
                if retries < max_retries:
                    time.sleep(delay)
                    delay *= 2  # 指数退避
        raise last_exception if last_exception else Exception("Unknown error")
    return wrapper

3. 数据缓存策略

python

复制

下载

import json
import os
from datetime import datetime, timedelta

class APICache:
    def __init__(self, cache_dir="api_cache", ttl=timedelta(hours=1)):
        self.cache_dir = cache_dir
        self.ttl = ttl
        os.makedirs(cache_dir, exist_ok=True)
    
    def _get_cache_path(self, key):
        return os.path.join(self.cache_dir, f"{key}.json")
    
    def get(self, key):
        path = self._get_cache_path(key)
        if not os.path.exists(path):
            return None
            
        with open(path, "r") as f:
            data = json.load(f)
        
        if datetime.fromisoformat(data["timestamp"]) + self.ttl < datetime.now():
            return None
            
        return data["value"]
    
    def set(self, key, value):
        path = self._get_cache_path(key)
        data = {
            "timestamp": datetime.now().isoformat(),
            "value": value
        }
        with open(path, "w") as f:
            json.dump(data, f)

七、常见问题与解决方案

1. 授权问题

  • 问题: "Invalid access token"
  • 解决: 检查token是否过期,及时刷新

2. 频率限制

  • 问题: "API call limit reached"
  • 解决: 实现请求队列和速率控制

3. 数据不完整

  • 问题: 返回字段缺失
  • 解决: 检查API版本,确认所需字段是否在权限范围内

4. 图片搜索准确率低

  • 问题: 搜索结果不相关
  • 解决: 优化图片质量,添加关键词过滤

八、进阶技巧

1. 结合多个API获取完整数据

python

复制

下载

def get_complete_product_info(access_token, product_id):
    # 获取基础信息
    base_info = get_product_detail(access_token, product_id)
    
    # 获取供应商信息
    supplier_info = get_supplier_info(access_token, base_info["supplierId"])
    
    # 获取交易记录
    trade_records = get_trade_records(access_token, product_id)
    
    # 获取评价数据
    reviews = get_product_reviews(access_token, product_id)
    
    return {
        "base_info": base_info,
        "supplier_info": supplier_info,
        "trade_records": trade_records,
        "reviews": reviews
    }

2. 构建商品数据监控系统

python

复制

下载

class ProductMonitor:
    def __init__(self, access_token):
        self.access_token = access_token
        self.products = {}
    
    def add_product(self, product_id):
        self.products[product_id] = {
            "last_price": None,
            "last_stock": None
        }
    
    def check_updates(self):
        updates = []
        for product_id in self.products:
            detail = get_product_detail(self.access_token, product_id)
            current_price = detail["priceInfo"]["price"]
            current_stock = detail["stockInfo"]["stock"]
            
            if (self.products[product_id]["last_price"] is not None and 
                self.products[product_id]["last_price"] != current_price):
                updates.append({
                    "product_id": product_id,
                    "type": "price",
                    "old": self.products[product_id]["last_price"],
                    "new": current_price
                })
            
            if (self.products[product_id]["last_stock"] is not None and 
                self.products[product_id]["last_stock"] != current_stock):
                updates.append({
                    "product_id": product_id,
                    "type": "stock",
                    "old": self.products[product_id]["last_stock"],
                    "new": current_stock
                })
            
            self.products[product_id]["last_price"] = current_price
            self.products[product_id]["last_stock"] = current_stock
        
        return updates

九、总结

本宝典全面介绍了1688三大核心API的使用方法,从基础的接入准备到高级的实战技巧,帮助开发者快速掌握1688平台的数据获取能力。通过合理运用这些API,您可以:

  1. 高效获取海量商品数据
  2. 深度分析商品详情信息
  3. 实现智能图片搜索功能
  4. 构建强大的电商数据应用

随着1688平台的不断更新,建议开发者定期查看[[官方API文档](url](url))获取最新信息,持续优化您的集成方案。