格式化 JSON 有效负载以传递给 API POST 调用 python

Formatting a JSON payload for passing to an API POST call in python

我有一个 Web 应用程序,我可以在其中创建额外的属性(键和值)并将它们传递到 JSON 输出中。这是从 Web 应用程序传递的内容的最终格式。

{
        'abendCode': '',
        'action': 'CREATE',
        'assignGroup': '[Team]',
        'component': '',
        'description': 'test alert',
        'entered': '',
        'logicalName': '',
        'pageGroups': '["[Team]"]',
        'priority': '1',
        'RACF': '',
        'sendPage': 'false',
        'sysProdName': 'MANUAL',
        'transactionId': '',
        'type': 'RESPONDER'
        }

我已经创建了一个 python 方法来构建一个 json 有效负载,以利用对 POST 对我们的票务系统的 api 调用来创建票证。在该方法中,我进行了一些格式化以去除不必要的字符,例如 [[Team]"] 并将其替换为 ['Team'] (这在 pageGroups 值中)。我然后从 'assignGroup': '[Team]' 中删除方括号以显示 'assignGroup': 'Team'

当我 运行 代码得到 500 时,我 90% 确定这是因为我的 JSON 格式不正确。

当我 运行 在 Postman 中执行以下操作时,它会创建一个工单。

{
    "type": "RESPONDER",
    "action": "CREATE",
    "logicalName": "",
    "component": "",
    "entered": "",
    "racfId": "",
    "description": "incident creation",
    "priority": "1",
    "assignGroup": "TEAM",
    "transactionId": "",
    "abendCode": "",
    "sysProdName": "MANUAL",
    "sendPage": "false",
    "pageGroups": ["TEAM"]
}

这是我的代码,其中一些内容因敏感性而被删除。

import requests
import json
import ast
from datetime import datetime
import re

# Date and time stamp for logging
now = datetime.now()
# Format: month day year day of the week HH:SS:00
# 03/18/2021 Tuesday 07:18:25
dt_string = now.strftime("%m/%d/%Y %A %H:%M:%S ")

ogArray = {
            'abendCode': '',
            'action': 'CREATE',
            'assignGroup': '[Team]',
            'component': '',
            'description': 'test alert',
            'entered': '',
            'logicalName': '',
            'pageGroups': '["[Team]"]',
            'priority': '1',
            'RACF': '',
            'sendPage': 'false',
            'sysProdName': 'MANUAL',
            'transactionId': '',
            'type': 'RESPONDER'
            }

action = "create"
alertId = "ab40f5e4-867c-b80b-a11aeea57731-1617302963378"
Team = "Team"

tcisApiToken = 'api token'
tcisApi_url_base = 'https://api.com/events/v1/'

tcisHeaders = {'Content-Type': 'applicarion/json', 'Authorization': 'Basic {0}'.format(tcisApiToken)}


def createTicket(ogArray, action, alertId, Team):
    api_url_base = Api_url_base
    headers = Headers
    time = dt_string
    api_url = '{0}events'.format(api_url_base)
    print(time + " Alert Id: " + str(alertId))
    data = ogArray
    # do some string processing
    print("---Pre process ogArray" + str(data))
    data['assignGroup'] = (data['assignGroup'][1:-1])
    data = re.sub("\'\[\"\[", '[\'', str(data))
    data = re.sub("\]\"\]\'", '\']', str(data))
    # Having an Issue here, with data[description] with the key ValueError commented it out for now
    # data['description'] = data['description'] + str(" [alertId:" + alertId + "]")
    print("---Print after format" +str(data))

    data = json.dumps(data)
    print("---After dumps" + str(data))

    data = json.loads(data)
    print("---After loads" + str(data))
    print(time + " Action: " + str(action))
    print(time + "JSON payload: " + str(data))
    # Build JSON POST request
    response = requests.post(url=api_url, data=data, headers=headers)
    print(time + 'API response = ' + str(response.status_code))
    print(time + "Formatted JSON data :" + str(data))
    print(response)
    response_url = json.loads(response.content.decode('utf-8'))

    if response.status_code == 200 and 'returnCode' in response_url:
        eventId = response_url["eventId"]
        incidentId = response_url["incidentId"]
        print(time + str(response_url))
    elif response.status_code == 200 and 'returnCode' not in response_url:
        print(time + str(response_url))
        print(time + "Failed to create  ticket. It is possible the  team does not exist or payload is formatted incorrectly. Contact  admin for support. See logs for more info.")
    else:
        note = 'Create Ticket Failed.'
        print(time + str(note))
        return None

if __name__ == '__main__':
    createTicket = createTicket(ogArray, action, alertId, Team)

这是我 运行ning:

的原始代码的输出
    04/02/2021 Friday 16:31:57  Alert Id: ab40f5e4-867c-46e4-b80b-a11aeea57731-1617302963378
---Pre process ogArray{'abendCode': '', 'action': 'CREATE', 'assignGroup': '[APP-SUPPORT]', 'component': '', 'description': 'test alert', 'entered': '', 'logicalName': '', 'pageGroups': '["[APP-SUPPORT]"]', 'priority': '1', 'RACF': '', 'sendPage': 'false', 'sysProdName': 'MANUAL', 'transactionId': '', 'type': 'RESPONDER'}
---Print after format{'abendCode': '', 'action': 'CREATE', 'assignGroup': 'APP-SUPPORT', 'component': '', 'description': 'test alert', 'entered': '', 'logicalName': '', 'pageGroups': ['APP-SUPPORT'], 'priority': '1', 'RACF': '', 'sendPage': 'false', 'sysProdName': 'MANUAL', 'transactionId': '', 'type': 'RESPONDER'}
---After dumps"{'abendCode': '', 'action': 'CREATE', 'assignGroup': 'APP-SUPPORT', 'component': '', 'description': 'test alert', 'entered': '', 'logicalName': '', 'pageGroups': ['APP-SUPPORT'], 'priority': '1', 'RACF': '', 'sendPage': 'false', 'sysProdName': 'MANUAL', 'transactionId': '', 'type': 'RESPONDER'}"
---After loads{'abendCode': '', 'action': 'CREATE', 'assignGroup': 'APP-SUPPORT', 'component': '', 'description': 'test alert', 'entered': '', 'logicalName': '', 'pageGroups': ['APP-SUPPORT'], 'priority': '1', 'RACF': '', 'sendPage': 'false', 'sysProdName': 'MANUAL', 'transactionId': '', 'type': 'RESPONDER'}
04/02/2021 Friday 16:31:57  Action: create
04/02/2021 Friday 16:31:57 JSON payload: {'abendCode': '', 'action': 'CREATE', 'assignGroup': 'APP-SUPPORT', 'component': '', 'description': 'test alert', 'entered': '', 'logicalName': '', 'pageGroups': ['APP-SUPPORT'], 'priority': '1', 'RACF': '', 'sendPage': 'false', 'sysProdName': 'MANUAL', 'transactionId': '', 'type': 'RESPONDER'}
04/02/2021 Friday 16:31:57 API response = 500
04/02/2021 Friday 16:31:57 Formatted JSON data :{'abendCode': '', 'action': 'CREATE', 'assignGroup': 'TCIS-APP-SUPPORT', 'component': '', 'description': 'test alert', 'entered': '', 'logicalName': '', 'pageGroups': ['APP-SUPPORT'], 'priority': '1', 'RACF': '', 'sendPage': 'false', 'sysProdName': 'MANUAL', 'transactionId': '', 'type': 'RESPONDER'}
<Response [500]>


createTicket = createTicket(ogArray, action, alertId, Team)
  File "D:\AtomProjects\pingtest\manualTicketCreate.py", line 70, in createTicket
    response_url = json.loads(response.content.decode('utf-8'))
  File "D:\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "D:\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "D:\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
[Finished in 0.931s]

我不确定是否需要转储,因为我在转储之前格式化 JSON 字符串。我一直在网上解决这个问题,但在这一点上我很困惑。我也查看了错误输出,但我不理解它们,即使在网上搜索它们也是如此。感谢任何帮助。

这是出了什么问题 -

  1. 您在 json.dumps 之后立即呼叫 json.loads。这现在将您的有效负载反序列化为常规 python 字典。
  2. 您想发送序列化的 JSON 对象作为您的负载。

以下是您的选择: 选项 1:

data = json.dumps(data)
print("---After dumps" + str(data))
response = requests.post(url=api_url, data=data, headers=headers)

选项 2: requests.post 支持 json 参数,您可以在其中直接使用 python 字典,它会在内部对其进行序列化。

# Note that json.dumps is commented out in this option.
# data = json.dumps(data)
response = requests.post(url=api_url, json=data, headers=headers)