API INTEGRATION PROCESS
1. Reviewed API Documentation:
- I carefully read the provided API documentation to understand the available endpoint. In my case template 6 there is only one available endpoint (/products).
- I have identified the structure of the data returned by the API, including field names and data types. It is an array of objects so an easy task to understand the structure.
- I don’t need any changes to be made in the schema I have done earlier. Because I first documented the data need then crafted schema so it has helped me alot.
2. Set Up API Calls
- I have used browser developer tools to test API endpoint (/product) and ensure that data was returned correctly.
- I have created importData.mjs file to fetch data from API.
- Added script to package.json to run command “import-data” to fetch data from API and post it to Sanity.
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"import-data": "node scripts/importData.mjs"
},
- Now it is time to create product schema in /sanity/schemaTypes/product.ts.
import { defineType } from "sanity"
export const product = defineType({
name: "product",
title: "Product",
type: "document",
fields: [
{
name: "title",
title: "Title",
validation: (rule) => rule.required(),
type: "string"
},
{
name:"description",
type:"text",
validation: (rule) => rule.required(),
title:"Description",
},
{
name: "productImage",
type: "image",
validation: (rule) => rule.required(),
title: "Product Image"
},
{
name: "price",
type: "number",
validation: (rule) => rule.required(),
title: "Price",
},
{
name: "tags",
type: "array",
title: "Tags",
of: [{ type: "string" }]
},
{
name:"dicountPercentage",
type:"number",
title:"Discount Percentage",
},
{
name:"isNew",
type:"boolean",
title:"New Badge",
}
]
})
- Here is the next step to create Sanity client with the token to developer access (read, write, management).
- Environment variables are set in .env file and here is the code to create client.
const client = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
useCdn: true,
apiVersion: '2025-01-26',
token: process.env.SANITY_API_TOKEN,
});