How to read the body (json data) of the request in a custom plugin

I am trying to create a custom plugin which needs to read the body of the request (by body i mean json data that is sent along with the request)

so i should be able to read the json data of a request like

POST myendpoint
{
     "somefield": "somevalue",
     "anotherfield": "anothervalue"
}

i currently have created a catAction, but it shows this error when i try to send a body

{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "request [POST /myendpoint] does not support having a body"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "request [POST /myendpoint] does not support having a body"
  },
  "status" : 400
}

how can i send and read the body?

Did you create a subclass of the BaseRestHandler?

What's the code?

So my endpoint is called deepclean
DeepCleanPlugin.java

public class DeepCleanPlugin extends Plugin implements ActionPlugin
{
    @Override
    public List<RestHandler> getRestHandlers(Settings settings,
                                             RestController restController,
                                             ClusterSettings clusterSettings,
                                             IndexScopedSettings indexScopedSettings,
                                             SettingsFilter settingsFilter,
                                             IndexNameExpressionResolver indexNameExpressionResolver,
                                             Supplier<DiscoveryNodes> nodesInCluster)
    {
        return Collections.singletonList((new DeepCleanAction()));
    }
}

DeepCleanAction.java

public class DeepCleanAction extends AbstractCatAction
{
    @Override
    protected RestChannelConsumer doCatRequest(RestRequest request, NodeClient client)
    {
        Table table = getTableWithHeader(request);
        String message = request.content().toString();
        table.startRow();
        table.addCell(message);
        table.endRow();
        table.startRow();
        table.addCell("this should be after message");
        table.endRow();
        return restChannel ->
        {
            try
            {
                restChannel.sendResponse(RestTable.buildResponse(table,restChannel));

            } catch (final Exception e)
            {
            restChannel.sendResponse(new BytesRestResponse(restChannel, e));
            }
        };
    }

Edit : after i changed message to be = request.content().toutf8String()
i was able to see the send the body, and the message was the same as body, but in string

how do i convert this into an object?
I know i can use json parsers, but i don't think that is a proper way.

I wanted to know how the _snapshot or other apis handle the body?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.