เชื่อมต่อ API ด้วย HTTP & URI แบบง่าย ๆ
Ruby by Keptcode.com
นำเข้า HTTP & URI
Path: [skeleton]\ruby\api.rb
Language: Ruby
require 'uri'
require 'net/http'
# API URL
@api_url = "https://api.keptcode.com/v1"
ตั้งค่า Header ให้กับ Request
Path: [skeleton]\ruby\api.rb
Language: Ruby
# Basic
headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' }
# Authentication
headers = { 'Authorization': 'Bearer D2X488D554H5EB989HI', 'Content-Type': 'application/json', 'Accept': 'application/json' }
ใช้งาน GET Method
Path: [skeleton]\ruby\api.rb
Language: Ruby
# URI: https://api.keptcode.com/v1/user/profile
uri = URI(@api_url + "/user/profile")
# Header Request
headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' }
# GET Request
req = Net::HTTP::Get.new(uri, headers)
# Response
res = Net::HTTP.start(uri.hostname, :use_ssl => true) do | http |
http.request(req)
end
# Output
puts res.body
ใช้งาน POST Method
Path: [skeleton]\ruby\api.rb
Language: Ruby
# URI: https://api.keptcode.com/v1/user/profile
uri = URI(@api_url + "/user/profile")
# Header Request
headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' }
# POST Request
req = Net::HTTP::Post.new(uri, headers)
# Body Request
request_body = {
name: "Keptcode",
}
req.body = request_body.to_json
# Response
res = Net::HTTP.start(uri.hostname, :use_ssl => true) do | http |
http.request(req)
end
# Output
puts res.body