Sanity API versions not returning key except v1
Based on the context, this statement is part of a discussion about how different Sanity API versions handle empty or unset fields in GROQ queries.
The key difference:
- API v1: Completely omits fields from the response when they're empty or unset - the key doesn't appear at all in the returned JSON
- API v2 and later versions (like v2021-03-25): Return
nullfor empty/unset fields when you explicitly request them in a projection
Why this happens:
When you write a GROQ query with a projection like *[]{_id, type->name}, you're explicitly asking for those fields. In API versions after v1, GROQ honors this request by including the key in the response even when the value doesn't exist - but it sets it to null rather than omitting it entirely.
This is particularly relevant when:
- A user clears a string field in Sanity Studio (the field gets removed from the document entirely, not set to an empty string)
- You're querying referenced documents where fields might not be set
- You're migrating from v1 to newer API versions
Solutions to handle this:
Use the coalesce() function to provide fallback values:
*[_type == 'movie']{name, 'rating': coalesce(rating, '')}Add validation rules to make fields required and prevent them from being cleared
Handle null values in your application code when consuming the API response
The original discussion thread also mentions an interesting edge case where the Vision plugin showed correct values while production API calls returned null - this was resolved by adding the specific projection to the webhook query, likely due to API version differences between the two contexts.
Show original thread35 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.