I tried using Faraday middleware, so I will summarize it easily.
HTTP client library written in ruby You can use this to access external APIs from your Rails project.
Faraday has middleware that allows you to customize request and response processing. There are two types, Request middleware and Response middleware. By using this, you can add authentication information at the time of request and write out the communication in the log.
You can use it as follows using symbols.
api_client.rb
Faraday.new(url: 'https://test.com') do |builder|
#Use middleware
builder.request :url_encoded
builder.response :logger, Config.logger if Config.enable_logger
end
Request middleware can set the details of the request before sending the request. Here, we will introduce two middleware. Authentication middleware can set the Authorization header, UrlEncoded middleware can convert the hash of key / value pairs into a URL-encoded request body.
Example of use
api_client.rb
#Authentication middleware
builder.request :basic_auth, "username", "password"
builder.request : authorization :Basic, "aut_key"
#UrlEncoded middleware
builder.request :url_encoded
The response middleware can set the details of the response when it receives the response. Here, we will introduce Logger middleware. Logger middleware allows you to log request and response body and headers. It also has a filter function that allows you to filter sensitive information using regular expressions.
Example of use
api_client.rb
#Logger middleware
builder.response :logger
#filter
builder.response :logger do | logger |
logger.filter(/(password=)(\w+)/, '\1[REMOVED]')
end
If you add a gem called faraday_middleware, you can use more middleware.
For example, you can use the ParseJson class and specify parser_options and content_type to parse the hash key as a symbol for JSON.
Example of use
api_client.rb
builder.response :json, parser_options: { symbolize_names: true }, content_type: 'application/json'
https://lostisland.github.io/faraday/ https://lostisland.github.io/faraday/middleware/list
Recommended Posts