I’d like to implement a custom REST endpoint that can also return an empty object. However, in the case where it should return an empty object, the empty associative array returned by the callback is transformed to an empty array.

How can I force the endpoint to transform the array into an object like I can in json_encode by setting the JSON_FORCE_OBJECT flag?

function rest_cb() {
    return array();  // this will result in the REST response [] but {} is required
}

function on_rest_api_init() {
    register_rest_route('ns/v1', 'empty-object', 'rest_cb');
}

1 Answer
1

Found the solution: By casting the return value to an object, it is ensured that in case of an empty array, an empty object will be returned on REST request.

Enhancing on my initial example, this code would work:

function rest_cb() {
    return (object) array();
}

Leave a Reply

Your email address will not be published. Required fields are marked *