make a http request with a custom body as multipart form data in ruby

To make a HTTP request in Ruby with a custom body and Content-Type set to multipart form data, we can use the http-request library.

Here's an example code snippet that shows how to make a POST request with a multipart form data body:

main.rb
require 'http/request'

file_name = 'example.txt'
file_content = File.read('/path/to/example.txt')

request = HTTP::Request.new(
  :post,
  'https://example.com/api/upload',
  [
    ['Content-Type', 'multipart/form-data']
  ],
  {
    :file => UploadIO.new(StringIO.new(file_content), 'text/plain', file_name),
    :name => 'Example Name'
  }
)

response = request.perform()

puts response.status
puts response.headers
puts response.body.to_s
443 chars
23 lines

In this example, we are creating a HTTP::Request object with the POST method, URL, headers, and body (as a hash of key-value pairs, where the keys are the field names and the values are UploadIO objects that encapsulate the file contents). Then we call perform() on the request object to actually make the HTTP request, and inspect the response object to see the status, headers, and body.

gistlibby LogSnag