I am new to Wordpress. I want to access WP-API to create a post using REST API. I am unable to perform POST, PUT and Delete request. Though I can retrieve data only. I wrote a ruby script for this. Below is my code snippet.
require 'net/http'
require 'net/http/oauth'
require 'json'
class CollectScript
def initialize
uri = URI.parse('http://vagrant.local/wp-json/wp/v2/posts')
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.request_uri)
req.basic_auth("admin", "password")
res = http.request(req)
puts res.body
end
end
CollectScript.new
While running the above code I am getting following error:
{"status":"error","error":"You need to login with a user capable of creating posts."}
Using the same code with GET
request I am able to get the posts JSON. But for HTTP POST
request I need to pass authentication. I tried with basic authentication and Oauth too. But same result.
Please can anyone help me to figure out the issue with authentication.
I simply install this basic_auth plugin in my Wordpress site.
Now I use the following code snippet for authentication
uri = URI.parse("http://vagrant.local/wp-json/wp/v2/posts")
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.request_uri)
req.basic_auth("admin", "password")
req.set_form_data({title: "Another 11new post", status: "publish", content_raw: "this is the content of the post", excerpt_raw: "Excerpt", post_media: ['/uploads/rails.png']})
res = http.request(req)
puts res.body
Now It successfully works.