Notifications
Clear all

[Solved] What is the proper way to authenticate with Model REST API's?

1 Posts
1 Users
0 Reactions
909 Views
0
Topic starter

The Platform SDK documentation talks about creating Model REST API's to read and write from data models.

Here is a link to that section of the documentation:
https://devnet.onenetwork.com/oms/apps/DeveloperNetwork/www/docs/guides/SdkUsersGuide/help/index.html#RestAPIs

I set up a Model REST API per the steps in the documentation. However, when I attempt to POST data to the new Model REST API, I get a 401 Unauthorized response code.

What are the proper headers and authentication to send when connecting to a Model REST API?

(If it matters, I want to connect to a Model API from the Java class of a custom interface. Specifically I am calling the "executeAction" method for writing data.)

Thank you!

1 Answer
0
Topic starter

Thanks to Yang Cao for explaining the commonly used method for inserting data into Models. (The Model API documentation mentions REST and gives a URL, but the SDK has a Java method for interacting with Models.)

There is a Java Class called ModelDataService. To write data to models from Java, we typically call the method [ModelDataService].write();

Here is a full example (parsing JSON and inserting into the Model 'Item'):

        //Read values from the POST body.
        JSONObject obj = new JSONObject(contents); //convert the JSON string into an object
        String enterprise = obj.getString("enterprise");
        String itemName = obj.getString("itemName");
        Float price = (float) obj.getDouble("price");
        Integer valueChainID = obj.getInt("valueChainID");

        //Initialize a ModelList
        ModelList<Item> modelList = new ModelList<Item>();
        modelList.setActionName("PLT.InsertOrUpdate");
        modelList.setValueChainId(valueChainID);

        //Initialize an Item using data from the POST body.
        Item newItem = new Item();
        newItem.setName(itemName);
        newItem.setValueChainId(valueChainID);
        newItem.setPriceAmount(price);
        newItem.setEnterpriseName(enterprise);

        List<Item> items = new ArrayList<Item>();
        items.add(newItem);

        //Add the Item to the ModelList
        modelList.getModels().addAll(items);

        //Write the ModelList to the database
        ModelDataService mds = Services.get(ModelDataService.class);
        ModelList returnedList = mds.write(modelList, ctx);

        if (returnedList.getListError() != null || returnedList.getErrors().size() > 0) {
          throw new Exception("Unable to create catalog for esg companies : " + returnedList.getListError().getValue());
        }