Consuming a Rest Service with GeneXus

Official Content

With GeneXus you can consume any Rest service (generated with GeneXus or not).
In some cases, service documentation (YAML file) is available. In this case, you can inspect the YAML using the OpenAPI import tool) and generate the consumer object and the related structured data types automatically.

When you don't have the YAML specification, you should have the following information to consume the service (besides the service Uri):

  • The method to call the service (i.e: GET, POST)
  • The expected body to call the service and its representation (Json, XML, etc) - in case it should be called using a POST.

So, to consume a Rest service, consider the following:

1. The way to consume a REST web service in GeneXus is by using the HttpClient data type. You can have all the objects generated automatically if you use the OpenAPI import tool when the service provides YAML documentation. In this case, you don't need to consider the next items.

2. If you have the expected body (if it's JSON), it can be inspected using the Json import tool to have the SDT created automatically in the KB. Otherwise, you should create it manually. 

3. Depending on the Http verb used, the parameters should be passed in the query string (GET) or in the body (POST).

4. Remember that the correct content type headers should be sent. For instance, for a JSON body, the code should be as follows:

&httpClient.AddHeader(!"Content-Type", !"application/json")

5. Error handling is achieved using the HttpClient data type as well.

Example

Suppose that you have the service Uri (http://server:8080/BaseUrl/AddCustomer) and you have to call the service using the POST HTTP method.
You are given the JSON format of the "Customer" so you should create a CustomerSDT structured data type to load the data to be passed to the service.

So, the code would be as follows:

&httpclient.Host = "server"
&httpclient.Port = 8080
&httpclient.Secure = 0
&httpclient.BaseUrl = "Baseurl"

//load &customersdt
&body = &customersdt.ToJson() 
 
&httpclient.AddHeader('Content-type','application/json')
&httpclient.AddString(&body)

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

In the following links you have different examples to call a Rest service using different HTTP methods:

 

 

Was this page helpful?
What Is This?
Your feedback about this content is important. Let us know what you think.