How do I access the body of a WP API request in a custom route?

I have created a custom route in WP API (v2 beta 4) to set a site option. I’m using AngularJS to make the API call, and for some reason, I’m not able to access the data sent within the request. Here is what I have so far:

gvl.service('gvlOptionService', ['$http', function($http) {

    this.updateOption = function(option, value) {

        return $http({
          method  : 'POST',
          url     : wpAPIdata.gvlapi_base + 'options',
          data    : { "option" : option,
                      "value" : value
          headers : { 'Content-Type': 'application/x-www-form-urlencoded',
                      'X-WP-Nonce' : wpAPIdata.api_nonce



This successfully sends the request and the data posted looks something like this:


The request successfully makes it to my custom route and to the callback that I have specified. Here is that callback function within the class:

public function update_option( WP_REST_Request $request ) {

    if(isset($request['option']) && $request['option'] == 'siteColor') {
        $request_prepared = $this->prepare_item_for_database($request);
        $color_updated = update_option('site_color', $request_prepared['value'], false);

        if($color_updated) {
            $response = $this->prepare_item_for_response('site_color');
            $response->set_status( 201 );
            $response->header('Location', rest_url('/gvl/v1/options'));
            return $response;
        } else {
            // ...

    } else {
        return new WP_Error( 'cant_update_option', __( 'Cannot update option.' ), array( 'status' => 400 ) );


The problem is that this always fails and returns the WP_Error because $request[‘option’] is null.

When I var_dump($request), I see the JSON string in the [‘body’] portion of the object, but it won’t let me access that when calling that portion of the array. I’ve also tried using the methods for retrieving parameters noted in the documentation (, but none of those seem to return the data either. Am I missing something really basic here?


You can use $request->get_json_params() which will return an array of key => values.

With these conditions(possibly a few more):

  1. The client sending the request has Content-Type: application/json in the header
  2. There is a raw body like {"option":"siteColor","value":"ff0000"}.


Leave a Comment