How to set and add items to an array using HTTP API

3 replies
Last updated: Feb 11, 2025
using the http api how do I set a specific object array using the index?maybe this?

"set": {
  "data": {
    "34" : {
      "field": "value"
    }
  }
}
AI Update

No, the approach you suggested won't work for setting a specific array element by index. In Sanity's HTTP API patch operations, you cannot directly target array elements by numeric index in the set operation like that.

To modify a specific array element, you have a few options:

1. Use JSONMatch path syntax with the array index:

The correct way is to use the path notation in your set operation:

{
  "patch": {
    "id": "document-id",
    "set": {
      "data[34].field": "value"
    }
  }
}

This targets the element at index 34 in the data array and sets its field property.

2. Target by a unique identifier (recommended):

If your array objects have a _key field (which they should for arrays of objects), it's better to target by that:

{
  "patch": {
    "id": "document-id", 
    "set": {
      "data[_key==\"unique-key-here\"].field": "value"
    }
  }
}

This is more reliable because array indices can change if items are added or removed, but _key values remain stable.

3. Replace the entire array element:

You can also replace the whole element at a specific index:

{
  "patch": {
    "id": "document-id",
    "set": {
      "data[34]": {
        "_key": "some-key",
        "field": "value",
        "otherField": "otherValue"
      }
    }
  }
}

The key takeaway is that you use the path notation (like "data[34].field") in the keys of your set object, not as nested objects like in your example. The Sanity documentation on patches explains this uses JSONMatch syntax for targeting specific values in documents.

im also not sure how you add new items to the array using the http api. I assume I get the length of the array and append an item with
"index": object
or is there a shorter way?
ahh I got it working finally:
"set": {
  "data": [{
    "_key": "2134",
    "_type": "bar",
    "field": value
  }]
}
making new entries makes sense now since its formatted like a normal document type.

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?