REST Service

../../_images/example-protocol-module.png

REST Service

Introduction

This example shows creating a REST interface.

Prerequisites

See Hello World to configure a workspace for the example.

REST Source code

This example will show how to deploy an existing module as a REST ervice deployed in a Baratine server.

  • MyModule - existing module
  • RestService - API for the module as a service
  • RestManagerImpl - service worker implementation
  • RestServiceImpl - service worker implementation

Existing module (MyModule)

public class MyModule
{
  void myGet(String id, Result<String> result);

  void myPut(String id, String value, Result<String> result);
}

Service API (RestService)

The RestService interface defines the proxy API.

RestService.java:

import io.baratine.core.Result;

public interface RestService
{
  void get(Result<String> result);

  void put(String value, Result<Void> result);
}

Service Manager (RestManagerImpl)

RestManagerImpl.java:

import io.baratine.core.Result;
import io.baratine.core.Lookup;
import io.baratine.core.OnLookup;

import javax.inject.Inject;

@Service("/rest")
public class RestManagerImpl
{
  @Inject @Lookup("/my-module")
  private MyModule _module;

  @OnLookup
  public RestServiceImpl onLookup(String path)
  {
    return new RestServiceImpl(_module, path);
  }
}

REST Service (RestServiceImpl)

RestManagerImpl.java:

public class RestServiceImpl implements RestService
{
  private MyModule _module;
  private String _id;

  RestServiceImpl(MyModule module, String id)
  {
    _module = module;
    _id = id;
  }

  public void get(Result<String> result)
  {
    _module.get(_id, result);
  }

  public void put(String value, Result<Void> result)
  {
    _module.put(_id, value, result.from(x->null));
  }
}

REST Access

curl -X PUT -d '["hello"]' http://localhost:8085/s/pod/my-service/1
{"status":"ok","value":null}

curl http://localhost:8085/s/pod/my-service/1
{"status":"ok","value":"hello"}