WP API returning SQL results as strings, rather than numbers

I have this code, but what I get in the browser are all the fields – even those stored as Int and Bool in SQL – as strings.

add_action( 'rest_api_init', function () {
  register_rest_route( 'restos/v1', '/resto/(?P<qname>.*)', array(
    'methods' => 'GET',
    'callback' => 'handle_get',
    'permission_callback' => function () {
      return current_user_can( 'edit_others_posts' );
    }
  ) );
} );

function handle_get( $data ) {
    global $wpdb;
    $query = "SELECT * FROM `restaurants` WHERE `qname` = '".$data['qname']."' LIMIT 1";
    $res = $wpdb->get_results($query)[0];

    return $res;
}

I tried return json_encode($res) but that did not help. How can I get an object sent over with numbers and booleans in json.

1
1

The string output type is expected for $wpdb query results, the db data types are not mapped to the corresponding PHP data types.

You will have to take care of it yourself, like:

$data = [
    'int'    => (int)    '123',
    'bool'   => (bool)   '1',
    'string' => (string) 'abc'
];

return rest_ensure_response( $data );

with the rest response:

{"int":123,"bool":true,"string":"abc"}

Here’s an interesting approach by Matthew Boynes, to handle it automatically in wpdb with a custom wrapper.

Note that you can use wpdb::get_row to get a single row.

Leave a Comment