lilixiaocc
lilixiaocc

Reputation: 343

Net/HTTP in rails with request header and body

I am trying to call external API for my project and I have some troubles while using Net::HTTP in my rails lib . Here is my code

class ApiCall
 def self.do_api_request(api_token, body)
    require 'net/http'
    require 'uri'
    uri = URI.parse('https://sample.com')
    header = {'Token' => api_token, 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
    request = Net::HTTP::Post.new(uri.request_uri, header)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = (uri.scheme == "https")
    request.body = body
    http.request(request)
 end
end

This is how I use it (assume I knew the api_token and body):

body = {'id' => 2, 'age'=> 23};

ApiCall.do_api_request(api_token, body) 

This way, it throws an error back:

NoMethodError: undefined method `bytesize' for Hash

Then after check online, seems like the body is hash instead of string, so I did this body = URI.encode_www_form(body) and after rerun, it gives me :

400 bad request

I have no ideas how to put both header and body into a rails Net::HTTP method

Solution:

I know where the problem is. request body supposed to be string so body = "{'id' : 2, 'age' : 23}" , I used body.to_json

Upvotes: 3

Views: 2549

Answers (1)

Pradeep Agrawal
Pradeep Agrawal

Reputation: 346

I will suggest you to use HTTParty for calling an api. This is real simple to use. Following are the examples-

HTTParty.get("https://api.bigcommerce.com/stores/"[email protected]_hash+"/v3/catalog/categories", :headers => @your_header_data)

This will return the response. Also for post request,

HTTParty.post("https://api.bigcommerce.com/stores/"[email protected]_hash+"/v3/catalog/products", :headers => @auth, :body => product_json)

So you can pass body to in body param here.

Upvotes: 1

Related Questions