Background: I am trying to make an API call, which must include a payload. The payload contains 2x date key-pair values, which were previously fixed values, and which I am trying to make dynamic, so they are always the current date.
Code: this is my code, which attempts to make the start_date
and end_date
values dynamic:
def job_initializer():
key, secret, url = ini_reader()
start_date = dt.datetime.today().strftime("%Y-%m-%d")
end_date = dt.datetime.today().strftime("%Y-%m-%d")
payload ="""
{
"data":{
"type":"jobs",
"attributes":{
"job_type":"portfolio_view_results",
"parameters":{
"view_id":"304078",
"portfolio_type":"firm",
"portfolio_id":"1",
"output_type":"json",
"start_date":"%s",
"end_date":"%s"
}
}
}
}
""" %(start_date, end_date)
d = {'payload': payload}
payload = json.dumps(d)
headers = {"Accept": "application/vnd.api json", "Content-Type": "application/vnd.api json", "firm": "381"}
response = requests.post(url, auth=HTTPBasicAuth(key, secret), headers=headers, json=payload)
print(response)
return(response.json())
job_initializer()
Issue: my code / API call works fine if I hardcode date values (e.g., "start_date": "2021-01-01"
) however, when I attempt to make the value dynamic I get a -
<Response [400]>
{'errors': [{'status': '400',
'title': 'Bad Request',
'detail': 'Missing data field'}]}
Observation: I have tried to debug by print(payload)
and I noticed that the dynamic tags are working, however the formatting looks way off, which might be the reason for this issue. Just calling that out, in case it helps with helping me work out the issue
{"payload": "\n \n {\n \"data\":{\n \"type\":\"jobs\",\n \"attributes\":{\n \"job_type\":\"portfolio_view_results\",\n \"parameters\":{\n \"view_id\":\"304078\",\n \"portfolio_type\":\"firm\",\n \"portfolio_id\":\"1\",\n \"output_type\":\"json\",\n \"start_date\":\"2022-01-10\",\n \"end_date\":\"2022-01-10\"\n }\n }\n }\n }\n ", "variables": {}}
Does anyone know what I am missing with my code?
CodePudding user response:
Don't quite understand what your problem is currently. Your code seems works. Is your question why you get a 400 error?
Since missing data
, I guess that the request does not take your payload. You can try to set your Content-Type to application/json
or change the request parameter from json
to data
.
Example:
r = requests.post(base_url, headers=headers, data=d)