Fetch Data from APIs

Load data from external APIs dynamically
LokaScript now supports the native fetch URL as json syntax! You can also use the call fetch() method with JavaScript's Fetch API.

Two Methods:
call fetch JSON async

Demo 0: Native Fetch Syntax (LokaScript)

Test the built-in fetch URL as json syntax:

Demo 1: Fetch User Data

Click the button to load a random user from JSONPlaceholder API:

Demo 2: Load Blog Posts

Load a list of posts from the API:

Demo 3: Error Handling

Try fetching from an invalid endpoint to see error handling:

❌ Error:

The Code

Basic Fetch:

<button _="on click fetch 'https://api.example.com/data' as json put it into #output"> Load Data </button>

With Loading State:

<button _="on click add .loading to me show #spinner fetch 'https://api.example.com/users' as json put it into userData -- Process the data hide #spinner remove .loading from me"> Fetch </button>

Loop Through Results:

<button _="on click fetch 'https://api.example.com/posts' as json put it into posts set html to '' repeat for post in posts set html to html + `<div>${post.title}</div>` end put html into #list"> Load Posts </button>

Error Handling:

<button _="on click fetch 'https://api.example.com/data' as json if it == null put 'Error: Failed to load data' into #error-message show #error-box else put it into #output end"> Load </button>

How it works:

Key Concepts:

Response Type Options:

HTTP Methods (with options):

<!-- POST request --> fetch '/api/users' as json with { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', email: 'john@example.com' }) } put it into newUser <!-- PUT request --> fetch '/api/users/1' as json with { method: 'PUT', body: JSON.stringify({ name: 'Updated Name' }) } put it into updatedUser <!-- DELETE request --> fetch '/api/users/1' with { method: 'DELETE' } log 'User deleted'

Common Use Cases:

Try it yourself: