【问题标题】:Python API with JSOn带有 JSOn 的 Python API
【发布时间】:2023-02-23 16:34:08
【问题描述】:

导入请求 导入 json

BASE_URL = 'http://host1.open.uom.lk:8080'
updated_entity = {
"productName":"Araliya Basmathi Rice",
 "description":"White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically       grown.",
"category":"Rice",
"brand":"Araliya",
"expiredDate":"2023.05.04",
"manufacturedDate":"2022.02.20",
"batchNumber":324567,
"unitPrice":1020,
"quantity":200,
"createdDate":"2022.02.24"
}

 response = requests.GET(f"{BASE_URL}/api/products/", json=updated_entity)
 print(response.status_code)
 print(response.json())

有谁知道这段代码有什么问题? 我想从 API 服务器检索所有产品并打印当前存储在服务器中的产品总数。

【问题讨论】:

  • I want to retrieve all the products [...]:相反会发生什么?
  • 代码打印什么? IE。状态码和json
  • 此代码引发 AttributeError。请发布您实际运行的代码。 API 的文档在哪里?这将告诉您需要做什么才能实现目标

标签: python json python-3.x api


【解决方案1】:

为了列出您应该这样做的产品:

import requests

URL = 'http://host1.open.uom.lk:8080/api/products'

with requests.get(URL) as response:
    response.raise_for_status()
    for item in response.json()['data']:
        print(item)

如果你想添加/更新一个项目,那么:

import requests

URL = 'http://host1.open.uom.lk:8080/api/products'

updated_entity = {
    "productName": "Araliya Basmathi Rice",
    "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.",
    "category": "Rice",
    "brand": "Araliya",
    "expiredDate": "2023.05.04",
    "manufacturedDate": "2022.02.20",
    "batchNumber": 324567,
    "unitPrice": 1020,
    "quantity": 299,
    "createdDate": "2022.02.24"
}

with requests.post(URL, json=updated_entity) as response:
    response.raise_for_status()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2020-07-01
    • 2012-12-18
    • 2017-01-04
    • 2013-07-27
    • 2015-12-01
    相关资源
    最近更新 更多