Getting started overview

Sanity.io offers a platform for structured content management, enabling developers to define content models and manage data through the Sanity Studio. Content is stored in the Sanity Content Lake, accessible via a real-time API. This guide outlines the process of initiating a Sanity.io project, obtaining necessary API credentials, and executing a foundational content retrieval request.

The initial setup involves creating an account, establishing a new project, and deploying the Sanity Studio. Accessing content programmatically requires project IDs and dataset names, which are used in API requests. Sanity.io utilizes GROQ (Graph-Relational Object Queries) for querying content, which allows for filtering, projection, and joining of data from the Content Lake (Sanity.io GROQ syntax documentation).

Quick Reference: Sanity.io Onboarding Steps

Step What to Do Where
1. Sign Up Create a Sanity.io account Sanity.io registration page
2. Create Project Initialize a new project, choose a template, and deploy the Studio. Note your Project ID. Sanity.io dashboard (after login)
3. Retrieve Credentials Locate Project ID and default Dataset name. Generate API tokens if write access is needed. Sanity.io project settings
4. Install CLI Install the Sanity CLI globally for local development. Terminal: npm install -g @sanity/cli
5. Local Studio Setup Initialize and run the Sanity Studio locally. Local project directory: sanity init, then sanity start
6. Query Content Construct a GROQ query to retrieve content from the Content Lake. API client, browser, or Sanity.io Vision tool

Create an account and get keys

To begin using Sanity.io, navigate to the Sanity.io account registration page. You can sign up using an email address, or through third-party authentication providers such as Google or GitHub. Upon successful registration, you will be directed to the Sanity.io dashboard.

From the dashboard, create a new project. You will be prompted to name your project and select an initial template, which can include starter schemas for blogs, e-commerce, or a blank canvas. During this process, Sanity.io will automatically deploy a Sanity Studio instance, which is the content editing interface. It is crucial to note your Project ID, as this identifier is essential for all API interactions (Sanity.io project creation guide).

Sanity.io projects typically come with a default dataset, often named production. This dataset name, along with your Project ID, forms the base for your API endpoints. For read-only access to public content, no explicit API keys are usually required, as long as the dataset is public. However, for write operations, or for accessing private content, you must generate API tokens. These tokens can be created and managed within your project settings under the "API" section. When creating a token, specify its permissions (e.g., read, write, deploy) and its scope (Sanity.io API tokens documentation).

For local development and interaction with your Sanity.io project, install the Sanity CLI globally using npm:

npm install -g @sanity/cli

Once installed, you can initialize a local Sanity Studio instance within a project directory by running sanity init and following the prompts to connect it to your cloud project. This CLI tool is also used for deploying schemas, managing datasets, and other development tasks.

Your first request

After setting up your project and obtaining your Project ID and dataset name, you can make your first API request to retrieve content. Sanity.io uses GROQ for querying its Content Lake. A basic read request does not typically require an API token if the content is public. The API endpoint follows this structure: https://<PROJECT_ID>.api.sanity.io/v1/data/query/<DATASET_NAME>.

Consider a scenario where your Sanity Studio has a document type named post with fields like title and slug. To fetch all post titles and slugs, your GROQ query might look like *[_type == "post"]{title, "slug": slug.current}.

Here's an example using curl to query your content:

curl "https://<YOUR_PROJECT_ID>.api.sanity.io/v1/data/query/<YOUR_DATASET_NAME>?query=*%5B_type%20%3D%3D%20%22post%22%5D%7Btitle%2C%20%22slug%22%3A%20slug.current%7D"

Replace <YOUR_PROJECT_ID> with your actual Sanity.io Project ID and <YOUR_DATASET_NAME> with your dataset (e.g., production). The query string parameters must be URL-encoded. You can use an online URL encoder for complex queries, or write the query directly in the Sanity.io Vision tool within your Studio to test it.

For programmatic access in a JavaScript environment, you would typically use the Sanity client library:

import { createClient } from '@sanity/client'

const client = createClient({
  projectId: '<YOUR_PROJECT_ID>',
  dataset: '<YOUR_DATASET_NAME>',
  apiVersion: '2023-05-03', // use current date (YYYY-MM-DD) to enable latest features
  useCdn: true, // set to false to get fresh data at the cost of a little speed
})

async function getPosts() {
  const query = `*[_type == "post"]{title, "slug": slug.current}`
  const posts = await client.fetch(query)
  console.log(posts)
}

getPosts()

This client configuration points to your specific project and dataset. The apiVersion ensures consistency with API features available on that date (Sanity.io JavaScript client documentation). The useCdn option can be toggled based on whether you need the freshest data (false) or prefer cached responses for performance (true).

Common next steps

After successfully retrieving content, several common next steps enhance your Sanity.io experience and integration:

  • Define Content Schemas: Customize your content models by defining schemas for various document types. This involves modifying the schema files in your local Sanity Studio project (e.g., schemas/post.js) to reflect the structure of your content (Sanity.io schema documentation).
  • Deploy Sanity Studio: Once your local Studio is configured and content schemas are defined, deploy it to the cloud. This makes your content editing interface accessible to team members. Use the Sanity CLI command sanity deploy.
  • Integrate with a Frontend Framework: Connect your Sanity.io Content Lake to a frontend framework like React, Next.js, Vue, or Svelte. Sanity.io offers various starter kits and examples for popular frameworks (Sanity.io integration guides).
  • Implement Webhooks: Set up webhooks to trigger actions in external services when content changes occur in Sanity.io. This is useful for rebuilding static sites, invalidating caches, or sending notifications (Sanity.io webhooks reference). Webhooks are a common pattern in API-driven architectures for real-time data synchronization, as described in Twilio's webhook security guide.
  • User Management and Roles: Invite team members to your Sanity.io project and assign appropriate roles and permissions to control access to content and project settings. This is managed through the Sanity.io dashboard.
  • Explore GROQ: Deepen your understanding of GROQ to construct more complex and efficient queries for specific content retrieval needs. The Sanity.io GROQ reference provides extensive examples and syntax details.

Troubleshooting the first call

When making your initial API call to Sanity.io, several common issues may arise:

  • Incorrect Project ID or Dataset Name: Verify that the projectId and dataset values in your API request match those found in your Sanity.io project settings. Even a single character mismatch will result in an authentication or resource not found error.
  • URL Encoding: Ensure that your GROQ query is properly URL-encoded when used as a query parameter in a direct HTTP request (e.g., with curl). Special characters like [, ], {, }, &, and spaces must be encoded. Tools like the Sanity.io Vision tool can help validate queries before encoding.
  • CORS Issues: If you are making requests from a browser-based application, you might encounter Cross-Origin Resource Sharing (CORS) errors. Ensure that the origin domain of your frontend application is added to the "CORS Origins" list in your Sanity.io project settings. This setting explicitly allows requests from specified domains (Sanity.io CORS configuration).
  • Public vs. Private Datasets and API Tokens: If your dataset is private or you are attempting write operations, you must include an API token with appropriate permissions in your request headers. For read-only access to public datasets, tokens are generally not required. Check the dataset visibility settings in your project.
  • Schema Mismatches: If your GROQ query refers to document types or fields that do not exist in your current content schemas, the query may return an empty array or an error. Verify that the types (e.g., _type == "post") and field names (e.g., title, slug.current) accurately reflect your defined schemas.
  • API Version: While not always a direct cause of failure for basic queries, using an outdated apiVersion in your client configuration can lead to unexpected behavior or prevent access to newer API features. It is recommended to use the current date (YYYY-MM-DD) for consistency (Sanity.io client options).