Monday, January 19, 2015

RESTAdapter: a new amazing feature in Delphi MVC Framework

RESTAdapter is a new amazing feature of the famous Delphi MVCFramework (DMVCFramework for short). DMVCFramework (as you know) is a powerful framework for web solution in Delphi that respect the MVC pattern and reach RMM Level 3! Above there is a link to the site project (if you want more info about this wonderful framework). Ok, let's go ahead. What is RESTAdapter? RESTAdapter turn a Delphi Interface into your REST API. In practice you can declare an interface that represents your REST API and the RESTAdapter does all work for you. Below a mini guide on how it works:
  

  [Headers('User-Agent', 'RESTAdapter-Test')]
   IRESTAPIService = interface(IInvokable)
    ['{58B9FA23-92F4-4B8E-814B-05232F32A41F}']

    [RESTResource(HttpGet, '/persons')]
    [MapperListOf(TPerson)]
    function GetListPerson: TObjectList<tperson>;

    [RESTResource(HttpGet, '/persons/{personid}')]
    function GetPersonByID([Param('personid')] APersonID: integer): TPerson;

    [RESTResource(httpPOST, '/persons')]
    function SavePerson([Body] ABody: TPerson): TPerson;

  end;

The RestAdapter class generates an implementation of the IRESTAPIService
interface:

  
  RESTAdapter := TRESTAdapter<IRESTAPIService>.Create; 
  RESTAPIService := RESTAdapter.Build('localhost', 9999);
  Person := RESTAPIService.GetPersonByID(1);

Use RTTI Attributes to describe the REST request:
  • RESTResource: to describe URI and REST verb of resource
  • Headers: a key-value pair that represents a Header of HTTP request
  • MapperListOf: to specify the Object Type of the List
  • Param: to specify that a method parameter is a param of HTTP Request
  • Body: to specify that a method parameter is the body of HTTP Request
The TRESTAdapter class inherits from TVirtualInterface. TVirtualInterface doesn't behave like an ordinary class, each instance has an associated reference counter to automatically free itself. In practice there isn't need to free the RESTAdapter object.

In the DMVCFramework samples folder, in particularly "wincellarclientRESTAdapter" you can find a real work example. 

I hope you enjoy it!