Official Content

You can consume any Rest Service with GeneXus, whether it's been generated with it or not.

In some cases, service documentation (the 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 URI service):

  • 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.

Samples

Suppose you have the URI service (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"/rest

//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()

See Also

Consuming a Business Component exposed as Rest with GeneXus
HowTo: Consume a Rest Data Provider
HowTo: Consume a Procedure exposed as a Rest service

Last update: February 2024 | © GeneXus. All rights reserved. GeneXus Powered by Globant