AG Grid server-side row model with paginated RESTful API and JS


Ag Grid Logo

All the AG Grid provided sample codes refer to a fake server when doing server-side row data. This leaves a new user to figuring out how they would like to build the server fetch from an actual API. The following code helps illustrate how to work with AG Grid by pulling from an actual RESTful API.

The example code uses the freeStar Wars API, SWAPI. This example focuses on utilizing the SWAPI Planets. Also the example is based off AG Grid's evaluation enterprise license.

Simple HTML starter file index.html

code
<div class="container">
    <div class="row">
        <div class="col-12">
            <h1>AG Grid Server Side Row Model with RESTful API and JS</h1>
            <p>Grid takes a bit to load, give it a few seconds. Pen generated using AG Grid evaluation Enterprise license key.</p>

            <div id="myGrid" class="ag-theme-alpine" style="height: 550px;"></div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/ag-grid-enterprise@30.2.0/dist/ag-grid-enterprise.min.js"></script>
<script src="swapi-ag-grid.js"></script>

The swapi-ag-grid.js file.

code
const apiUrl = "https://swapi.dev/api/planets/";

// AG Grid
const columnDefs = [];

const gridOptions = {
    defaultColDef: {
        sortable: true,
        resizable: true,
        flex: 1,
        minWidth: 150
    },

    // use the server-side row model
    rowModelType: "serverSide",
    animateRows: true,
    pagination: true,
    cacheBlockSize: 10,
    paginationPageSize: 10,
    getContextMenuItems: getContextMenuItems,
    sideBar: {
        toolPanels: [
            {
                id: "columns",
                labelDefault: "Columns",
                labelKey: "columns",
                iconKey: "columns",
                toolPanel: "agColumnsToolPanel",
                toolPanelParams: {
                    suppressPivotMode: true,
                    suppressRowGroups: true,
                    suppressValues: true
                }
            }
        ],
        defaultToolPanel: ""
    }
};

// Set initial grid on page load
document.addEventListener("DOMContentLoaded", () => {
    const gridDiv = document.querySelector("#myGrid");
    const headers = {
        'Content-Type': 'application/json',
    };

    fetch(`${apiUrl}`, {
        method: "GET",
        headers
    })
        .then((response) => response.json())
        .then((data) => {
        new agGrid.Grid(gridDiv, gridOptions);
        dynamicallyConfigureColumnsFromObject(data.results[0]);
        const datasource = createServerSideDatasource();
        gridOptions.api.setServerSideDatasource(datasource);
    });
});

async function getServerData(url) {
    const response = await fetch(url, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        },
    });
    const data = await response.json();
    return {
        rowData: data.results,
        rowCount: data.count,
    };
};

// Create server-side datasource
function createServerSideDatasource() {
    return {
        getRows: async (params) => {
            const { request } = params;
            const { endRow, count, startRow, sortModel, filterModel } = request;
            let page = endRow / gridOptions.paginationPageSize
            const url = `${apiUrl}?limit=${gridOptions.paginationPageSize}&page=${page}`;
            const { rowData, rowCount } = await getServerData(url);

            if (rowData.length) {
                params.success({ rowData, rowCount });
            } else {
                params.fail();
            }
        }
    };
}

// Determine options provided when right click within grid
// Called by grioOptions
function getContextMenuItems(params) {
    var result = ["copy", "copyWithHeaders"];
    return result;
}

function dynamicallyConfigureColumnsFromObject(anObject) {
    const colDefs = gridOptions.api.getColumnDefs();
    colDefs.length = 0;
    const keys = Object.keys(anObject);
    keys.forEach((key) => colDefs.push({ field: key }));
    gridOptions.api.setColumnDefs(colDefs);
}

Here is a CodePen embed to see the code in action.


More articles tagged: ag-grid javascript