We can query and update the Sanity documents by sending the HTTP request to the specific Sanity API route. Sanity_io uses GROQ language to define exactly what data we need/mutate. You can read more about Sanity GROQ on the below page.
To query the Sanity data, we can send the HTTP request to the below API route.
https://<projectId>.api.sanity.io/v2021-06-07/data/query/<dataset>?query=*
Please note that the projectId
and dataset
in the URL string matches your Sanity project credential.
The response to the above HTTP request from the Sanity Query is as below:
{
"ms": <server-side processing time>,
"query": <submitted query>,
"result": <query result>
}
You can find your Sanity projectId
and dataset
from the sanity dashboard as below.
In the code, we can send the get request to the above URL to fetch the data. But we gonna use the @sanity/client
official package to fetch, and mutate the data.
To install the package, we can execute the below command in the terminal.
npm install @sanity/client
After installing the package, run the command npm run develop
to start the server.
To make use of @sanity/client
, we can create a file at the location src/lib/sanity/sanityActions.js
, and write the below code.
import createClient from "@sanity/client"
const client = createClient({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
useCdn: false, // set to `false` to bypass the edge cache
apiVersion: "2023-05-03", // use current date (YYYY-MM-DD) to target the latest API version
token: process.env.GATSBY_SANITY_BEARER_TOKEN, // Only if you want to update content with the client
})
export const sanityRequest = async query => {
try {
const request = await client.fetch(query)
return request
} catch (err) {
return []
}
}
export const sanityCreate = async (action, post) => {
try {
let result
if (action == "createOrReplace") {
result = client.createOrReplace(post)
} else if (action == "createIfNotExists") {
result = client.createIfNotExists(post)
} else {
result = client.create(post)
}
return result
} catch (err) {
return []
}
}
export const sanityUpdate = async (_id, obj) => {
try {
const result = client.patch(_id).set(obj).commit()
return result
} catch (err) {
return []
}
}
To run the above function correctly, we need to define the below secret variables .env
.
GATSBY_SANITY_PROJECT_ID
GATSBY_SANITY_DATASET
GATSBY_SANITY_BEARER_TOKEN
As for now, the Sanity Server dataset is public which means that anyone can send requests to the Sanity server. This could be harmful because if someone deletes the data, then you'll be the responsible person.
It's is always a good practice to make your dataset Private so that it is accessible with a token or by authenticated users. We can change the dataset to private from the sanity dashboard as below.
Now, we need to create a token in the Sanity Dashboard that we can use to send the request. We can create the token as below.
We need to save this token into the .env
file of the Gatsby project. Later, we can use this token to send the request.
Now, To test the function (sanityActions.js
), we can create a serverless function at the below location:
src/api/testquery.js
import { sanityRequest } from "../lib/sanity/sanityActions"
export default async function handler(req, res) {
const action = req?.body?.action || req?.query?.action
const query = req?.body?.query || req?.query?.query
let data = null
if (action == "get") {
data = await sanityRequest(query)
}
res.status(200).send({
action: action,
data: data,
})
}
To test the above function, We can use Postman to send the request to the URL localhost:8000/api/testquery
and navigate to Sanity Studio as below.
Above, we have defined a query to fetch the subscription for the specified _id
.
To update the Sanity document, we can update the code for the function (testquery.js
) as below.
import { sanityRequest, sanityUpdate } from "../lib/sanity/sanityActions"
export default async function handler(req, res) {
const action = req?.body?.action || req?.query?.action
const query = req?.body?.query || req?.query?.query
const updatedobj = req?.body?.updatedobj || req?.query?.updatedobj
const _id = req?.body?._id || req?.query?._id
let data = null
if (action == "get") {
data = await sanityRequest(query)
} else if (action == "update") {
data = await sanityUpdate(_id, updatedobj)
} else {
data = null
}
res.status(200).send({
action: action,
data: data,
})
}
We can use Postman to update the Sanity document as shown below.
Later in this course, We can use this function to create and update the user's subscriptions.