使用 Python 调用商品条形码查询API并解析商品信息

发布时间:2026/6/24 12:44:17
使用 Python 调用商品条形码查询API并解析商品信息 在项目开发中经常会遇到根据商品条码查询基础信息的需求例如商品录入、数据校验、库存管理等。本文以一个条形码查询接口为例演示如何使用 Python 发起请求并处理返回结果。请求参数接口主要使用一个查询参数barcode条码编号通常为 13 位或 14 位数字Python 请求示例下面使用urllib3调用接口import urllib3 host https://market.aliyun.com/detail/cmapi00065867 path /barcode/index method GET appcode 你的AppCode querys barcode6921830106820 url host path ? querys http urllib3.PoolManager() headers { Authorization: APPCODE appcode } response http.request(GET, url, headersheaders) content response.data.decode(utf-8) if content: print(content)返回结果示例接口返回一般是 JSON 格式示例如下{ code: 1, msg: 操作成功, data: { barcode: 6921830106820, brand: 老厨, goods_name: 老厨香辣牛肉干, company: 温州老厨食品有限公司, keyword: 牛肉干, goods_type: 食品、饮料和烟草预制食品和罐头小吃肉干和处理过的肉, category_code: 10005767, category_name: 预制/加工牛肉, spec: 52g, price: 6.00, origin_country: 中国, remark: ... } }常用字段说明返回数据中常见字段包括barcode条码brand品牌goods_name商品名称company生产公司keyword关键词goods_type商品分类category_code分类编码category_name分类名称spec规格price价格origin_country原产国remark备注信息解析 JSON 数据如果需要在程序中直接使用这些字段可以对返回值进行解析import urllib3 import json host https://market.aliyun.com/detail/cmapi00065867 path /barcode/index query barcode6921830106820 url f{host}{path}?{query} appcode 你的AppCode http urllib3.PoolManager() headers { Authorization: APPCODE appcode } response http.request(GET, url, headersheaders) content response.data.decode(utf-8) if content: result json.loads(content) if result.get(code) 1: data result.get(data, {}) print(条码, data.get(barcode)) print(商品名称, data.get(goods_name)) print(品牌, data.get(brand)) print(规格, data.get(spec)) print(价格, data.get(price)) print(产地, data.get(origin_country)) else: print(查询失败, result.get(msg))注意事项AppCode需要替换成自己的值。barcode参数填写正确的条码编号。返回字段是否完整取决于接口数据源中的记录情况。部分字段可能为空这是正常情况。实际使用时建议增加异常处理避免网络错误或接口返回异常导致程序中断。