使用 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 = 'barcode=6921830106820' url = host + path + '?' + querys http = urllib3.PoolManager() headers = { 'Authorization': 'APPCODE ' + appcode } response = http.request('GET', url, headers=headers) 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 = 'barcode=6921830106820' url = f'{host}{path}?{query}' appcode = '你的AppCode' http = urllib3.PoolManager() headers = { 'Authorization': 'APPCODE ' + appcode } response = http.request('GET', url, headers=headers) 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参数填写正确的条码编号。- 返回字段是否完整,取决于接口数据源中的记录情况。
- 部分字段可能为空,这是正常情况。
- 实际使用时,建议增加异常处理,避免网络错误或接口返回异常导致程序中断。
