SR
Click to open github profile
Usage

Build Query URLs

Learn how to create custom query URLs for fetching data from Craft CMS.


In this guide, you’ll learn to use the useCraftUrlBuilder() composable to build custom query URLs for your Craft CMS backend. This approach offers precise control over the data you retrieve, allowing you to specify fields and configure queries to suit your needs.

Build an URL

The useCraftUrlBuilder() composable lets you construct a query URL step-by-step. Here’s how to set up a query URL to fetch a list of related news articles:

const queryUrl = useCraftUrlBuilder('entries')
  .section('news')
  .fields(['title'])
  .limit(3)
  .buildUrl('one')

//result = https://your-primary-site-url/v1/api/queryApi/customQuery?elementType=entries&id=1&status=active&one=1
Tip

Find out more about the available query methodes in the useCraftQuery() docs.

Fetch with Query URLs

After building the query URL, you can use it in a fetch function to retrieve data:

For example:

const queryUrl = useCraftUrlBuilder('entries')
  .section('news')
  .fields(['title'])
  .limit(3)
  .buildUrl('one')

const data = ref(await fetchData(queryUrl));
Warning

You probalby want to have an error handling that fits your needs.

Here is a small fetch function with some error handling in place.

~/utils/fetcher.ts
export async function fetchData(url: string) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to fetch data from ${url}: ${response.statusText}`);
  }

  return await response.json();
}

This approach allows you to fetch only the data you need from Craft CMS and you can do that wherever you need it.


Copyright © 2024 Samuel Reichör