2 / 5
Dec 2024

Hi all,

I am trying to interact REST API of Atlas in Powershell by invoke-RestMethod
API with Get method is fine for me

$ApiPublicKey = "" $ApiPrivateKey = "" $Uri = "https://cloud.mongodb.com/api/atlas/v2/clusters" $headers = @{} $headers.Add("Accept", "application/vnd.atlas.2023-01-01+json") [securestring]$secStringPassword = ConvertTo-SecureString $ApiPrivateKey -AsPlainText -Force [pscredential]$credential = New-Object System.Management.Automation.PSCredential ($ApiPublicKey, $secStringPassword) $results = Invoke-RestMethod -Uri $Uri -Headers $headers -Credential $credential -Method Get $results.results

But when I tried “post”, e.g. MongoDB Atlas Administration API

$ApiPublicKey = "" $ApiPrivateKey = "" [securestring]$secStringPassword = ConvertTo-SecureString $ApiPrivateKey -AsPlainText -Force [pscredential]$credential = New-Object System.Management.Automation.PSCredential ($ApiPublicKey, $secStringPassword) $SourceProjectId = "" $SourceClusterName = "" # create download restore job # uri $download_uri = "https://cloud.mongodb.com/api/atlas/v2/groups/$SourceProjectId/clusters/$SourceClusterName/backup/restoreJobs" # headers $download_headers = @{} $download_headers.Add("Accept", "application/vnd.atlas.2023-01-01+json") # body $download_body = @{} $download_body.Add("deliveryType", "download") $download_body.Add("snapshotId", "xxxxx") $download_result = Invoke-RestMethod -Uri $download_uri -Headers $download_headers -Credential $credential -body $download_body -Method post

I am getting this error

Invoke-RestMethod: { "error": 415, "reason": "Unsupported Media Type" }

I suspected this is the problem at body parameter, can anyone share the workable syntax or exmpale of “post” method of invoke-RestMethod ?

Thanks @chris

This is one of the root causes.
Another issue is that i should convert body into json before passing into Invoke-RestMethod.

It is working now. :sweat_smile:

Hi Chris,

Here we go:

$ApiPublicKey = "<public-key>" $ApiPrivateKey = "<private-key>" $SourceProjectId = "<project-id>" # The project ID of the source cluster $SourceClusterName = "<cluster-name>" # The name of the source cluster [securestring]$secStringPassword = ConvertTo-SecureString $ApiPrivateKey -AsPlainText -Force [pscredential]$credential = New-Object System.Management.Automation.PSCredential ($ApiPublicKey, $secStringPassword) # create download restore job # uri $download_uri = "https://cloud.mongodb.com/api/atlas/v2/groups/$SourceProjectId/clusters/$SourceClusterName/backup/restoreJobs" # headers $download_headers = @{ "Accept" = "application/vnd.atlas.2023-01-01+json" "Content-Type" = "application/vnd.atlas.2023-01-01+json" } # body $download_body = @{ deliveryType = "download" snapshotId = "<snapshot-id>" } | ConvertTo-Json -Depth 10 $download_result = Invoke-RestMethod -Uri $download_uri -Headers $download_headers -Credential $credential -body $download_body -Method post

Hope it is clear. :sweat_smile: