Invoking Rest API using Powershell – CosmosDb

Question:

I was trying to deploy cosmos database using Cosmos DB REST Api. I’m using a function to build the authorisation header and I got the script from https://gallery.technet.microsoft.com/scriptcenter/How-to-query-Azure-Cosmos-0a9aa517 link. It works perfectly fine for GET & POST however when I tried to execute a PUT command I’m always getting below error.

Invoke-RestMethod : The remote server returned an error: (401)
Unauthorized.

Im trying to update the offer for Cosmos collection but it always ends with the error and I couldn’t understand whats the reason. I also checked my headers and authorisation with Microsoft documentation and looks fine to me. Refer https://learn.microsoft.com/en-us/rest/api/documentdb/replace-an-offer for Uri and headers required. My request and response are below

Request

Response

My Powershell Code

Can someone throw me some help as why my PUT requests are failed with authorisation error, what I’m missing and how can I correct it.

Answer:

Response message clearly states used payload for verification. Tracing ‘$payLoad’ in Generate-MasterKeyAuthorizationSignature will quickly revel the issue.

You need to address at-least below two issues for this to work

  • RepalceOffer documentation states RID of the offer, instead you are
    passing the collection name.
  • ResourceLin hardcoded: $ResourceLink
    = “offers” in Modify-Offer where as it needs to point to the RID of the resource.

Here is slightly modified code which should do job

Other alternative recommended approach if possible is to consume client SDK in Powershell. Here is a sample code which updates first offer of the account.

Source:

Invoking Rest API using Powershell – CosmosDb by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply