DEV Community

Explorer
Explorer

Posted on

🌐 Integrate External REST API Data into Joget Dropdown Using BeanShell Script

Overview

In this guide, you’ll learn how to dynamically populate a Joget dropdown field using data fetched from an external REST API.

This is especially useful when you want to display live data from APIs (internal or third-party) directly in your Joget forms.


Full Script (with explanations)



import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.apps.form.service.FormUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import org.joget.commons.util.LogUtil;

public FormRowSet load(String[] values) {

    LogUtil.info("API Loader", "Received parameter: " + values[0]);
    String param = values[0];
    FormRowSet rows = new FormRowSet();

    try {
        // Example API endpoint
        URL url = new URL("https://jsonplaceholder.typicode.com/posts?id=" + param);

        // HTTP connection setup
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        // Read API response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        conn.disconnect();

        // Parse JSON response
        JSONArray jsonArray = new JSONArray(content.toString());
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            FormRow apiOption = new FormRow();
            apiOption.setProperty(FormUtil.PROPERTY_VALUE, jsonObject.getString("title"));
            apiOption.setProperty(FormUtil.PROPERTY_LABEL, jsonObject.getString("title"));
            rows.add(apiOption);
        }

    } catch (Exception e) {
        LogUtil.error("API Error", e, "Error fetching data from API");
    }

    return rows;
}

// Execute the loader
return load(values);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)