Sanity is a structured content platform with a powerful query language called GROQ. The free tier includes generous API usage — 500K API requests/month and 20GB bandwidth.
Setting Up
npm create sanity@latest -- --project-id your-id --dataset production
Get your project ID and dataset from manage.sanity.io.
Querying with GROQ
GROQ (Graph-Relational Object Queries) is Sanity's query language — more powerful than REST, simpler than GraphQL.
import { createClient } from "@sanity/client";
const client = createClient({
projectId: "your-project-id",
dataset: "production",
apiVersion: "2024-01-01",
useCdn: true
});
// Get all blog posts, ordered by date
const posts = await client.fetch(
`*[_type == "post"] | order(publishedAt desc) {
title,
slug,
publishedAt,
"authorName": author->name,
"categories": categories[]->title,
"imageUrl": mainImage.asset->url
}`
);
posts.forEach(p => console.log(`${p.title} by ${p.authorName}`));
Advanced GROQ Queries
// Count posts per category
*[_type == "category"] {
title,
"postCount": count(*[_type == "post" && references(^._id)])
}
// Full-text search
*[_type == "post" && title match "React*"] {
title, slug, publishedAt
}
// Pagination
*[_type == "post"] | order(publishedAt desc) [0..9] {
title, slug
}
Mutations — Create and Update
// Create a document
await client.create({
_type: "post",
title: "New Post via API",
slug: { current: "new-post-via-api" },
publishedAt: new Date().toISOString()
});
// Patch an existing document
await client
.patch("document-id")
.set({ title: "Updated Title" })
.commit();
Real-Time Listening
const subscription = client
.listen(`*[_type == "post"]`)
.subscribe(update => {
console.log(`${update.transition}: ${update.result?.title}`);
});
Use Cases
- Headless websites: Pair with Next.js, Remix, or Astro for blazing-fast sites
- Content workflows: Custom publishing pipelines with real-time collaboration
- Structured data: Rich schema definitions with references and validation
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)