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



我有一个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]"]并将其替换为[团队](这在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)

以下是我运行的原始代码的输出:

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:AtomProjectspingtestmanualTicketCreate.py", line 70, in createTicket
response_url = json.loads(response.content.decode('utf-8'))
File "D:Python39libjson__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "D:Python39libjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:Python39libjsondecoder.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 dict,它将在内部序列化它。

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

相关内容

  • 没有找到相关文章

最新更新