tags:

views:

212

answers:

2

I'm building an API using PHP.

What do I need to do to recognize a JSON encoded request?

Does it come with a certain request type?

How do I get just the request body so that I can json_decode it?

+1  A: 

RFC 4627 recommends the mime type application/json. You can read the request data with php://input.

Matthew Flaschen
thank you. php://input is what i was looking for.
john
A: 

The mime type for json is application/json, but I doubt that has caught on yet to add that to responses.

The easiest way to spot a json response is that it will most likely be wrapped in curly braces and have colons after each member. But that still isn't a sure fire way to know it's json.

The easiest way to test it from PHP is to try to json_decode it, if it throws an error, either it's not json, or it's not well-formed json and thus you won't be able to use it anyway.

Anthony
i know what json looks like. the question is json_decode what? how do i get the 'json-encoded payload' to run json_decode on?
john
Ah, so I left you a comment in the main question. Are they passing it as POST? or are you actually retrieving it?
Anthony
So if it's POST, it would depend on if it had a variable name. I would try both of the following: `print_r($_POST)`, to see if POST is still an array, and if so, what the json is keyed to, and I would try: `json_decode($_POST)`. If I had to guess, it's a little of both: `json_decode($_POST[0])`
Anthony
They are passing it as POST.
john