Skip to content

Using custom CODECs with rest.li

Karthik Balasubramanian edited this page Nov 10, 2017 · 2 revisions

Pegasus version 12.0.0 adds support for custom codecs provided by implementing applications. RestLi server, by default has support for JSON and PSON codecs. Custom codecs can be added both on the client and server side.

Creating a new Codec:

New or custom codecs for parsing the request and encoding the response can be done by implementing the DataCodec interface. After creating the custom codec, follow the steps below to configure RestLI server and client.

Server

Add the codec on the server side during boot-up. This is done by registering the codec to a MimeType on restli config.

Eg,

private static final DataCodec CODEC = new MyCustomCodec();
RestLiConfig buildRestLiConfig()
{
  RestLiConfig restLiConfig = new RestLiConfig();
  restLiConfig.addCustomContentType(“application/custom-json”, CODEC);
}

Once registered, the restli server will use the registered codec to decode request body if the ContentType header on the request matches the MimeType (eg, 'application/custom-json') specified.

On the response side, if the AcceptType header on the request matches the MimeType of the custom codec, the custom codec supplied will be used to encode the response body.

Errors

  • If the ContentType or AcceptType headers cannot be parsed as proper MimeTypes, it would result in “400 Bad Request” error.
  • If the server does not understand the ContentType specified, ie if no codec is registered for the content type specified, server will default to JSON Codec.
  • If the server does not understand the AcceptType specified, it would result in “406 Not Acceptable” error.

Client

On the client side, there are two scenarios, using a custom codec to encode the request body and specifying a custom AcceptType to request the server to encode response using custom codec.

Both the ContentType for request body and AcceptType for response can be configured using RestliRequestOptions.

Eg,

RestliRequestOptionsBuilder optionsBuilder = new RestliRequestOptionsBuilder();
ContentType CUSTOM_TYPE = ContentType.createContentType(
    "application/json-v2", new MyCustomCodec());

optionsBuilder.setContentType(CUSTOM_TYPE);
optionsBuilder.addAcceptType(CUSTOM_TYPE);

Errors

  • Invalid ContentType in request options will result in IllegalStateException. Invalid AcceptType will result in “400 Bad request” error from the server.
  • If the ContentType provided is not registered with a Codec, then the client will default to JSON codec.
  • If the client specifies an AcceptType that is not registered on the server, it would result in a “HTTP 406 Not Acceptable” error.
Clone this wiki locally