Invoke-RestMethod

This topic contains 1 reply, has 2 voices, and was last updated by  Don Jones 2 months, 2 weeks ago.

  • Author
    Posts
  • #72331

    TommyQuality
    Participant

    Hi,

    I'm trying to get my head around the Invoke-Restmethod, but I'm getting lost so hoping someone can help me out.

    To start off I'm trying to post a new post to my WordPress site. I'll start off my using:

    $R = Invoke-Webrequest http://mywordpresssite.com/wp-login.

    This gets the login form for which i can then create an array to pass the creds into the login form:

    $R = Invoke-WebRequest http://mywordpresssite.com/wp-login.php
    $R.Forms[0].Fields.user_login = "username"
    $R.Forms[0].Fields.user_pass = 'password'
    $Session = Invoke-WebRequest -Method POST http://mywordpresssite.com/wp-login.php -Body $R
    

    So now i think i have logged in, but im not 100% sure?

    I now want to create the new post so i, so i think i do this.....

    $params = @{ 
        title = "test Rest API post" 
        content = "test Rest API post content" 
        status = 'publish' 
    }
    
    $params1=$params|ConvertTo-Json 
    Invoke-RestMethod -Method post -Uri http://mywordpresssite.com/wp-json/wp/v2/posts/ -ContentType "application/json" -Body $params1 -UseBasicParsing 
    

    But i get "message":"Sorry, you are not allowed to create posts as this user"

    So I'm a bit lost to how i pass the authenticated session into the restmethod. I've followed some examples and played around with the facebook example, but it's does tie up with this.

    Any help would be really appreciated.

    Cheers

    TommyQ

  • #72406

    Don Jones
    Keymaster

    The web server doesn't "remember" who you are; that's you job, based on the cookie that you got back from the login form. You have to pass that information along in each request.

    Now, I don't know much about WordPress' JSON API, but I suspect it isn't cookie-based – most REST APIs aren't. So you need to figure out how that API wants you to identify yourself. You're not doing anything wrong from a PowerShell perspective; you're just not doing whatever WordPress wants you to do. Sadly, this is probably not a great place to get WordPress API questions answered accurately ;).

You must be logged in to reply to this topic.