How to read and write to a Sanity Content Lake via tokens

6 replies
Last updated: Nov 29, 2021
How do i
read
and
write
to my content lake via tokens. I am Not using Sanity Studio, but from my own application i want to read and write data. Do i have to shape my data in GRAQ way, or is it simple
JSON
object
Post
?
AI Update

Great question! You can absolutely read and write to your Content Lake from your own application without using Sanity Studio. Here's how it works:

Reading Data

For reading data, you'll use the HTTP Query API to execute GROQ queries. Yes, you do need to use GROQ (not "GRAQ") to query your content, but it's actually quite intuitive once you get started.

A basic query looks like:

GET https://<projectId>.api.sanity.io/<apiVersion>/data/query/<dataset>?query=*[_type == "post"]

You can also use parameters in your GROQ queries (prefixed with $) which is safe for user input since they're JSON literals that get substituted into the query.

Writing Data

For writing data, you'll use the Mutation API, and here's the good news: you write simple JSON objects, not GROQ! The Mutation API accepts standard JSON documents.

You have several mutation operations available:

  • create - Creates a new document (fails if ID exists)
  • createIfNotExists - Only creates if the ID doesn't exist
  • createOrReplace - Creates or overwrites existing document
  • patch - Updates specific fields in existing documents
  • delete - Removes documents

Example JSON for creating a document:

{
  "mutations": [
    {
      "create": {
        "_type": "post",
        "title": "My Post",
        "content": "Post content here"
      }
    }
  ]
}

For drafts, prefix the ID with drafts.:

{
  "create": {
    "_id": "drafts.post-123",
    "_type": "post",
    "title": "Draft Post"
  }
}

Authentication

You'll need to create an API token in Sanity Manage:

  1. Run npx sanity@latest manage or access Manage from your Studio
  2. Go to the API tab
  3. Create a token with appropriate permissions (Viewer for read-only, Editor for write access)
  4. Store it securely in environment variables

Important security note: Never expose write tokens in frontend code! Use them only in server-side environments, API routes, or serverless functions.

Add the token to your requests via the Authorization header:

Authorization: Bearer <your-token>

Quick Summary

  • Reading: Use GROQ queries via the Query API
  • Writing: Use simple JSON objects via the Mutation API
  • Auth: API tokens with appropriate permissions
  • Security: Keep write tokens server-side only

The Mutation API supports transactions too, so you can perform multiple operations atomically. One thing to note: when using the HTTP API directly, you're responsible for your own validation - the Studio's schema validation doesn't automatically apply at the API level.

Hi Dev-Thoughts. You can use the http API to send JSON objects (along with your token) that represent the changes you want to make. Those get sent to a url that each project has ready to accept changes to your data. Here's some examples of the format you send the JSON in: https://www.sanity.io/docs/http-patches . As far as the token goes, you send it along with your request in the headers, so for example using axios I usually do something like this:
const options = {
    url: `https://${projectId}.<http://api.sanity.io/v2021-06-07/data/mutate/production|api.sanity.io/v2021-06-07/data/mutate/production>`,
    method: 'post',
    data: myChangesArePatchesInHere,
    headers: {
      'Content-type': 'application/json',
      'Authorization': `Bearer ${token}`
    }
};

let data = await axios.request(options) ...
Or, you can use one of the
client libraries , which each have a syntax of their own, and can incorporate GROQ queries if needed. For the token there, (for the JavaScript client anyway) you pass your token into a new instance of the client object, and then use that client instance to operate on your data: https://www.sanity.io/docs/js-client#api
Thank you
user U
this is useful for me. Though i wonder, when i will
post
a small object
{
  blog Name: ....
  Des: ...
  Date:...
}  
to the content lake where will it store or how will i pull back? For example with Sanity studio i can see my block post etc. How can i simply
fetch
back then object i write to Content lake?
Hi - so, I think am getting your question, but let me know if not. Your data will end up "in" the studio as if you had entered it there. So, for example, if you have defined in your schema a document type called
Foods
and you add a food with the title "Pizza" through an HTTP request, a new
Food
called "pizza" will pop right into view on your studio.
If you mean how can you get data back immediately after you make the request, you can add query parameters to configure what is returned to you as a result of your post/change/patch, the details of that are here:
https://www.sanity.io/docs/http-mutations#ac77879076d4 . By default I believe you will always be returned a transaction which will have an id that you can query later through the history API to get the details if needed.
In the end, your Content Lake is your content lake and you can pull and push data to it in many different ways! The studio makes it easy to get the structure of things going, and then have a solid foundation to build additional CRUD on.
Yes, your answer is something i am trying to understand. 🙂
So if i understood right. I do need to have predefined schema in Sanity Studio to be able to
write, read, delete
from somewhere else?
Hi - well, yes, ideally. Technically speaking, however, if you have the token you can write to your dataset even if the schema doesn't match. It will just show up as an unknown field in your studio. For example, let's say I have some code that for some reason adds a value for a field called
price
on my pizza document, even though I have not yet created the field in my schema. When I visit that document in the studio it will notify me that there is a field with data that isn't in the schema. I can then add it to the schema in my studio code, and it will be accessible and "normal" like all the other data, or I could delete the value in the studio.
This is making sense now for me, i have started to implement the get request and play with project. Thank you
user U

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?