Use SAP Leonardo as a keyword to search on wechat, you can find many articles. But WHEN I looked around, I didn’t see anything from a specific programming point of view. So I’m going to contribute one.

demand

Develop a Java program, the user can specify a picture, the Java program calls SAP Leonardo trained machine learning API, the API will recognize the picture, return a text message to the user, telling the user the recognition result.

  1. Visit https://api.sap.com and click on API:

Click on Product Image Classification API:

You will see the following screen. The interface contains an introduction to the API’s Model Schema, which fields are included in the response structure returned after you call the API, and the corresponding types (objects or arrays). The interface includes a small API call console, where you can directly select a local graphics file and click the Try It Out button to experience the EFFECTS of the API.

For example, I used the following image to test:

  1. Download SDK there is a button in the upper right corner of the API console from the previous step. Click to Download the SDK locally:

After the import is complete, see the figure. The red areas are code that comes with the SDK, and the blue areas are code that Jerry created manually himself to call the API and print the results.

Double-click pom.xml in the root directory to maintain the following dependencies:

For simplicity, in line 13 above I hard-coded the absolute address of the local image file. The hard-coded API key in line 8 above comes from the API console:

At this point, done, run the program… What’s going on?

Error analysis

Looking through the error messages, Jerry soon figured out what the problem was. The blue underline in the figure above hints at the root of the error. The SAP SDK uses Gson, an open source Java library published by Google, to deserialize the responses returned by the API into Java objects. With Gson, application developers don’t have to reinvent the wheel, just define Java classes that act as containers to store the results of Gson deserialization.

Back in the API console, the request field in the API response structure is declared to be of type String.

However, testing shows that the content of the Request field is actually a Json object:

In the SDK from http://api.sap.com, the Gson container class Response. Java declares a request field of type String, not object, so Gson throws an exception: Expected a string but was BEGIN_OBJECT at line 31 column 15 path $.request

https://github.com/i042416/ProductImageMLService

More Leonardo wonderful, all at https://api.sap.com!

For more of Jerry’s original technical articles, please follow the public account “Wang Zixi” or scan the following QR code: