Hi,

I have generated a REST export from a view page in Drupal 8. The REST export is working fine and gives the JSON output, when I call the API. But, I would like to modify the structure of this REST export response. That means, currently the REST export response is just an array with out any name for that array. I have to add a name for that response array. Is there anyway to modify Drupal 8 REST Export API response for implementing this?

Thanks,

Comments

anoopmohan’s picture

I found the answer for this:

1) Create a new custom serializer class in a custom module in the path "Drupal\module_name\Plugin\views\style\CustSerializer.php".
2) The custom serializer class should be extended from the core Serializer class ("Drupal\rest\Plugin\views\style\Serializer.php").
3) Override the render() method in the custom serializer class.
4) You can modify the REST Export response structure (like., add a new name for the response array) in the render() method.
5) Now go to your view -> REST Export -> and change the format to use the newly created serializer.

Thanks,

hkirsman’s picture

Thank you, anoopmohan! I needed separator definition so MS Word would know how to open csv properly.

 public function render() {
    $render = parent::render();
    // Add separator definition so Microsoft Word would know how to open the csv
    // file.
    $render = "sep=,\r\n" . $render;
    return $render;
  }
TheSteveLavigne’s picture

@hkiresman I am needing to do the same thing and wondering if you can post your custom module here so I can take a look. Thanks!

hkirsman’s picture

Sure. I didn't check if everything kept working after I deleted excessive code but I think it's ok. Check it out at https://www.upload.ee/files/6906552/ekt_event_registration.zip.html Click on the big green Download button.

pinkninjajess’s picture

Hello, I was wondering if you could please possibly share your code again - I've been trying to implement this, and I'm really stuck.  Thanks :)

hkirsman’s picture

That's strange. The link works for me. Some commercial popping up but otherwise ok.

pinkninjajess’s picture

Got it, thanks so much!

prakashsingh’s picture

In this custom serializer, how would you go about defining contextual filters for this REST endpoint? It should be some kind of argument passed to render() method.

Thanks

goldenflower’s picture

my serializar class is working as expected, and now i want to add custom header having status code. and i can not see any option in return parameter.

return $this->serializer->serialize($rows, $content_type, ['views_style_plugin' => $this]);

Thanks.

TheSteveLavigne’s picture

I have my module and custom class working; however, I simply want to update the rendered xml structure.

The root xml node is '' and I need to make it ''. I them need to replace the individual '' with ''.

Can anyone help with this?

taggartj’s picture

you need to make yourself a custom serializeer
see https://api.drupal.org/api/drupal/core%21modules%21serialization%21src%2...


namespace Drupal\mymodule\Encoder;

use Drupal\serialization\Encoder\XmlEncoder as SerializationXMLEncoder;

/**
 * Encodes xml API data.
 *
 * @internal
 */
class MyApiXMLEncoder extends SerializationXMLEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['my_xml'];

  /**
   * {@inheritdoc}
   */
  public function encode($data, $format, array $context = []) {
    $parent =  parent::encode($data, $format, $context);
    // do stuff 
    return $parent
  }
}

you will need a service for this for dpendiny injection like

serializer.encoder.myxmlapi:
    class: Drupal\dpe_api\Encoder\MyApiXMLEncoder
    tags:
      - { name: encoder, priority: 21, format: 'my_xml' }

Ps sorry you are using xml try not to make it too insainly nested lol.

Sinan Erdem’s picture

Hello taggartj,

I would like to just export plain text instead of XML. Can I still use your code? Where should I put this code? Inside a custom module's .module file?

Thank you

taggartj’s picture

Yes you can make it do that, you need to make a module folder example "mytextencode"
but need to then follow the module folder structure:
in module/custom/mytextencode (your real module name)
mytextencode
 - /src
 -- /Encoder
so put in mytextencode/src/Encoder
make a new class like MyTextEncoder.php and put code in there however
but you see Example above Simply extends SerializationXMLEncoder ... so you should look at how
The Drupal class XmlEncoder and follow that as an example. sorry not much help i know but its sunday AM.

Sinan Erdem’s picture

Thank you taggartj, it is very helpful. I will try.

silentbob’s picture

Does anybody know why Drupal ist putting out something like "url":"http:\/\/www.google.com" instead of "url":"http://www.google.com" in a view? The source Field is just a simple unformatted Textfield exported trough a View JSON Export.

taggartj’s picture

in the Views rest settings you can use fields not renderd entity, then on the field settings you can put on use raw data, and change the labels

bryanbraun’s picture

This will work but be careful. Choosing "Raw Output" bypasses Drupal's render function, so various processing steps that rely on that won't be run. For example, tokens used in these fields won't be processed and translated fields may not render in their translated language.

: Bryan

jacklee0410’s picture

Hi, anoopmohan I'm a newbie in drupal8. I have created a custom module for custom serializer for rest export. But I get ajax error when I doing configuration in views.

bluegeek9’s picture

The Pager Serializer module returns the pagination information and the view data in the Rest Export View.

Download and Install the module like any other Drupal module.  

$result = [
      'rows' => $rows,
      'pager' => [
        'current_page' => $current_page,
        'total_items' => $total_items,
        'total_pages' => $total_pages,
        'items_per_page' => $items_per_page,
      ],
    ];
sparsh.sinha’s picture

I have generated a REST export from a view. But I don't need the main array. Is there any way to remove this?

[

    {

        "title": "Product",

        "body": "<p>Here are the Product Details</p>"

    }

]

It should display like below

    {

        "title": "Product",

        "body": "<p>Here are the Product Details</p>"

    }

SebaZ’s picture

Views results are always an array of rows because even if you set limit to display only 1 row (pager settings) you will get the collection of results with 1 element inside.