【问题标题】:Printing JSON POST Response/output to screen in Python在 Python 中将 JSON POST 响应/输出打印到屏幕
【发布时间】:2020-06-04 16:34:52
【问题描述】:

当我在邮递员中向这个 api 发送一个发布请求时,我会得到一个对我的发布请求的响应输出。我只想知道如何将其打印到屏幕上和/或解析它以使用响应以供进一步使用

url = ("https://mysupersecretapi/123456/execute")

    headers =  {'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Authorization': 'basic' , 'Content-Type':'application/json;charset=utf-8'}
    perameters = {
"inputs": {
"Container_Full": 'true',
"Container_Note": "",
"Output_Stream_Id": "1",
"Piece_Serialized": "<Container><Pieces><PieceSerialNo>"+strContainer[0]+"</PieceSerialNo> <CustomerSerialNo/><Note></Note></Pieces></Container> ",
"Qty_Is_Container_Qty": 'true',
"Quantity": 1,
"Workcenter_Key": 58368,
"Validate_Only": 'false',
"Start_New_Container": 'true'
  }
}

    plexReq = requests.post(url,auth=HTTPBasicAuth, headers=headers, json=perameters)
    print(plexReq.request.headers)
    ####START HERE

    print(plexReq.status_code)
    response = requests.get(url)
    plexResponse = json.dumps(response.json)
    print(plexResponse)

'''

这是我使用 POSTMAN 时得到的输出

{
"outputs": {
    "New_Container": null,
    "New_Serial_No": null,
    "Recorded_Master_Unit_No": null,
    "Recorded_Part_No": null,
    "Recorded_Quantity": null,
    "Recorded_Revision": null,
    "Recorded_Serial_No": null,
    "Result_Code": 5106,
    "Result_Error": true,
    "Result_Message": "Workcenter status does not allow production",
    "Validation_Failed": false
     },
     "tables": [],
    "transactionNo": "2069710"
     }

'''

【问题讨论】:

    标签: python json api post request


    【解决方案1】:

    不确定Printing to the screen? 是什么意思。 PostMan 只是一个用于发出API 请求的 API 工具,它不是 Python 解释器,以便能够将其打印到屏幕上。

    parse it to use the response for further use?无法解析获取的数据以用于另一个请求。只能在请求 URL 中手动完成。

    编辑: 这仅适用于 PostMan,如果您的请求来自您的应用程序,则可以解决,请参阅here

    【讨论】:

    • 顺便说一句,这只适用于PostMan,如果您的请求来自您的应用程序,则可以解决,请参阅here
    • 因此,当我在该 API 上使用 post 方法时,该 API 是一个记录生产的存储过程,在该过程执行后,如果该过程正确执行,它会返回一个包含容器序列号的输出响应。当我使用邮递员时,它会给出我显示的输出响应。我想在 python 中做同样的事情
    • 考虑使用像urllib2 see here 这样的库。对 URL 进行必要的调用,它将按预期为您提供响应。您可能还想查看您请求的站点的 API 文档,因为它们可能还有相关的代码 sn-ps 可能对您有所帮助。
    • 我刚刚在您对邮递员的第一条评论中查看了该链接。我没有意识到他们生成了代码 sn-ps。这很有帮助,原来我需要使用 requests.request(“POST”, url, headers=headers, data = payload) 然后使用 print(response.text.encode('utf8')) 打印输出感谢您的帮助!
    • @Damian_W 如果此答案对您的问题有所帮助,请单击答案旁边的复选标记将其标记为已接受。请参阅here 了解更多信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    相关资源
    最近更新 更多