How to get documents that reference a specific document in GET requests to the Sanity API.
3 replies
Last updated: Oct 5, 2021
R
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:
But if I remove the
Example #2
400 error:
Again, if I remove the references part of the query then it returns correctly with the rest of the user data:
Can you not use
Thank you in advance!
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"
&& 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"
<https://mySanityId.api.sanity.io/v2021-06-07/data/query/production?query=*[_id> == $id]&$id="abcdef123456"
references()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
R
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:
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
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.