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));

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

~/composables/useCraftFetch.ts
export async function useCraftFetch(url: string) {
  const { authToken } = useCraft()
  const response = await fetch(url, {
    headers: {
      Authorization: authToken,
    }
  });

  if (!response.ok) {
    throw new Error(`Failed to fetch data from ${url}: ${response.statusText}`);
  }

  return await response.json();
}

Copyright © 2025 Samuel Reichör