Adding reference array to Sanity document via Python HTTP API mutation
I can see the issue with your mutation structure! When creating array fields (like your variants array of references) in Sanity via the HTTP API, you don't need to specify the _type and of properties in the data itself - those are schema definitions. You should just provide the array of reference objects directly.
Here's the corrected mutation structure:
mutations = []
for taxon in Taxons:
for product in taxon.products:
mutations.append({
'createOrReplace': {
'_type': 'product',
'_id': product.id,
'name': product.name,
'composition': product.composition,
'coo': product.coo,
'slug': product.slug,
'minimumOrderQuantity': product.moq,
'orderIncrement': product.oqi,
'reference': product.reference,
'variants': [
{
'_type': 'reference',
'_ref': variant.id,
'_key': variant.key
}
for variant in product.variants
]
}
})
mutation = {
'mutations': mutations
}The key changes:
- Remove the wrapping object:
'variants'should directly be an array[...], not{'_type': 'array', 'of': [...]} - Keep the reference structure: Each item in the array should still have
_type: 'reference',_ref, and_key
About _key constraints: According to the Sanity documentation on IDs and Paths, keys follow similar rules to document IDs - they should be strings made up of a-zA-Z0-9._- characters, cannot start with a dash, and must not have more than one consecutive period. As long as your variant.key values follow these rules, you should be fine.
Important note: Each _key within an array must be unique within that array. Sanity uses these keys internally to track items across changes. If you're reusing the same value for both variant.id and variant.key, that's perfectly acceptable as long as each variant has a unique key within the product's variants array.
If you're still experiencing crashes after this change, it might be worth checking:
- That all your
variant.idvalues actually exist as document IDs in your dataset - That your
variant.keyvalues are unique within each product's variants array - That the variant documents you're referencing are of the correct document type that your schema expects
Show original thread5 replies
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.