1

Using PHP, I'm attempting to parse a POST request containing nested JSON objects but have gotten nowhere. I can access all of my top-level keys/values but cannot access the nested ones. To get by, I've been accepting single-level objects and having users pass a JSON string to the API for requests containing any nested values but I'd like to allow users to simply POST their JSON queries to the API as they should.

Here is the JSON query in question:

(Sent with Python)

data = {
    "apiKey": '12345678910',
    "toolType": 'testTool',
    "query": {
        "argType": "foo",
        "arg": [
            "do",
            "re",
            "mi"
            ]
    },
    "planInfo": "0"
}
r = post(
    "https://api.example.io/",
    data=data
)

Upon receipt of the POST request, I'd like to access the nested objects of $query but am getting stuck with the string-value "arg".

So far I've tried two things:

[1] echo file_get_contents("php://input"), which only returns:

apiKey=12345678910&toolType=testTool&query=argType&query=arg&planInfo=0

As you can see, $query is not parsed, which is understandable as this is a string query and I'm assuming that serializing nested objects wont be possible with this method..

[2] var_dump($_REQUEST) which gives me a similar evaluation of the query:

array(4) {
  ["apiKey"]=>
  string(11) "12345678910"
  ["toolType"]=>
  string(8) "testTool"
  ["query"]=>
  string(3) "arg"
  ["planInfo"]=>
  string(1) "0"
}

I'm assuming that $_REQUEST is also simply a string query, maybe even an array of parsed values from php://input?

Conclusion:

At this point my overall question is, using PHP, is it even possible to parse nested objects in JSON on the receiving end of a POST request, and if so, what am I missing?

Any feedback would be appreciated, thanks.

cgrom
  • 149
  • 2
  • 9
  • You should get python to post the data as `application/json`. Right now, it's posting the data as `application/x-www-form-urlencoded` – Phil Oct 30 '20 at 04:23
  • Thank you for your feedback. I've tried adding `'Content-type': 'application/json'` to the POST headers with no avail. Same results as the previous I'm afraid :/ – cgrom Oct 30 '20 at 04:51
  • You don't need to play around with the headers, just use `post("https://api.example.io/", json=data)` – Phil Oct 30 '20 at 05:13
  • Whoa yes that was it! I overlooked the request itself. `php://input` works as expected to where I can decode and etc, thanks @Phil ! – cgrom Oct 30 '20 at 05:49

0 Answers0