Skip to content

Instantly share code, notes, and snippets.

@rafaelfelix
Created November 19, 2015 21:12
Show Gist options
  • Save rafaelfelix/bafb0436dfda8e64d8b0 to your computer and use it in GitHub Desktop.
Save rafaelfelix/bafb0436dfda8e64d8b0 to your computer and use it in GitHub Desktop.
Cloudflare API v4 client class in Ruby (NOT YET FINISHED)
class CloudflareClient
CLOUDFLARE_API_ENDPOINT = "https://api.cloudflare.com/client/v4"
def initialize(email, api_key)
require "rest-client"
require "json"
raise ArgumentError, "Parameters email and api_key are mandatory" if email.to_s.empty? or api_key.to_s.empty?
@auth_headers = {"X-Auth-Email" => email, "X-Auth-Key" => api_key, "Content-Type" => "application/json"}
end
def get_zone_by_name(zone_name)
send_req "#{CLOUDFLARE_API_ENDPOINT}/zones?name=#{zone_name}"
end
def get_dns_record(zone_id, record_name, record_type = nil)
url = "#{CLOUDFLARE_API_ENDPOINT}/zones/#{zone_id}/dns_records?name=#{record_name}"
url += "&type=#{record_type}" if not record_type.to_s.empty?
send_req url
end
def post_dns_record(zone_id, record_name, record_type, record_content, zone_name, proxied = false)
post_data = {'name' => record_name, 'type' => record_type, 'zone_name' => zone_name, 'content' => record_content, 'proxied' => proxied}
send_req "#{CLOUDFLARE_API_ENDPOINT}/zones/#{zone_id}/dns_records", "post", post_data.to_json
end
def put_dns_record(zone_id, record_id, record_name, record_type, record_content, zone_name, proxied = false)
put_data = {'id' => record_id, 'name' => record_name, 'type' => record_type, 'zone_name' => zone_name, 'content' => record_content, 'proxied' => proxied}
send_req "#{CLOUDFLARE_API_ENDPOINT}/zones/#{zone_id}/dns_records/#{record_id}", "put", put_data.to_json
end
private
# wrapper to dispatch http requests and handle errors
def send_req (url, http_verb = "get", payload = nil)
begin
call = "RestClient.#{http_verb} '#{url}'"
call += ", '#{payload}'" if not payload.to_s.empty?
call += ", @auth_headers"
response = eval call
rescue => e
response_body = JSON.parse(e.response.body)
end
# check for errors
if not response_body.to_s.empty? and not response_body["success"]
message = "Cloudflare API Error: #{response_body['errors']} for #{http_verb} request"
messsage += " - data: #{payload}" if not payload.to_s.empty?
raise message
end
JSON.parse(response)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment