Join live – Get insights, tips, + Q&A from Sanity developers on our latest releases

How to get documents that reference a specific document in GET requests to the Sanity API.

3 replies
Last updated: Oct 5, 2021
When making GET requests to the Sanity api, how can I get documents that reference a specific document?
I've tried two different ways and I always get a 400 error (in my app and in Postman when making the same requests).

Example #1
400 error:

<*[_type> == "registrationForm" &amp;&amp; references($id)]&amp;$id="abcdef123456"
But if I remove the
&amp;&amp; references($id)
the request returns all registration form documents with no error:

<*[_type> == "registrationForm"]&amp;$id="abcdef123456"

Example #2
400 error:

<*[_id> == $id]{"registrations": *[_type == "registrationForm" &amp;&amp; references(^._id)]}&amp;$id="abcdef123456"
Again, if I remove the references part of the query then it returns correctly with the rest of the user data:

<*[_id> == $id]&amp;$id="abcdef123456"
Can you not use
in HTTP queries or is there some syntax I am missing?
Thank you in advance!
Oct 4, 2021, 8:53 PM
Hi Riley. It could be that your ampersands need to be encoded. Could you try:

<*[_type> == "registrationForm" %26%26 references($id)]&amp;$id="abcdef123456"
Oct 4, 2021, 9:15 PM
That did it! I just needed to encode the GROQ query ampersands. Didn't realize that I hadn't been using ampersands in my other requests so it wasn't a problem before.
I'm using RTK Query to make the requests so I'll leave a sample of my code if it is helpful to anyone:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

const userRegistrationsQuery = `
  *[_type == 'addRegistrationForm' %26%26 references($id)]

export const sanityApi = createApi({
  reducerPath: 'sanityApi',
  baseQuery: fetchBaseQuery({ 
    baseUrl: `https://${process.env.SANITY_PROJECT_ID}.<|>` 
  endpoints: (builder) =&gt; ({
    getUserRegistrations: builder.query({
      query: (id) =&gt; `?query=${userRegistrationsQuery}&amp;$id="${id}"`

export const {useGetUserRegistrationsQuery} = sanityApi

Oct 5, 2021, 3:09 PM
Awesome! Thanks for the follow-up and leaving the snippet for others. 😄
Oct 5, 2021, 3:10 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?