微店平台商品关键字搜索接口调用指南:Python代码实现与实战解析

29 阅读2分钟

一、接口概述

微店开放平台提供商品搜索API接口,支持通过关键字检索店铺商品信息。本接口采用RESTful风格设计,支持OAuth2.0认证,返回标准JSON格式数据。

图片.png 获取key和secret

二、准备工作 注册微店开放平台开发者账号 创建应用并获取以下凭证: Client ID Client Secret 申请「商品搜索」接口权限 三、核心接口代码实现(Python示例) python Copy Code import requests import urllib.parse

class WeidianSearchAPI: def init(self, client_id, client_secret): self.base_url = "openapi.weidian.com/" self.client_id = client_id self.client_secret = client_secret self.access_token = self._get_access_token()

def _get_access_token(self):
    """获取OAuth2.0访问令牌"""
    token_url = f"{self.base_url}token"
    params = {
        "grant_type": "client_credentials",
        "client_id": self.client_id,
        "client_secret": self.client_secret
    }
    response = requests.post(token_url, params=params)
    return response.json()['access_token']

def keyword_search(self, keyword, page=1, page_size=20):
    """商品关键字搜索接口"""
    search_url = f"{self.base_url}goods/search"
    headers = {
        "Authorization": f"Bearer {self.access_token}",
        "Content-Type": "application/json"
    }
    params = {
        "keyword": urllib.parse.quote(keyword),
        "page": page,
        "page_size": page_size
    }
    response = requests.get(search_url, headers=headers, params=params)
    
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"API请求失败: {response.text}")

使用示例

if name == "main": # 初始化配置 CLIENT_ID = "your_client_id" CLIENT_SECRET = "your_client_secret"

search_api = WeidianSearchAPI(CLIENT_ID, CLIENT_SECRET)

# 执行搜索
try:
    result = search_api.keyword_search("智能手机", page=1)
    print("搜索结果:", result)
except Exception as e:
    print("搜索异常:", str(e))

四、关键参数说明 请求参数: 参数名 类型 必填 说明 keyword string 是 URL编码后的搜索关键词 page int 否 分页页码(默认1) page_size int 否 每页结果数(最大50) sort_field string 否 排序字段(price/sales/update) sort_order string 否 排序方式(asc/desc) 返回数据结构示例: json Copy Code { "code": 0, "message": "success", "data": { "total": 150, "goods_list": [ { "goods_id": "123456", "title": "旗舰智能手机 8GB+256GB", "price": 2999, "sales": 1500, "thumbnail": "https://...", "shop_id": "778899" }, // ... 其他商品数据 ] } }

五、技术要点解析 安全认证‌:通过Client Credentials方式获取access_token,有效期为2小时 请求编码‌:关键词需进行URL编码处理 错误处理‌:建议实现自动重试机制(401时刷新token) 性能优化‌:建议添加本地缓存减少API调用次数 分页策略‌:推荐使用游标分页替代传统分页 六、常见问题排查 403错误:检查接口权限是否申请 429错误:触发API调用频率限制(默认100次/分钟) 数据缺失:确认店铺是否开启商品信息开放权限 编码异常:确保关键词进行双重URL编码 七、扩展建议 实现搜索联想词功能(使用/search/suggest接口) 增加搜索结果缓存层(Redis/Memcached) 整合商品类目过滤条件(category_id参数) 添加自动化测试用例(模拟不同搜索场景)