编写Python Web客户端调用在线超市API创建商品并打印响应码
Python 在线超市API商品创建客户端
需求说明
我们需要编写一个Python Web客户端,对接在线超市的API完成新商品创建操作,相关API信息如下:
- 基础URL:
http://host1.open.uom.lk:8080 - 核心接口:
- POST
/api/products/:提交新商品数据,完成商品录入 - 其他辅助接口(本次需求暂不使用):
- GET
/api/products/:获取所有商品列表 - GET
/api/products/X/:获取ID为X的单个商品详情 - PUT
/api/products/:更新已有商品记录
- GET
- POST
需要提交的商品JSON数据如下:
{ "productName":"Araliya Basmathi Rice", "description":"White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.", "category":"Rice", "brand":"CIC", "expiredDate":"2023.05.04", "manufacturedDate":"2022.02.20", "batchNumber":324567, "unitPrice":1020, "quantity":200, "createdDate":"2022.02.24" }
实现代码
import requests base_url = 'http://host1.open.uom.lk:8080' create_product_endpoint = '/api/products/' new_product_data = { "productName": "Araliya Basmathi Rice", "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.", "category": "Rice", "brand": "CIC", "expiredDate": "2023.05.04", "manufacturedDate": "2022.02.20", "batchNumber": 324567, "unitPrice": 1020, "quantity": 200, "createdDate": "2022.02.24" } try: # 发送POST请求,json参数自动将字典序列化为JSON格式并设置Content-Type为application/json response = requests.post(base_url + create_product_endpoint, json=new_product_data) # 主动触发HTTP错误(如4xx、5xx状态码) response.raise_for_status() print("创建新商品 - 响应码:", response.status_code) print("创建新商品 - 响应内容:", response.json()) except requests.exceptions.RequestException as err: print("请求出错:", err)
代码说明
- 使用
requests库发送HTTP请求,这是Python中常用的HTTP客户端库,需提前安装(pip install requests) - 通过
json参数传入商品数据,requests会自动处理JSON序列化,并设置正确的请求头 response.raise_for_status()用于捕获HTTP异常状态码,避免手动判断状态码- 异常捕获块处理所有请求相关的错误(如网络连接失败、HTTP错误等)
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

