Make WordPress Core

Opened 3 years ago

Closed 3 years ago

#52956 closed defect (bug) (invalid)

WP_REST_Request->get_params() doesn't correctly handle boolean false

Reported by: ivankk's profile ivankk Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.7
Component: REST API Keywords: close
Focuses: Cc:


When I use addQueryArg with a false value, it's not interpreted as false by WP_Rest_Request->get_params()

wp.url.addQueryArgs( 'endpoint', { foo: false } );

will give us endpoint?foo=false which rest_route callback $request->get_params();

Will treat as array( 'foo' => 'false' );

This arises as there's no standard for encoding a boolean in a query string.

Attachments (1)

poc.php (1.0 KB) - added by ivankk 3 years ago.

Download all attachments as: .zip

Change History (5)

3 years ago


#1 @ivankk
3 years ago

Added a poc mu-plugin which demonstrates the issue.

Also raised a bug against the Gutenberg project as both the JS library and PHP need to work the same. Issue#30428

#2 @TimothyBlynJacobs
3 years ago

  • Component changed from General to REST API
  • Keywords close added
  • Milestone Awaiting Review deleted
  • Version set to 4.7

Hi @ivankk,

Welcome back to trac and thanks for the ticket!

There is no way to encode a boolean value in a URL. Instead, you need to define the expected type of your request argument using JSON Schema in your route's args definition: rest_sanitize_boolean will then convert a 'false' string to a boolean false value.

#3 @ivankk
3 years ago

@TimothyBlynJacobs what do you think about an update to the documentation?

Because the WordPress REST API accepts URL form encoded data both in the POST body or as the query portion of the URL, many primtive types perform type juggling to convert these string values into their proper native types.

boolean Booleans, the integers 0 and 1, or the strings "0", "1", "false", and "true". 0 is treated as false and 1 is treated as true.

Maybe the Overview section could be updated to elaborate on what sorts of things we could be missing out on if we didn't have a schema in place (type coercion / juggling as an example):

You can implement endpoints without using a schema, but you will be missing out on a lot of things. It is up to you to decide what suits you best.

#4 @TimothyBlynJacobs
3 years ago

  • Resolution set to invalid
  • Status changed from new to closed

That sounds like a good idea to me. Our docs are hosted on Github: Feel free to make a PR!

Note: See TracTickets for help on using tickets.