Skip to content

Instantly share code, notes, and snippets.

@harssh
Created March 25, 2023 01:31
Show Gist options
  • Save harssh/6fa9687c07ca33cf5c906b28217d8a82 to your computer and use it in GitHub Desktop.
Save harssh/6fa9687c07ca33cf5c906b28217d8a82 to your computer and use it in GitHub Desktop.
Send POST request in RUBY
Post some JSON
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("http://localhost:3000/users")
header = {'Content-Type': 'text/json'}
user = {user: {
name: 'Bob',
email: '[email protected]'
}
}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json
# Send the request
response = http.request(request)
This will simply submit a POST request with the JSON as the body.
But, there were some methods that required a file be submitted with the JSON? Things get a little more complicated when you do this, but it is still manageable.
Post a file with some JSON
require 'net/http'
require 'uri'
require 'json'
require 'mime/types'
uri = URI.parse("http://localhost:3000/users")
BOUNDARY = "AaB03x"
header = {"Content-Type": "multipart/form-data, boundary=#{BOUNDARY}"}
user = {user: {
name: 'Bob',
email: '[email protected]'
}
}
file = "test_file.xml"
# We're going to compile all the parts of the body into an array, then join them into one single string
# This method reads the given file into memory all at once, thus it might not work well for large files
post_body = []
# Add the file Data
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"user[][image]\"; filename=\"#{File.bsename(file)}\"\r\n"
post_body << "Content-Type: #{MIME::Types.type_for(file)}\r\n\r\n"
post_body << File.read(file)
# Add the JSON
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"user[]\"\r\n\r\n"
post_body << user.to_json
post_body << "\r\n\r\n--#{BOUNDARY}--\r\n"
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = post_body.join
# Send the request
response = http.request(request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment