Webflow Magic: Effortlessly Fetch & Display API Data
As of today, Webflow has a new feature called Logic. With Webflow Logic, you can construct and perform automated workflows (also known as “flows”) that collect and route sales leads, connect with your customers, manage your site content, and more — all from within the Webflow Designer.
However, a simple flow to replace a text element with fetched data from an API is still not available. This simple feature should have been included in Logic from day 1, but it is not.
Fortunately, with some custom code, you can still perform this task. You can follow the steps below.
This JavaScript code snippet fetches data from an API and updates the text content of specified elements with the fetched data.
Usage
- Add unique classes or IDs to the elements you want to update with the fetched data.
- Replace the example API endpoint, response properties, and element classes/IDs in the code snippet below with the specific ones you need for your project:
window.addEventListener('load', function() {
fetch('https://api.example.com/your-endpoint')
.then(response => response.json())
.then(data => {
// Update the element with the fetched data
const value = data.propertyName;
document.querySelector('.your-element-class').textContent = value;
// Add more elements and properties as needed
});
});
- Copy and paste the modified JavaScript code inside the <script> tags in the Footer Code section of your project settings.
Customization
The code snippet can be customized by changing the API endpoint, modifying the elements’ class names or IDs, and updating the data properties to match your project’s structure.
- To change the API endpoint, replace the URL in the fetch function with the desired endpoint:
fetch('https://api.example.com/your-endpoint')
- To update the class names or IDs, replace the class names or IDs in the document.querySelector method with the desired ones:
document.querySelector('.your-custom-class').textContent = value;
- To add more elements and properties, repeat the process of updating an element with the fetched data:
const anotherValue = data.anotherPropertyName;
document.querySelector('.another-element-class').textContent = anotherValue;
Compatibility
This code is compatible with modern web browsers that support the fetch
API and should work without any issues in most projects. However, it's always a good practice to test the functionality on different devices and browsers to ensure it works as expected.
Thanks for reading! I am Daris Ali Mufti a UI UX Designer based in Jakarta Indonesia. Still a lot to learn! any insights, differing opinions, or advice are always welcome. I am always open to having a dialogue with others and recognize that I am not an industry expert just yet.