🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

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:

<https://mySanityId.api.sanity.io/v2021-06-07/data/query/production?query=*[_type> == "registrationForm" && references($id)]&$id="abcdef123456"
But if I remove the
&& references($id)
the request returns all registration form documents with no error:

<https://mySanityId.api.sanity.io/v2021-06-07/data/query/production?query=*[_type> == "registrationForm"]&$id="abcdef123456"

Example #2
400 error:

<https://mySanityId.api.sanity.io/v2021-06-07/data/query/production?query=*[_id> == $id]{"registrations": *[_type == "registrationForm" && references(^._id)]}&$id="abcdef123456"
Again, if I remove the references part of the query then it returns correctly with the rest of the user data:

<https://mySanityId.api.sanity.io/v2021-06-07/data/query/production?query=*[_id> == $id]&$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:

<https://mySanityId.api.sanity.io/v2021-06-07/data/query/production?query=*[_type> == "registrationForm" %26%26 references($id)]&$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}.<http://api.sanity.io/v2021-06-07/data/query/production|api.sanity.io/v2021-06-07/data/query/production>` 
  endpoints: (builder) => ({
    getUserRegistrations: builder.query({
      query: (id) => `?query=${userRegistrationsQuery}&$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?