I’ve been working a lot with Python over the last few months and one piece of work I’ve spent quite a lot of time on is interfacing Python solutions with Cosmos DB.
Microsoft has shipped a great Cosmos DB Python SDK that provides almost all a developer could need to work with Cosmos DB. In one of my use cases I needed to batch insert multiple entities at the same time which is something the Cosmos DB SDK doesn’t support in any language. This meant I immediately looked at the Cosmos DB Bulk Executor library, only to find it only supports Java and .Net right now 🤨.
Luckily, having done a fair bit of Cosmos DB over the last few years I was aware this bulk insert pattern had been solved previously using Cosmos DB Stored Procedures so I weant and dug up the sample bulk import stored procedure from GitHub:
Well… not quite!
Thankfully I have a fairly good head of hair, because I tore a fair bit of it out getting it all to work.
The first challenge I hit was a general lack of complex “Calling Cosmos DB Stored Procedures from Python” samples. Yes, there are simple examples floating around, but *all* of them consist of calling a stored procedure with no parameters, or calling a stored procedure with a single parameter. While I was calling and passing only one parameter I was passing an array and not a single value.
No matter what I did all I could generate from Cosmos DB was this response (pasted here in case others search for a fix online):
Exception: HTTPFailure: Status code: 400 Sub-status: 400
Clear as mud … quelle horreur! I even found myself here:
Thankfully before I could post a question that would invariably be closed by some 30 million reputation-holding moderator and then down-voted into oblivion, I did a bit more digging and came across an answer to this question:
This answer in particular:
Thanks Aram…upvoted with a comment linking here 😊.
Which lead me to the solution shown below. The key element here is the line:
The ‘new_docs’ array is itself enclosed in an array!
Happy days! 😎
P.S. – You can learn about working with Cosmos DB completely for free on Microsoft Learn. (The added bonus is no Azure subscription or entry of credit card details is required to get going!)