Webapi and post resquest

Welcome Forums General PowerShell Q&A Webapi and post resquest

This topic contains 3 replies, has 4 voices, and was last updated by

 
Participant
3 months, 3 weeks ago.

  • Author
    Posts
  • #104822

    Participant
    Points: 0
    Rank: Member

    Hello,
    I have a query that works with Postman
    Postman body
    {
    "ObjectDN": "toto",
    "AttributeName": "Disabled",
    "Values": ["1"]
    }

    I try in powershell
    [code]
    Powershell extract
    $fullID = "toto"
    function retire($fullID){
    $json = @{ObjectDN=$fullID;AttributeName="Disabled";Values="1"}|ConvertTo-Json
    $uri = $baseurl + '/Config/Write?apikey=' + $global:key
    $statut = Invoke-RestMethod -Uri $uri -Body $json -Method POST -ContentType 'application/json'
    if($statut.Result -eq $null){
    return "error"
    }else{
    return $statut.Result
    }
    [/code]
    When I run it I have an error
    « Invoke-RestMethod : {"Error":"Unable to parse input document."} »

    I think the problem is the conversion of the line
    "Values": ["1"]
    that works in Postman
    but in powershell we can not use []
    I'm looking for a solution
    Bests regards

  • #104830

    Participant
    Points: 158
    Helping Hand
    Rank: Participant

    Try generating your JSON like so:

    $body = New-Object -TypeName PSObject -Property @{
        "ObjectDN" = "toto"
        "AttributeName" =  "Disabled"
        "Values" = @("1")
    }
    
    $jsonBody = $body | ConvertTo-Json
    
    $jsonBody
    

    Output:

    {
        "AttributeName":  "Disabled",
        "Values":  [
                       "1"
                   ],
        "ObjectDN":  "toto"
    }
    
  • #104881

    Participant
    Points: 48
    Rank: Member

    To point out a personal experience with one specific API that didn't seem to like any carriage returns in the JSON body, I had to also use the -compress parameter of ConvertTo-JSON and also wrap the value with single quotes.

    $JSON=@{Name=Value} | ConvertTo-JSON -compress
    $Body='$($JSON)'
    Invoke-RESTMethod -body $Body #missing URI/Header/Method of course
    
  • #104944

    Participant
    Points: 0
    Rank: Member

    Hello
    Thank you for yours answer I would test on my return from holidays
    Yann

The topic ‘Webapi and post resquest’ is closed to new replies.