Insert document on CosmosDB through Powershell - powershell

I am using Invoke-RestMethod to make a post request to create a new document in CosmosDB. So far I followed theses links: Invoking Rest API using PowerShell - CosmosDb
, Add a Document to CosmosDB via the REST API using PowerShell and the official documentation.
My script retrieves an object like this from external service:
{
"ObjectId": "bd33f6b5-a066-4f0f-8d1b-291a6a2b90ba",
"Date": "\/Date(1589379850000)\/",
"Data": "{\"CreationTime\":\"2019-06-13T13:21:55\",\"Id\":\"e985f142-9359-4ebf-a319-7fa30b6c9987\", \"Fields\":[{\"Name\":\"foo\",\"Value\":\"bar\"}]}"
}
My objective is to post the field Data into cosmos. To this I extract this field using: $payload | Select-Object -expand Data. (I have the above json as PowerShell object). Since this extracted object is a string, I passed it to Invoke-RestMethod:
Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $headers -Body $payload
But I keeping getting a Bad Request status. I've also tried the following:
Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $headers -Body ($payload | ConvertTo-Json -Depth 100)
Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $headers -Body ($payload | ConvertFrom-Json | ConvertTo-Json -Depth 100)
Note: I was able to deserialize this string in C# using newtonsoft (I made a function to receive the PowerShell request). I also was able to insert this document via Postman. Looks like the issue is in the body of the request, since using the PowerShell code generated by Postman worked for me.
Edit: I am passing the content type ("application/json") in header of the request. It also fails when pass it I directly to the Invoke-RestMethod
Can someone give a light? To me it should work fine.

Your payload is missing the required id attribute:
Remember that the REST API is for the Core SQL API operations. Your payload seems to be for a Mongo document?
Make sure you are also passing the partition key. Reference: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/PowerShellRestApi/PowerShellScripts/CreateItem.ps1

The data seems to be double converted, to extract it you can use this:
$json = '{"ObjectId": "bd33f6b5-a066-4f0f-8d1b-291a6a2b90ba", "Date": "\/Date(1589379850000)\/", "Data": "{\"CreationTime\":\"2019-06-13T13:21:55\",\"Id\":\"e985f142-9359-4ebf-a319-7fa30b6c9987\", \"Fields\":[{\"Name\":\"foo\",\"Value\":\"bar\"}]}"}'
$data = $json | ConvertFrom-Json | Select-Object -ExpandProperty "Data" | ConvertFrom-Json
$body = $data | ConvertTo-Json -Depth 10
So now $body is a proper JSON object which can be send by the Invoke-RestMethod:
Invoke-RestMethod -Method $verb -Uri $queryUri -Headers $headers -Body $payload -ContentType "application/json"

Related

Issue with for each loop with Invoke-RestMethod

I am currently having issues creating a powershell script that taks to an api with Invoke-RestMethod and a loop, I have spent all day trying to figure out where i am going wrong but i have not managed to come up with something.
Here is the code that i am trying to make
$url = "/api/Rest/v1"
$Body = #{
Username = ""
Password = ""
Privatekey = ""
}
$apikey = Invoke-RestMethod -Method 'Post' -Uri $url/Authenticate -Body $body
$headers = #{
'Authorization' = $apikey
}
$allusers = Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers | ft -HideTableHeaders Id
foreach ($userid in $allusers)
{
echo $userid
Invoke-RestMethod -Uri $url/Users/$userid -Method Get -Headers $headers
echo "test"
}
I am not having issues with the veriables $apikey and $allusers as they seem to output what i need but i think my issue is to do with the outbut being in format table but i have tried other methods for the for each and i have no clue where i am going wrong
So i have tested the Invoke-RestMethod commands on there own and they work as exspected but when i try the script above i get the following.
Invoke-RestMethod : {"Message":"User with specified id was not found."}
the output of $allusers displays something like the following for the user ID
dce502ed-e4b6-4b5e-a047-0bf3b34e98c6
dc1e60c1-99a7-479a-a7d6-0dc618c8dd5e
1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3
AKA the following work with no issues and outputs what i need
Invoke-RestMethod -Uri $url/Users/1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3 -Method Get -Headers $headers
I would really appreciate some kind of guidance on this.
The standard advice applies:
Format-* cmdlets (such as Format-Table, whose built-in alias is ft) emit output objects whose sole purpose is to provide formatting instructions to PowerShell's for-display output-formatting system.
In short: only ever use Format-* cmdlets to format data for display, never for subsequent programmatic processing - see this answer for more information.
Therefore, remove the | ft -HideTableHeaders Id pipeline segment and use member-access enumeration to extract all .Id property values as data.
$allusers = (Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers).Id

Correctly format JSON for Powershell Post? (Missing '=' operator after key in hash literal.)

I am attempting to use Powershell to perform some "POST" requests. However, I can't seem to get the JSON correctly formatted. How do I accomplish this?
>> $JSON=#{name:"TestName"}
>> Invoke-WebRequest -Uri http://localhost:7071/api/HttpTrigger1 -Method POST -Body $JSON
>> $response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" -Method Post -Body $JSON -ContentType "application/json"
ParserError:
Line |
1 | $JSON=#{name:"TestName"}
| ~
| Missing '=' operator after key in hash literal.
So, there are two ways you can do this:
The first, as suggested by Santiago, is
$json = '{name:"TestName"}'
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
-Method Post -Body $json -ContentType "application/json"
The second, using (roughly) the syntax you were using, is
#create a Powershell object (note the use of '=' instead of ':' for assignment)
#(such a simple example is not an improvement over the example above)
$json = #{ name = "TestName" } | ConvertTo-JSON
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
-Method Post -Body $json -ContentType "application/json"
The first method is certainly cleaner and more direct. The second is useful when the source data for the request comes as the result of manipulating Powershell objects, and you want to convert them for use in a web request.

Invoke-RestMethod to acces Joe SandBox API

I'm trying to create a powershell script to access JoeSandBox API to download reports.
I'm following their API details there https://www.joesandbox.com/userguide?sphinxurl=usage/webapi.html
Here's the beginning of the REST script I've put together:
$json = #{
apikey="XXXX";
webid= "YYYY"
} | ConvertTo-Json
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -Body $json -ContentType 'multipart/form-data'
Basically, I don't get the access...
Invoke-RestMethod : {"errors":[{"code":2,"message":"apikey is required."}]}
Thanks
$body = #{'apikey'='XXX'; 'webid'='YYY'}
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -body $body

Cant get a response from API Rest call with Powershell script

Im trying to send an API call to X and then the response will trigger some other things.
The issue i have is that im not getting any response in the ISE.
When im sending manually with fiddler/postman i get a response.
Im sending a simple post :
$Json = '{"Headers_In_Here"}}'
$Post = Invoke-WebRequest 'http://Server_URL' -Method Post -Body $Json -ContentType 'application/json'
Try adding ConvertTo-Json .
$Post = Invoke-WebRequest 'http://Server_URL' -Method Post -Body $Json -ContentType 'application/json' | ConvertTo-Json

Error 400 bad request when creating a group calendar event in powershell with Microsoft Graph API

I'm trying to create an event in a calendar in an Office 365 group via powershell.
This is my first experience to do this type of programming so sorry if my question will be very basic :-)
First, I created a simple json file (calendar.json)
{
"start":
{
"dateTime":"2017-03-12T17:00:00.0000000",
"timeZone":"UTC"
},
"end":
{
"dateTime":"2017-03-12T17:30:00.0000000",
"timeZone":"UTC"
},
"responseStatus": {
"response": "None"
},
"iCalUId": "null",
"isReminderOn": false,
"subject": "Test Event created from API"
}
Then I create the event with these steps:
Use a tested powershell function that give me the token
Add header with this code:
$headers = #{}
$headers.Add('Authorization','Bearer ' + $token.AccessToken)
$headers.Add('Content-Type',"application/json")
Because I'm starting now, I convert the json file in an object and then the object in json (I know, it's quite stupid, but I've done so beacuse I have no knowledge of json and how convert without error in powershell code)
$json = ConvertFrom-Json -InputObject (Gc 'C:\Users\mmangiante\OneDrive - Interactive Media S.p.A\Office 365\calendar.json'-Raw)
$body = ConvertTo-Json $json
Call the Invoke-RestMethod
response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups/768afb0c-bafd-4272-b855-6b317a3a9953/calendar/events' -Method Post -Headers $headers -Body $json
What is returned is a 400 bad request.
It's the same error of Sending Microsoft Graph request events returns 400
Given the answer given to that question I modified my code to return the error:
try{$restp=Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups/768afb0c-bafd-4272-b855-6b317a3a9953/calendar/events' -Method Post -Headers $headers -Body $json
} catch {$err=$_}
$err
like suggested in How do I get the body of a web request that returned 400 Bad Request from Invoke-RestMethod but I found nothing of interest.
The only thing that I found is that, at the time of writing, the Invoke-RestMethod doesn't return the full response as in this https://github.com/PowerShell/PowerShell/issues/2193
I suppose my json is not "well formed", but I don't know why.
Does anyone have a suggestion?
This formatting has worked for me in the past. Let me know if this resolves your issues:
$headers = #{
"Authorization" = ("Bearer {0}" -f $token);
"Content-Type" = "application/json";
}
$body = #{
Name1 = 'Value1';
Name2 = 'Value2';
}
$bodyJSON = $body | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri <API HERE> -Headers $headers -Body $bodyJSON -OutFile $output
Thanks Shawn,
I tried your suggestion but without luck; I have done other test with 2 other api and found discordant results.
The first test is to use the graph api related to contact, creating a contact as in https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/user_post_contacts
I created the powershell representation of the sample json:
$contactbody = #{
givenName = 'Ciccio';
surname = 'Patacca';
emailAddresses = #(
#{
address = 'cicciopatacca#cicciociccio.com'
name = 'Ciccio Patacca'
}
)
businessPhones = (
'+39 555 123 4567'
)
}
and then converted in json
$contactbody = $contactbody | ConvertTo-Json
I retrieved from Azure Portal the object ID related to my user in my company and so I call the rest method:
$response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/users/e37d2dbe-bdaf-4098-9bb0-03be8c653f7d/contact' -Method Post -Headers $headers -Body $contactbody
The final result is a 400 bad request error.
So, I tried another example and reused some code retrieved from a google search.
This time I copied the powershell json representation as in the sample and converted:
$body = #{"displayName"="ps-blog"; "mailEnabled"=$false; "groupTypes"=#("Unified"); "securityEnabled"=$false; "mailNickname"="ps1" } | ConvertTo-Json
and, as stated in https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/group_post_groups I called the rest method
$response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups' -Method Post -Headers $headers -Body $body
and this worked.
So I thought that the previously powershell representations of the sample with the error were not correctly formed (even if when I printed it they are equal to the samples on the graph api); for test, I rewritten the last powershell of the body as this:
$body = #{
displayName = 'TestGraphGroup';
mailEnabled = $true;
groupTypes = #('Unified')
securityEnabled = $false;
mailNickname = 'TestGraphGroup'
}
$body = $body | ConvertTo-Json
and invoked last method: it worked again.
So, where I'm doing wrong?
A new SDK was released that makes this easier.
Checkout instructions on how to use it here