Rest
A rest api datasource for the datatable or other components
import { Rest } from "@schukai/monster/source/components/datatable/datasource/rest.mjs";Introduction
The REST API Datasource Component is a powerful tool for enabling seamless integration with server-side RESTful APIs within your web applications. Designed as a foundational building block for data-driven components like tables, this component ensures robust, efficient, and intuitive data handling.
By bridging the gap between client-side interactivity and server-side data management, this component simplifies the process of fetching, manipulating, and displaying data in your application. Whether you're creating a lightweight web app or an enterprise-grade solution, the REST API Datasource Component enhances your application's responsiveness and user experience.
Key Features
- Seamless Data Integration: Automatically fetches and synchronizes data with REST APIs, providing real-time updates for your application.
- Customizable Query Parameters: Flexibly configure filters, sorting, pagination, and more to match your application's requirements.
- Event-Driven Architecture: Built-in support for custom events like data fetching, error handling, and success notifications, ensuring smooth user interactions.
- Intersection Observer Support: Optimized for lazy loading, fetching data dynamically as elements come into view.
- Auto-Initialization: Streamlines the setup process with configurable automatic initialization options.
- Reusable and Modular: Easily integrates into various components, such as data tables, ensuring consistency and reusability across your application.
Enhancing Development Efficiency
The modular design of the REST API Datasource Component simplifies its integration into any web project. It supports standard web technologies and adheres to modern development practices, reducing the time and complexity involved in managing data-centric features.
Developers benefit from programmatic control over core functionalities like data reading and writing, as well as the ability to customize behaviors through options and configurations. This flexibility accelerates the development process and ensures compatibility with existing tools and workflows.
The REST API Datasource Component is an indispensable resource for developers aiming to build modern, data-driven web applications with a focus on efficiency, scalability, and maintainability.
Lookup Columns
This guide explains how to enrich datatable rows with lookup values that are fetched from secondary APIs. The lookup runs inside the REST datasource and only during read()/fetch().
What the feature does
- Keeps the original ID in the dataset.
- Writes the lookup result to a new target field (for example
brandDisplay). - Optionally toggles a loading flag per row for skeleton styling.
- Deduplicates requests per lookup column and caches results in memory.
- Supports both remote lookup APIs and local resolver functions.
When to use it
Use lookup columns when your main dataset contains IDs or codes that must be replaced with human-readable labels, icons, or combined content.
Basic setup
- Enable lookups on the REST datasource.
- Configure lookup columns.
- Use the lookup target field in the datatable template.
HTML
<monster-datasource-rest
id="products-ds"
data-monster-options='{
"features": { "autoInit": true },
"read": { "url": "/api/products", "method": "get" }
}'>
</monster-datasource-rest>
<monster-datatable
id="products"
data-monster-datasource-selector="#products-ds">
<template id="products-row">
<div data-monster-head="ID" data-monster-mode="fixed"
data-monster-replace="path:products-row.id"></div>
<div data-monster-head="Brand"
data-monster-attributes="class path:products-row.brandLoading | ?:lookup-cell monster-skeleton-col-30 monster-skeleton-animated:lookup-cell"
data-monster-replace="path:products-row.brandDisplay | default:--"></div>
</template>
</monster-datatable>
JavaScript
const ds = document.querySelector("#products-ds");
ds.setOption("lookups.enabled", true);
ds.setOption("lookups.sourcePath", "dataset");
ds.setOption("lookups.columns", {
brand: {
key: "brandId",
target: "brandDisplay",
loadingKey: "brandLoading",
url: "/api/brands",
response: { path: "data", id: "id" },
format: {
template: '<span class="lookup-pill"><span class="${icon}"></span>${name}</span>',
},
},
});
Configuration reference
lookups (root)
lookups.enabled(boolean, defaultfalse): Enables lookup resolution onread()/fetch().lookups.sourcePath(string, defaultdataset): Path to the rows inside the main datasource payload.lookups.request.idsParam(string, defaultids): Query parameter name for batched IDs.lookups.request.idsSeparator(string, default,): Separator when multiple IDs are sent.lookups.response.path(string, defaultdataset): Path to the array of lookup entries in the lookup response.lookups.response.id(string, defaultid): Field name of the ID in each lookup entry.lookups.format.template(string, default${name}): Default template for rendering a lookup entry.lookups.format.marker.open/lookups.format.marker.close: Custom template markers if you do not want${}.lookups.columns(object): Map of lookup column definitions.
lookups.columns.<name>
key(string, required): Field name in the row that contains the lookup ID.target(string, required): Field name where the lookup result will be stored.loadingKey(string, optional): Boolean field toggled while the lookup is pending.url(string, optional): Lookup API endpoint. If omitted,resolvemust be provided.response.path/response.id(optional): Override the lookup response mapping for this column.request.idsParam/request.idsSeparator/request.init(optional): Override request settings for this column.format(object or function, optional): Ifformatis a function:format(entry, row)returns a string/HTML. Ifformatis an object: useformat.templateand optionalformat.marker.resolve(function, optional): Local resolver for lookups that do not need a URL. Receives(value, row).
Response mapping examples
Default response format
{
"dataset": [
{ "id": 15, "name": "Apex" }
]
}
No extra config needed because response.path defaults to dataset and response.id defaults to id.
Custom response format
{
"meta": { "status": 200 },
"data": [
{ "id": "019b...", "name": "Hosen" }
]
}
Configure the response path:
ds.setOption("lookups.columns.category.response", { path: "data", id: "id" });
URL templates
You can embed the batched IDs into the URL instead of using a query parameter:
ds.setOption("lookups.columns.brand.url", "/api/brands?ids=${ids}");
The ${ids} placeholder will be replaced by the joined ID list.
Caching and deduplication
- Each lookup column has an internal cache and pending set.
- IDs are fetched once per datasource instance.
- Results are reused for subsequent reads until the datasource instance is destroyed.
Notes and limitations
- Lookups run only for
read()/fetch(). - Lookup changes update the datasource dataset and therefore re-render the datatable.
- If you need to reset the cache, recreate the datasource instance.
Validation Mapping
When the API returns validation errors, map them to bind paths so the form can attach messages to the correct controls.
<monster-datasource-rest
data-monster-option-response-path-validationErrors="meta.validationErrors"
data-monster-option-response-path-validationMessage="meta.message"
data-monster-option-validation-map='{"name":"path:data.name","email":"path:data.email"}'
></monster-datasource-rest>
Use data-monster-option-labels on the form to override messages by validation code.
API Contract Checklist
- Response wraps data consistently (for example
datasetwith objects). - Validation errors live in a stable path (for example
meta.validationErrors). - Validation errors include
codeand/ormessage. data-monster-option-response-path-validationErrorspoints to the correct JSON path.data-monster-option-response-path-validationMessagepoints to a human-readable message.data-monster-option-validation-mapexists for keys that do not match bind paths.- Optional:
labels.<CODE>entries exist for i18n overrides. - Write payload format matches what the API expects (dataset vs. object).
Simple Rest Datasource
As you can see, there's nothing to see. This isn't surprising, as this component doesn't have any visible elements and only provides data, for example, for the data table.
In the code tab, you can see how the tags are structured. There, you'll notice that the monster-datasource-rest tag has one attribute: data-monster-option-read-url. This attribute is used to specify the URL from which the data should be fetched.
Javascript
import '@schukai/monster/source/components/datatable/datasource/rest.mjs';HTML
<!--
Data source for the datatable
You can use the monster-datasource-rest component to fetch data from a REST API and populate
a datatable with it. In this example, we use only the data-monster-option-read-url attribute to
specify the URL from which the data should be fetched.
-->
<monster-datasource-rest
data-monster-option-read-url="/assets/examples/countries.json">
</monster-datasource-rest>Stylesheet
/** no additional stylesheet is defined **/Auto Init
In this example, too, you can't really see much. But we have still included a text. However, this is only decorative. Look at the code tab to understand the example.
Javascript
import '@schukai/monster/source/components/datatable/datasource/rest.mjs';HTML
<!--
Data source for the datatable with auto init
You can use the monster-datasource-rest attribute
data-monster-option-features-autoInit to automatically initialize
the data source when the component is created. In this example,
we use the data-monster-option-read-url attribute to specify
the URL from which the data should be fetched.
The Autoinit feature offers two additional configuration options:
1. data-monster-option-autoinit-intersectionObserver
This attribute allows you to control whether loading
should only occur when the data source is within the visible viewport.
2. data-monster-option-autoinit-onetime:
This attribute determines whether loading should happen once or multiple times.
Important: For multiple loads, intersectionObserver must be set to true.
-->
<monster-datasource-rest style="display: flex;"
data-monster-option-features-autoinit="true"
data-monster-option-read-url="/assets/examples/countries.json">
This is a slotted content
</monster-datasource-rest>Stylesheet
/** no additional stylesheet is defined **/Rest Datasource With Fetch
This example demonstrates how to manually work with the DataSource. Since we are not using Auto-Init, data must be explicitly fetched by calling the read method.
The method uses the URL defined in the read configuration to query the data. The URL can include various placeholders, such as:
- filter: For specific query criteria.
- orderBy: For sorting the results.
- page: For specifying the page number.
These placeholders must be inserted into the URL, e.g., for the page: ${page}.
Further settings and details can be found in the REST Datasource documentation.
Javascript
import '@schukai/monster/source/components/datatable/datasource/rest.mjs';
const restAPI = document.getElementById("Re9Oo")
const codeOutput = document.getElementById("Ui0Ee")
// here we set the page to 4, in this example the page is hardcoded and has no effect
restAPI.setOption('read.parameters.page', "4")
// here we read the data from the API and display it in the codeOutput element
restAPI.read().then((response) => {
// here we display the data in the codeOutput element
codeOutput.innerHTML = JSON.stringify(restAPI.data, null, 4)
}).catch((error) => {
// if there is an error, we log it to the console
console.error(error)
})HTML
<monster-datasource-rest style="display: flex;" id="Re9Oo"
data-monster-option-read-url="/assets/examples/countries.json?page=${page}">
This is a slotted content
</monster-datasource-rest>
<strong>Result</strong>
<pre><code id="Ui0Ee"></code></pre>Stylesheet
/** no additional stylesheet is defined **/HTML Structure
<monster-rest></monster-rest>JavaScript Initialization
const element = document.createElement('monster-rest');
document.body.appendChild(element);Exported
RestDerived from
DatasourceOptions
The Options listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class. Therefore, it inherits Options from these parent classes. If you cannot find a specific Options in this list, we recommend consulting the documentation of the Datasource.
- since
- deprecated
Properties and Attributes
The Properties and Attributes listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class and ultimately from HTMLElement. Therefore, it inherits Properties and Attributes from these parent classes. If you cannot find a specific Properties and Attributes in this list, we recommend consulting the documentation of the Datasource.
data-monster-options: Sets the configuration options for the collapse component when used as an HTML attribute.data-monster-option-[name]: Sets the value of the configuration option[name]for the collapse component when used as an HTML attribute.
Methods
The methods listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class and ultimately from HTMLElement. Therefore, it inherits methods from these parent classes. If you cannot find a specific method in this list, we recommend consulting the documentation of the Datasource.
Constructor
constructor()Behavioral methods
fetch()deprecated since 2024-12-24- {Promise
|*}
read instead.read()- {Promise}
monster-datasource-fetchmonster-datasource-fetchedmonster-datasource-error
reload()deprecated since 2023-06-25- {Promise
|*}
read instead.write()- {Promise}
Structural methods
setParameters()undefined{string}: page
- {Rest}
Static methods
[instanceSymbol]()- {symbol}
instanceof operator.getCSSStyleSheet()- {CSSStyleSheet[]}
getTag()- {string}
Lifecycle methods
Lifecycle methods are called by the environment and are usually not intended to be called directly.
[assembleMethodSymbol]()- {void}
connectedCallback()disconnectedCallback()Other methods
initIntersectionObserver()- {Rest}
autoInit.intersectionObserver must be set to false.Events
The component emits the following events:
monster-datasource-fetchmonster-datasource-fetchedmonster-datasource-error
For more information on how to handle events, see the mdn documentation.