Why REST APIs

Before we explore specific APIs and demos, I’d like to discuss the relevance of using APIs in the context of a client application like those built with Delphi. In the past, the most common way to add a feature to a program was to write the proper code or use an existing library to add the capability, and distribute the compiled code of the feature along with the application. 

Today’s online services and REST APIs often offer similar capabilities activated by passing proper parameters with an HTTP call to a server and receiving back the result. Examples include image transformations, creating a PDF, transforming text to speech or reading the text embedded in an image.

Why would you use one approach over the other? There are cases in which only one of the alternatives is realistic (fast performance graphic rendering requires an installed graphic library while an AI capability is generally available online), but in other scenarios both approaches might be possible.

Using a local library has the advantage of:

  • Generally faster execution

  • No need of an Internet connection

  • Possibly the ability of fine tuning and customizing the feature and tying it better with the code and UI

  • At the security level, you don’t need to worry about the communication being encrypted to avoid someone accessing to application data in transit

Using a REST APIs has the advantage of:

  • Keeping the app smaller, as you don’t need to distribute extra library code

  • Always use the latest version of the library, as it can be updated separately from the client application

  • At the security level, you don’t need to worry about updating the library in case any issue is discovered, having to deploy a new version of the application

Finally, there is often a difference between the costs of a library vs. a REST API:

  • Unless the library is free and open source, it would generally have an upfront fixed per-developer cost

  • Most REST APIs have a pay per use model, often with a free level you can use for development and testing

  • So the REST API might be cheaper for limited use, but become more expensive for extensive use

Introducing APILayer

APILayer is an Idera business focused on offering hosted APIs and on creating an API Marketplace, hosting also third-party APIs. You can read more about the many available services at https://apilayer.com/

There are many powerful APIs as part of APILayer, and while some make more sense in a web application (like IpStack), many others make perfect sense also in a client application, like the file processing services offered by FileStack (https://www.filestack.com/) or the nifty third-party email verification Api (https://apilayer.com/marketplace/email_verification-api).

In my demo below I’d focus on a simple APIs, possibly not the most powerful one: WeatherStack, which as the name implies can deliver current, historical and forecast data about the weather:

https://weatherstack.com/

Using RAD Studio REST Debugger

Once you have identified the REST API you plan to use, the easiest way to start developing a client application is to use the REST Debugger, available as part of RAD Studio installation (and accessible from the Tools menu) and also as a separate free download for anyone (https://www.embarcadero.com/free-tools/rest-debugger).

The debugger offers the ability to configure a REST API, save that configuration for future use (or to share it with another developer), and import the configuration in a Delphi or C++Builder application.

In a simple case, like that of WeatherStack, after you start the REST Debugger you first have to configure the primary endpoint:

Next you need to set the proper parameters configuration, including the specific endpoint (current), the query parameter and the access_key authentication information:

The parameters depend on the endpoint and are listed in the API documentation. At this point you can use the SendRequest button to try the API and check the response in the bottom portion of the REST Debugger UI:

The resulting data structure is relatively complex, but we can filter out some of the nested tables (like location visible above) in a table structure. Given we are likely looking for the current data, we can use that JSON root element to get the data in a table structure:

Building an Actual Demo in Delphi

Once you are happy with the configuration and the data A(possibly including the table data) you can use the Copy Component button of the REST Debugger to streamline the development of an application. This button, in fact, captures the REST Client Library components configuration and allows you to  paste it into a form or data module in the RAD Studio IDE.

In this case I just created a simple FireMonkey application with Delphi, added a data module, and pasted the components configuration in it. It results in the following data module:

The actual configuration of the components is the following:

object DataModule14: TDataModule14
  object RESTClient1: TRESTClient
    BaseURL = 'http://api.weatherstack.com'
  end
  object RESTRequest1: TRESTRequest
    Client = RESTClient1
    Params = <
      item
        Name = 'access_key'
        Value = 'xxxxxxxxxxxxxxxxx'
      end
      item
        Name = 'query'
        Value = 'Piacenza, Italy'
      end>
    Resource = 'current'
    Response = RESTResponse1
  end
  object RESTResponse1: TRESTResponse
    RootElement = 'current'
  end
  object RESTResponseDataSetAdapter1: TRESTResponseDataSetAdapter
    Dataset = FDMemTable1
    Response = RESTResponse1
    TypesMode = JSONOnly
  end
  object FDMemTable1: TFDMemTable
    FetchOptions.AssignedValues = [evMode]
    FetchOptions.Mode = fmAll
  end
end

As you the see, the RESTClient component has the overall configuration of the site, the RESTRequest refers to the endpoint and its parameters, the optional RESTResponse component holds the results and can pass it via the RESTResponseDataSetAdapter component to an in-memory table, the FDMemTable component.

At this point, what you need in the main form is a button to make the call and an edit box with the location and a display component (I’ve used a read only edit box). In the button’s OnClick event handler, you can write some code like the following:

procedure TForm13.BtnRefreshClick(Sender: TObject);
begin
  DataModule14.RESTRequest1.Params[1].Value := EditLocation.Text;
  DataModule14.RESTRequest1.Execute();
  EditCurrent.Text := DataModule14.FDMemTable1.FieldByName('temperature').AsString;
end;

As an alternative, you can tie the input and the out via Visual LiveBindings, connecting the input edit to the request parameters and the specific field of the in-memory table to the output control.To be able to do this, you first have to execute the HTTP request at design time, using a specific command of the RESTRequest component. This populates components metadata, including the in-memory table. After doing it, you can wire the input and the output in the LiveBindings designer, and reside the code executed when pressing the button to:

DataModule14.RESTRequest1.Execute();

This is the LiveBindings designer configuration:

And finally, this is the application at runtime, in this hot summer day:

Conclusion

As you have seen, implementing a client for a REST API in Delphi is relatively simple (I already demonstrated the same in the past covering a different API here). Now in the case of a weather application there aren’t many alternatives compared to accessing live data from a web service, while in other scenarios using an API would be an alternative compared to embedding the same feature in a library part of the application.

We plan to showcase a few more of APILayer’s APIs on the Embarcadero blog, so stay tuned and feel free to share your ideas with us.