I apologize in advance, as I have trouble phrasing my questions, but please bear with me and I'll try to be as precise as possible. However, my question is somewhat vague and hard to ask.
I've recently been discussing with one of my colleagues regarding responses sent back from a RESTful API via PHP. Where we've differed is in our response from the server.
His argument has been to just json_encode the raw object (which is a PHP object representation of a row of data from a database table). However, where I have found issue with that is in, for example, a situation where you only need to send back a few columns of data.
For example, let's say you are returning an object where all you need is the primary key, description, and name from a table. However, that object also has properties for other uses (var1, var2, etc.) If echoed out like so:
echo(json_encode($object));
the JSON would look like this:
{
    "primary_key": 4,
    "description": "hello",
    "name": "name namerton",
    "var1": null,
    "var2": null,
    "var3": null,
    "var4": null,
    "var5": null,
    "var6": null
}
I typically prefer to loop through my objects in the following way:
$objectArray = array(
    "primary_key" => $object->primary_key,
    "description" => $object->description,
    "name" => $object->name
);
echo(json_encode($objectArray));
That converts the data into an array, returning a JSON result more like this:
{
    "primary_key": 4,
    "description": "hello",
    "name": "name namerton"
}
My question, I suppose, is whether there is any sort of standard for json encoding objects and returning them from an API? Is either one or the other bad practice? Or is this a matter of personal preference?
My main worry is sending back tons of empty keys, or even sending back unintentional data from the server. I.e. if you only wish to send back primary key, description, and name, but have two other properties set, you'll send those back as well if you JSON encode that object. His main response is that only properties that should be meant to be sent back should be public, and that if we send back extra data, so what? I just have trouble agreeing, but wonder if one approach or other has any reason for being favored.
Thanks in advance for opinions/answers.
I agree with you. You shouldn't directly expose your schema via REST response, lest some unscrupulous types decide to hack your setup, and now have an educated guess on your schema layout, which can occur even with a valid api key.
I would only return the columns requested, and those columns would be changed so they don't mirror the schema.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With