This time, I will give a sample using the most basic net / http, but there are multiple HTTP clients in Ruby.
About request parameters In the case of GET, the parameter is included in the query string, In the case of POST, I was a little addicted to including it in the request body.
I will rewrite it later.
require 'uri'
require 'net/http'
require 'openssl'
require 'base64'
## 1.Obtaining an access token by Oauth authentication
# client_id and client_Use secret
client_id = ENV['API_CLIENT_ID']
client_secret = ENV['API_CLIENT_SECRET']
credential = Base64.strict_encode64(client_id + ':' + client_secret)
uri = URI.parse('https://example.oauth2/token')
#Create an HTTP request to get an access token
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
#The following depends on the specifications of the Web API used.
request_header = {
'Authorization': "Basic #{credential}",
'Content-Type': 'application/x-www-form-urlencoded'
}
request = Net::HTTP::Post.new(uri.request_uri, request_header)
request.body = 'grant_type=client_credentials'
#Get access token from request transmission / response
response = https.request(request)
response_body = JSON.parse(response.body)
access_token = response_body['access_token']
## 2.Send HTTP request to Web API
#Creating an HTTP request using an access token
endpoint_uri = URI.parse('https://example.api.com' + '/v1/hoge/huga')
https = Net::HTTP.new(endpoint_uri.host, endpoint_uri.port)
https.use_ssl = true
#The following depends on the specifications of the Web API used.
request_header = {
'Authorization': "Bearer #{access_token}",
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
request = Net::HTTP::Post.new(endpoint_uri.request_uri, request_header)
data = { api_key: "abcd1234", name: "test", email: "[email protected]" }
request.body = URI.encode_www_form(data)
#Send request / get response
response = https.request(request)
-Ruby 2.7.0 Reference Manual library net / http -The most understandable explanation of OAuth --Throw a POST request to the Web API on net / https -Do you want to put that request parameter in the query string or in the body?
If you have any Web API specifications or sample code to use, read them as well.
faraday
oauth2
Recommended Posts