Request contains an invalid argument. while using Safe Browsing Api with Rails 7

143 Views Asked by At

I want to build this simple project where users can check url safety

using Safe Browsing API but It doesn't work correctly even though

I've tried multiple ways but no success.

This's my controller method below.

def check_url
    if params[:link].present?
      api_key = ENV[""]
      # Set up the request parameters
      url = params[:link]
      
      formatted_url = canonicalize_url(url)
    
      threat_types = ["MALWARE", "THREAT_TYPE_UNSPECIFIED", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"]
      platform_types = ["ANY_PLATFORM"]
      body = {
        client: {
          clientId: api_key,
          clientVersion: "1.0.0",
        },
        threatInfo: {
          threatTypes: threat_types,
          platformTypes: platform_types,
          threatEntryTypes: %w[URL THREAT_ENTRY_TYPE_UNSPECIFIED EXECUTABLE],
          threatEntries: [
            { url: formatted_url },
          ],
        },
      }

      # Set up the request headers
      headers = {
        "Content-Type" => "application/json",
        "Authorization" => "Bearer #{"api_key"}",
      }

      # Make the request to the Safe Browsing API
      response = HTTP.post(
        "https://safebrowsing.googleapis.com/v4/threatMatches:find",
        json: body,
        headers: headers,
      )

      # Check the response
      if response.code == 200
        data = JSON.parse(response.body)
        puts JSON.pretty_generate(data)
        if data["matches"].empty?
          # render plain: "The URL is safe"å

          puts "The URL is safe"
          @url_is_safe = true
        else
          # render plain: "The URL is not safe"
          puts "The URL is not safe"
        end
      else
        # render plain: "An error occurred"
        puts "An error occurred"
      end
    else
      puts "link variable is empty"
    end
    puts "Response code: #{response.code}"
    puts "Response body: #{response.body}"

    puts "Request parameters: #{body}"
    puts "Request headers: #{headers}"
  end

I added a method to format :link variable, which is url in this case,

called canonicalize_url(url)

And this is the error shown in the logs

Print out responses as you can see in the code, so I can understand the errors.

enter image description here

Please let me know if you had any questions or requests, Thanks!

0

There are 0 best solutions below