HowTo: Consuming a Procedure exposed as a Rest service

Official Content
This documentation is valid for:

The following is a simple example where we consume a procedure exposed as a Rest web service, which only receives simple parameters and doesn't return any.

In the example, the "AddCustomer" Procedure is declared as REST web service in GeneXus, so the following properties are set as described here:

  • Expose as web service = true
  • Rest protocol = true

exposeaswsprop2

The procedure receives "in" parameters in order to add a Customer to the corresponding table:

Parm Rule:

parm(in:&CustomerId,in:&CustomerName,in:&CustomerBirthDate);

Source:

new
   CustomerId = &CustomerId
   CustomerName = &CustomerName
   CustomerBirthDate = &CustomerBirthDate
endnew

In order to call AddCustomer as a REST web service, you should use HttpClient data type. A GeneXus client should look as shown below:

// http://server:8080/BaseUrl/rest/AddCustomer
&httpclient.Host = 'server'
&httpclient.Port = 8080
&httpclient.Secure = 0
&httpclient.BaseUrl = 'Baseurl'
 
&body = &customersdt.ToJson() //&customersdt is a variable of CustomerSdt data type which is an SDT that includes the CustomerId, CustomerName and CustomerBirthDate items.
&body = '{ "Customer":' + &body + '}' 
 
&httpclient.AddHeader('Content-type','application/json')
&httpclient.AddString(&body)

&httpclient.Execute('POST','AddCustomer') 
//Then process the HttpClient response.

Download the sample from Sample consuming a Rest procedure

As shown in the example, the parameters are sent in JSON format in the body of the HttpRequest; that's why in the example we use the method to convert the data contained in an SDT to JSON format.

Also, pay special attention to the line:

&body = '{"Customer":' + &body + '}'

As can be seen, it is necessary to wrap the &Body parameter, in this case inside the 'Customer' key, because the REST program generated by GeneXus wrapped all the input parameters.  

This is particularly necessary when the REST service receives more the one input parameter, for instance: 

parm(in:&Customer, in:&Mode, out:&CustomerId, out:&Message);

The rest protocol expects a valid JSON, and this is always in the form of {Field: Value, Field: Value,..}, an array [Field: value, Field: value] or a combination of both. So in that case you can't send something like this in the body:

{"CustomerId": 1, "CustomerName": "Paul", "CustomerBirthDate": "1977-01-18"} "INS"

Because this is not a valid JSON.

Then it has to be sent like this:

{"Customer": {"CustomerId": 1, "CustomerName": "Paul", "CustomerBirthDate": "1977-01-18"}, "Mode": "INS"}}

Note that each parameter is wrapped with the name of the parameter in the parm rule.

 

Note:
With respect to consuming a Rest service (it can be generated by GeneXus or not), GeneXus provides the OpenAPI import tool.

 

Next, read Procedures as REST: Using SDT as input to the procedure

See Also

Rest web services in GeneXus