Skip to content

Instantly share code, notes, and snippets.

@javiervidal
Forked from dob/scratch.rb
Created July 24, 2013 16:29
Show Gist options
  • Save javiervidal/6072167 to your computer and use it in GitHub Desktop.
Save javiervidal/6072167 to your computer and use it in GitHub Desktop.
# If you post to a Ruby on Rails REST API endpoint, then you'll get an
# InvalidAuthenticityToken exception unless you set a different
# content type in the request headers, since any post from a form must
# contain an authenticity token.
#
# This example shows you how to post to a rails endpoint.
require 'json'
def post_to_endpoint(endpoint)
uri = URI.parse(endpoint)
post_params = {
:title => "2BR Apartment For Rent in NYC",
:description => "Great midtown west location. I love this place.",
:price => "1500",
:api_key => "my_api_key"
}
# Convert the parameters into JSON and set the content type as application/json
req = Net::HTTP::Post.new(uri.path)
req.body = JSON.generate(post_params)
req["Content-Type"] = "application/json"
http = Net::HTTP.new(uri.host, uri.port)
response = http.start {|htt| htt.request(req)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment