Adding reference array to Sanity document via Python HTTP API mutation

5 replies
Last updated: Nov 2, 2022
Hi All! I’m currently working on some bulk upload for uploading product catalogs to sanity via a python script (later to be made into lamda function). All is going quite smoothly however… I am trying to make a mutation for the HTTP API that adds a reference to each variant per product. My mutation looks as follows

mutations = []
  for taxon in Taxons:
    for product in taxon.products:
      mutations.append({
        'createOrReplace': {
          '_type': 'product',
          '_id': product.id,
          'name': product.name,
          # 'description': product.description,
          'composition': product.composition,
          'coo': product.coo,
          'slug': product.slug,
          'minimumOrderQuantity': product.moq,
          'orderIncrement': product.oqi,
          'reference': product.reference,
          # 'leadtime': product.leadtime,
          'variants': {
            '_type': 'array',
            'of': [
              {
                '_type': 'reference',
                '_ref': variant.id,
                '_key': variant.key
              }
              for variant in product.variants
            ]
          }
        }
      })
  
  mutation = {
    'mutations': mutations
  }
However when I call this, the products are created in such a way that they crash the desk, as so…

Edit: Note that variant.id and variant.key are both strings and are currently the same thing. I set the ID when I upload the variants originally and so have assumed I can reuse them for references.
AI Update

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:

  1. Remove the wrapping object: 'variants' should directly be an array [...], not {'_type': 'array', 'of': [...]}
  2. 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.id values actually exist as document IDs in your dataset
  • That your variant.key values 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 thread
5 replies
see attached
Hey
user U
! What immediately stands out to me is that your variants array isn't structured correctly. If that field is an array in your schema, you directly set the array. No need to wrap it in an object with a specified
_type
!
Hazar I’ve fixed it.

mutations.append({
        'createOrReplace': {
          '_type': 'product',
          '_id': product.id,
          'name': product.name,
          # 'description': product.description,
          '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
          ]
        }
      })
Fantastic!!
Fantastic!!

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?