How to hide unpublished documents in Sanity API response?

3 replies
Last updated: Sep 14, 2020
Also another question not related with the above one. Is there a way to limit the response in the API? i mean, if i want to hide "unpublished" documents in the API response? (havent tested, is a question my colleagues made me)
AI Update

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 default
  • previewDrafts - Returns draft versions when they exist, falls back to published versions
  • raw - 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 thread
3 replies
The drafts only show up using authenticated requests, but you can filter them with GROQ. See this article https://www.sanity.io/docs/drafts
Thank you
user B
, but if using authenticated requests, all the data of my document Studio will be available, right?
Yes, that's correct. Drafts don't show in the unauthenticated API by default though, only published documents.

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.

Was this answer helpful?