Guide to Generating URLs and Using WebStudio Variables for Sanity GROQ Queries

Date

This guide will help you construct URLs for querying the Sanity API using GROQ queries within WebStudio. It covers how to incorporate WebStudio variables into your queries, considering the limitations of the Expression Editor (e.g., lack of support for functions like encodeURIComponent()).


Overview

  • Objective: Build a URL that includes a GROQ query with variables from WebStudio.
  • Challenges:
    • WebStudio’s Expression Editor doesn’t support functions like encodeURIComponent().
    • Variables need to be included directly in the URL.
  • Solution: Pre-encode the GROQ query and carefully insert variables into the encoded string.

Step-by-Step Instructions

1. Write Your GROQ Query with Placeholders

Begin by writing your GROQ query using placeholders for the variables you want to include.

Example GROQ Query:

groqCopy code*[_type == "{collection}"
  && title match "{title}*"
  && project._ref == "{project}"
  && company._ref == "{company}"] {
    title,
    _id,
    slug,
    stage,
    pageType,
    "project": project->{
      title,
      _id,
    },
    "company": company->{
      title,
      _id,
      "imageUrl": mainImage.asset->url
    },
    "mainImageUrl": mainImage.asset->url
  }
  • Placeholders: {collection}, {title}, {project}, {company} will be replaced with variables from WebStudio.

2. URL-Encode the Query with Placeholders

Use an online URL encoder to encode the entire query, ensuring that placeholders remain intact.

URL-Encoded Query with Placeholders:

perlCopy code*%5B_type%20%3D%3D%20%22{collection}%22%0A%20%20%26%26%20title%20match%20%22{title}%2A%22%0A%20%20%26%26%20project._ref%20%3D%3D%20%22{project}%22%0A%20%20%26%26%20company._ref%20%3D%3D%20%22{company}%22%5D%20%7B%0A%20%20title%2C%0A%20%20_id%2C%0A%20%20slug%2C%0A%20%20stage%2C%0A%20%20pageType%2C%0A%20%20%22project%22%3A%20project-%3E%7B%0A%20%20%20%20title%2C%0A%20%20%20%20_id%2C%0A%20%20%7D%2C%0A%20%20%22company%22%3A%20company-%3E%7B%0A%20%20%20%20title%2C%0A%20%20%20%20_id%2C%0A%20%20%20%20%22imageUrl%22%3A%20mainImage.asset-%3Eurl%0A%20%20%7D%2C%0A%20%20%22mainImageUrl%22%3A%20mainImage.asset-%3Eurl%0A%7D

3. Identify Encoded Sections for Variable Insertion

Break the encoded query into parts, identifying where each placeholder is located.

Example Breakdown:

  • Part 1 (Before {collection}):perlCopy code*%5B_type%20%3D%3D%20%22
  • Insert {collection} Variable
  • Part 2 (Between {collection} and {title}):perlCopy code%22%0A%20%20%26%26%20title%20match%20%22
  • Insert {title} Variable
  • Part 3 (Between {title} and {project}):perlCopy code%2A%22%0A%20%20%26%26%20project._ref%20%3D%3D%20%22
  • Insert {project} Variable
  • Part 4 (Between {project} and {company}):perlCopy code%22%0A%20%20%26%26%20company._ref%20%3D%3D%20%22
  • Insert {company} Variable
  • Part 5 (After {company}):perlCopy code%22%5D%20%7B...%7D

4. Construct the URL in WebStudio’s Expression Editor

In the Expression Editor, build the URL by concatenating the parts and inserting variables.

Expression Example:

javascriptCopy code// Base URL and start of the query
'https://your-project-id.api.sanity.io/v2022-03-07/data/query/production?query='

// Part 1: Before `{collection}`
+ '*%5B_type%20%3D%3D%20%22'

// Insert `collection` variable
+ system.search.collection

// Part 2: Between `{collection}` and `{title}`
+ '%22%0A%20%20%26%26%20title%20match%20%22'

// Insert `title` variable
+ system.search.title

// Part 3: Between `{title}` and `{project}`
+ '%2A%22%0A%20%20%26%26%20project._ref%20%3D%3D%20%22'

// Insert `project` variable
+ system.search.project

// Part 4: Between `{project}` and `{company}`
+ '%22%0A%20%20%26%26%20company._ref%20%3D%3D%20%22'

// Insert `company` variable
+ system.search.company

// Part 5: After `{company}`
+ '%22%5D%20%7B...%7D'

// Append the perspective parameter
+ '&perspective=published'

Note: Replace '...%7D' in Part 5 with the rest of the encoded query (fields and projections).


5. Ensure Variables Are URL-Safe

Because you can’t use encodeURIComponent() in WebStudio, variables must be URL-safe.

  • Allowed Characters:
    • Letters (a-z, A-Z)
    • Numbers (0-9)
    • Hyphens (-)
    • Underscores (_)
  • Disallowed Characters:
    • Spaces
    • Special characters (e.g., !, @, #, $, %, ^, &, *, (, ), etc.)

If Variables May Contain Disallowed Characters:

  • Option 1: Preprocess variables outside of WebStudio to remove or replace special characters.
  • Option 2: Ensure that inputs provided in WebStudio are restricted to URL-safe characters.

6. Input the Expression into WebStudio

  1. Open the URL Field:
    • Navigate to the field where you need to input the URL.
  2. Access the Expression Editor:
    • Click on the {} or fx icon next to the URL field.
  3. Paste the Expression:
    • Copy the constructed expression and paste it into the editor.
  4. Save and Test:
    • Save the expression.
    • Test the URL to ensure it’s working as expected.

7. Test the URL

  • Use Known Values:
    • Replace variables with actual values to test the URL.

Example with Hardcoded Values:

javascriptCopy code'https://your-project-id.api.sanity.io/v2022-03-07/data/query/production?query=*[_type=="projectWebpage"
  && title match "home*"
  && project._ref == "project-id"
  && company._ref == "company-id"] {
    title,
    _id,
    slug,
    // other fields
  }&perspective=published'
  • Test in Browser or API Client:
    • Paste the URL into a browser or use an API client like Postman to test the response.

8. Troubleshoot Common Issues

Issue: No Results Returned

  • Verify Data:
    • Ensure that documents matching the query exist in your Sanity dataset.
    • Check that the fields (title, project._ref, company._ref) have the expected values.

Issue: Variables Not Substituted

  • Check Variable Names:
    • Ensure that the variable names in your expression match those defined in WebStudio.
    • For example, use system.search.title if that’s the correct variable.

Issue: Syntax Errors

  • Verify Expression Syntax:
    • Ensure all strings are properly concatenated.
    • Check for unmatched quotes or missing + operators.

9. Additional Tips

  • Start Simple:
    • Begin with a basic query using one variable.
    • Gradually add more variables and conditions as you confirm each part works.
  • Use Console Logs (If Available):
    • Some environments allow you to log variable values for debugging.
    • Example: console.log(system.search.title)
  • Consult WebStudio Documentation:
    • Refer to WebStudio’s resources for specific syntax and features.
    • Understand how variables are accessed and used in expressions.

Example of a Complete Expression

Assuming Variables:

  • system.search.collection
  • system.search.title
  • system.search.project
  • system.search.company

Expression:

javascriptCopy code'https://your-project-id.api.sanity.io/v2022-03-07/data/query/production?query='
+ '*%5B_type%3D%3D%22'
+ system.search.collection
+ '%22%0A%20%20%26%26%20title%20match%20%22'
+ system.search.title
+ '%2A%22%0A%20%20%26%26%20project._ref%20%3D%3D%20%22'
+ system.search.project
+ '%22%0A%20%20%26%26%20company._ref%20%3D%3D%20%22'
+ system.search.company
+ '%22%5D%20%7B%0A%20%20title%2C%0A%20%20_id%2C%0A%20%20slug%2C%0A%20%20stage%2C%0A%20%20pageType%2C%0A%20%20%22project%22%3A%20project-%3E%7B%0A%20%20%20%20title%2C%0A%20%20%20%20_id%2C%0A%20%20%7D%2C%0A%20%20%22company%22%3A%20company-%3E%7B%0A%20%20%20%20title%2C%0A%20%20%20%20_id%2C%0A%20%20%20%20%22imageUrl%22%3A%20mainImage.asset-%3Eurl%0A%20%20%7D%2C%0A%20%20%22mainImageUrl%22%3A%20mainImage.asset-%3Eurl%0A%7D'
+ '&perspective=published'

Key Takeaways

  • Variables Must Be URL-Safe:
    • Since you can’t URL-encode variables in the Expression Editor, ensure they contain only URL-safe characters.
  • Pre-Encode the Query:
    • Encode the GROQ query with placeholders and insert variables directly into the encoded string.
  • Careful String Construction:
    • Pay attention to quotes and concatenation to avoid syntax errors.
  • Test Incrementally:
    • Build and test your expression step by step to identify any issues early.

Conclusion

By following these steps, you can successfully generate URLs that include GROQ queries with variables from WebStudio. This method works within the limitations of WebStudio’s Expression Editor and allows you to dynamically fetch data from the Sanity API based on user inputs or other variables in your project.


If you have any questions or need further assistance, feel free to reach out!

More
ARTICLES

Pinpoint your brand vision with my style quiz. You’ll get a free downloadable brand board and even generate a homepage with your personal brand style!