1

I am learning Ruby programming and I am building an API testing project. I have a request to a specific site and I am using Faraday gem. Here my code:

conn = Faraday.new
f_response = conn.post do |req|
  req.url 'https://api.abcxyz.vn/v2/tokens'
  req.headers['Content-Type'] = 'application/json'
  req.body = '{"email": "xxx@gmail.com","password": "abc123","grant_type": "password"}'
end

The request is OK and I got the successfull code 201 as I expected. But I do not understand the format of req.headers['Content-Type'] = 'application/json'. Is it a hash or array. Because if I replace my code as following:

request_headers = {"Content-Type" => "application/json"}
conn = Faraday.new
f_response = conn.post do |req|
  req.url 'https://api.abcxyz.vn/v2/tokens'
  req.headers = request_headers
  req.body = '{"email": "xxx@gmail.com","password": "abc123","grant_type": "password"}'
end

The result 404 error code. Woud you please help me out with this case. Pluse I have another API which requires the 'X-Access-Token' attched in the header fields. How can I input it into the payload.

1 Answers1

0

req.headers is a Hash, but by using req.headers = you are wiping out any headers that Faraday has set automatically such as 'User-Agent'. To add new headers, do the same that you've done for 'Content-Type':

conn = Faraday.new
f_response = conn.post do |req|
  req.url 'https://api.abcxyz.vn/v2/tokens'
  req.headers['Content-Type'] = 'application/json'
  req.headers['X-Access-Token'] = 'x-access-token-goes-here'
  req.body = '{"email": "xxx@gmail.com","password": "abc123","grant_type": "password"}'
end
infused
  • 24,000
  • 13
  • 68
  • 78