In part I we only used the design-time support of the components. As a reminder, this is what our application will look like:
Our base is an assortment of controls found in the Embarcadero REST library that is delivered with Delphi:
The first part explains the setup in great detail. We will now write the source code in order to allow the user to look up shows by their name. Then we will extend the functionality that will allow us to list all the episodes.
All the components are already in place. We just need to provide the graphical components for the user to enter the series title, the button to initiate the lookup and the grid to display the values.
- In order to be able to use a grid, drop a TDataSource (dsLookup) on the form and connect it to tblLookup.
- Drop a TEdit (txtTitle) and TButton (btnSearch) component on the form.
- Implement the OnClick event of the button:
procedure TFrmMain.btnSearchClick(Sender: TObject); begin RequestLookup.Params.ParameterByName('title').Value := txtTitle.Text; RequestLookup.Execute; AdapterLookup.Active := True; end;
- Drop a TDBGrid on the form and connect it to the datasource. Align and select the columns as you see fit.
This form should look somewhat like this in the designer:
In the OnClick event we set the parameter ‘title’ to the value that the user entered in the TEdit. We can use it ‘as is’ the framework will make sure that it will be encoded correctly. Then we execute the request and open the adapter to display the results. Error handling is included – yes. If you read the documentation you will see that the Execute method will not toss an exception – ever. It is your responsibility to check the Status property of the response if the request was successfull. We simply do nothing and the user will see that something is wrong if there is no result being shown … (With the form setup you will also be able to have a look at the response though…)
To make sure that all the datasets are in the correct state, add the following implementation for the OnCreate event of the form:
procedure TFrmMain.FormCreate(Sender: TObject); begin AdapterLookup.Active := False; AdapterShow.Active := False; tblLookup.Close; tblShow.Close; end;
Here’s a demo what it looks like if you search for ‘Star Trek’:
As you can see, the REST API is rather smart as it does not only list precise matches. That is exactly the functionality we were looking for. Next we will add another request that will enable us to display all the episodes of a show. Furthermore, it will show how to restrict the dataset adapter to a subset of the JSON result.