How to call a restful web service in Faraday

Here is the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require 'faraday'
conn = Faraday.new(:url => 'https://SERVER_URL') do |c|
c.use Faraday::Request::UrlEncoded # encode request params as "www-form-urlencoded"
c.use Faraday::Response::Logger # log request & response to STDOUT
c.use Faraday::Adapter::NetHttp # perform requests with Net::HTTP
end
conn.basic_auth('USERNAME', 'PASSWORD')
# Get request
response = conn.get 'REST SERVICE PATH'
puts response.body.inspect
# Post request
response = conn.post 'REST SERVICE PATH', CONTENT do |req|
req.headers['Content-Type'] = '' # the default Content Type set by Faraday is NOT accepted by some web services, so you may need to reset it to blank
req.headers['charset'] = 'utf-8'
end
# Put request
resp = conn.put WEB_SERVICE_URL, CONTENT do |req|
req.headers['Content-Type'] = 'YOUR_MIME_TYPE'
# OR req.headers['Content-Type'] = ''
end
Share