How to hide unpublished documents in Sanity API response?
Yes! You can absolutely control whether unpublished (draft) documents appear in your API responses using perspectives. This is exactly what they're designed for.
By default (as of API version 2025-02-19), Sanity uses the published perspective, which means you'll only get published documents - no drafts will be returned. This is typically what you want for production environments.
How to use perspectives
You can specify the perspective in your API requests using the perspective parameter:
To hide unpublished documents (production):
https://YOUR_PROJECT_ID.api.sanity.io/v2025-02-19/data/query/YOUR_DATASET?query=*[_type=="post"]&perspective=published
The available perspectives are:
published- Only returns published documents (excludes drafts) - this is the defaultpreviewDrafts- Returns draft versions when they exist, falls back to published versionsraw- Returns everything including both drafts and published documents
In your client code
If you're using the JavaScript client, you can set the perspective like this:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'production',
useCdn: true,
apiVersion: '2025-02-19',
perspective: 'published' // Only published documents
})Additional GROQ filtering
You can also explicitly filter out drafts in your GROQ queries if needed:
*[_type == 'post' && !(_id in path("drafts.**"))]This ensures that even if the perspective includes drafts, they won't be in your results.
So to answer your colleagues: yes, the API respects the perspective setting, and with perspective=published (the default), unpublished documents are automatically hidden from your responses!
Show original thread3 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.