-1

I have a payload for an API call, like so:

start_period = "2022-05-02"
end_period = "2022-05-02"

payload = {"period": f"{{'p1': [{{'type': 'D', 'start': '{start_period}', 'end': '{end_period}'}}]}}",
               "max-results": 50,
               "page-num": 1,
               "options": {}
               }

When I send this payload, I retrieve a HTTP 403 error. The payload's period when debugging in PyCharm looks like:

'{\'p1\': [{\'type\': \'D\', \'start\': \'2022-05-02\', \'end\': \'2022-05-02\'}]}'

or within the dict itself (again in PyCharm Debugger):

{'period': "{'p1': [{'type': 'D', 'start': '2022-05-02', 'end': '2022-05-02'}]}", 'max-results': 50, 'page-num': 1, 'options': {}}

It should look like this:

{"period": {"p1": [{"type": "D", "start": "2022-05-02", "end": "2022-05-02"}]}, "max-results": 50, "page-num": 1, 'options': {}}

(note the extra quotation marks wrapping around the entire period). I'm not sure if the single quotations are throwing this error. Is my current f-string correct?

pymat
  • 1,090
  • 1
  • 23
  • 45
  • 1
    Is the transfer format supposed to be JSON? Why is a preformatted string used, rather than using Python data structures and letting the JSON module convert to JSON? – outis May 04 '22 at 05:56

1 Answers1

1

Those quotes indicate it's a string. It's appearing as a string in the transfer data because it's a string in payload.

If you're using something to convert the payload to JSON for transfer, don't pre-encode the "period" portion. If you do, the JSON formatter will then encode that entire portion as a string, rather than as objects & arrays. Instead, use Python dicts & arrays and let the JSON formatter handle the conversion.

payload = {
    "period": {
        'p1': [{
            'type': 'D',
            'start': start_period,
            'end': end_period
        }]
    },
    "max-results": 50,
    "page-num": 1,
    "options": {},
}

json.dumps(payload)
outis
  • 75,655
  • 22
  • 151
  • 221
  • Actually this solution is much cleaner, thank you for that. I still retrieve a 403 error, so it could be that the payload is now correct but other credentials are incorrect... – pymat May 04 '22 at 06:08