Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

IPGeolocation Ruby SDK

Official Ruby SDK for the IPGeolocation.io IP Location API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, timezone, network, hostname, abuse, user-agent, and security data from one API.

  • Ruby 2.7+
  • Sync client built on Net::HTTP
  • Typed responses plus raw JSON and XML methods

Table of Contents

Install

gem install ipgeolocation_sdk

Or add it to your Gemfile:

gem"ipgeolocation_sdk","~> 2.0"

Then run:

bundle install
require"ipgeolocation_sdk"

RubyGems package: ipgeolocation_sdk
Package page: https://rubygems.org/gems/ipgeolocation_sdk
GitHub repository: https://github.com/IPGeolocation/ip-geolocation-ruby-sdk

Quick Start

require"ipgeolocation_sdk"client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))beginresponse=client.lookup_ip_geolocation(ip: "8.8.8.8")putsresponse.data.ip# 8.8.8.8putsresponse.data.location&.country_name# United Statesputsresponse.data.location&.cityputsresponse.data.time_zone&.nameputsresponse.metadata.credits_chargedensureclient.closeend

You can also pass LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest objects if you want validation before the request is sent.

At a Glance

ItemValue
Gemipgeolocation_sdk
ModuleIpgeolocationSdk
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, timezone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportNet::HTTP

Get Your API Key

To use most SDK features, create or access your IPGeolocation account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.

Authentication

API Key

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Request-Origin Auth

client=IpgeolocationSdk::IpGeolocationClient.new(request_origin: "https://app.example.com")

request_origin must be an absolute http or https origin with no path, query string, fragment, or userinfo.

Important

Request-origin auth does not work with /v3/ipgeo-bulk. Bulk lookup always requires api_key.

Note

If you set both api_key and request_origin, single lookup still uses the API key. The API key is sent as the apiKey query parameter, so avoid logging full request URLs.

Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need include for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.

Client Configuration

FieldTypeDefaultNotes
api_keyStringunsetRequired for bulk lookup. Optional for single lookup if request_origin is set.
request_originStringunsetMust be an absolute http or https origin.
base_urlStringhttps://api.ipgeolocation.ioOverride the API base URL.
connect_timeoutNumeric10.0Time to open the connection, in seconds.
read_timeoutNumeric30.0Time to wait while reading the response body, in seconds.

The client constructor accepts either an IpGeolocationClientConfig or a hash with the same keys.

Available Methods

MethodReturnsNotes
lookup_ip_geolocation(request = nil)ApiResponse with typed dataSingle lookup. Typed JSON response.
lookup_ip_geolocation_raw(request = nil)ApiResponse with StringdataSingle lookup. Raw JSON or XML string.
bulk_lookup_ip_geolocation(request)ApiResponse with bulk result arrayBulk lookup. Typed JSON response.
bulk_lookup_ip_geolocation_raw(request)ApiResponse with StringdataBulk lookup. Raw JSON or XML string.
closenilCloses the client. Do not reuse the client after this.

Note

Typed methods support JSON only. Use the raw methods when you need XML output.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupArray of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt.
includeSingle and bulkArray of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkArray of field paths to keep, for example ["location.country_name", "security.threat_score"].
excludesSingle and bulkArray of field paths to remove from the response.
user_agentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers. Use a hash where each value is a string or an array of strings.
outputSingle and bulk"json" or "xml". Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

client=IpgeolocationSdk::IpGeolocationClient.new(api_key: ENV.fetch("IPGEO_API_KEY"))

Caller IP

Omit ip to look up the public IP of the machine making the request.

response=client.lookup_ip_geolocationputsresponse.data.ip

Domain Lookup

Domain lookup is a paid-plan feature.

response=client.lookup_ip_geolocation(ip: "ipgeolocation.io")putsresponse.data.ipputsresponse.data.domain# ipgeolocation.ioputsresponse.data.location&.country_name

Security and Abuse

response=client.lookup_ip_geolocation(ip: "9.9.9.9",include: ["security","abuse"])putsresponse.data.security&.threat_scoreputsresponse.data.abuse&.emails&.first

User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

visitor_ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"response=client.lookup_ip_geolocation(ip: "115.240.90.163",include: ["user_agent"],headers: {"User-Agent"=>visitor_ua})putsresponse.data.user_agent&.nameputsresponse.data.user_agent&.operating_system&.name

Note

The user_agent request field overrides the SDK's default outbound User-Agent header. It takes precedence over headers["User-Agent"].

Filtered Response

response=client.lookup_ip_geolocation(ip: "8.8.8.8",include: ["security"],fields: ["location.country_name","security.threat_score","security.is_vpn"],excludes: ["currency"])putsresponse.data.location&.country_nameputsresponse.data.security&.threat_scoreputsresponse.data.security&.is_vpn

Raw XML

response=client.lookup_ip_geolocation_raw(ip: "8.8.8.8",output: IpgeolocationSdk::ResponseFormat::XML)putsresponse.data

Bulk Lookup

Bulk lookup is a paid-plan feature and always requires api_key.

Each bulk result is either a success or an error.

response=client.bulk_lookup_ip_geolocation(ips: ["8.8.8.8","invalid-ip","1.1.1.1"],include: ["security"])response.data.eachdo |result|
ifresult.success?putsresult.data.ipputsresult.data.security&.threat_scorenextendputsresult.error.messageend

Response Metadata

Each method returns an ApiResponse with data and metadata.

metadata includes:

FieldMeaning
credits_chargedCredits charged for the request when the API returns that header
successful_recordsNumber of successful bulk records when the API returns that header
status_codeHTTP status code
duration_msClient-side request time in milliseconds
raw_headersResponse headers as Hash<String, Array<String>>

Helper methods:

metadata=response.metadataputsmetadata.status_codeputsmetadata.duration_msputsmetadata.header_values("X-Credits-Charged").inspectputsmetadata.first_header_value("Content-Type")

JSON Helpers

Use these helpers to turn SDK objects into JSON:

putsIpgeolocationSdk.to_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data)putsIpgeolocationSdk.to_pretty_json(response.data,:full)

Compact mode omits nil fields. Full mode keeps them.

Errors

The SDK raises these exception classes:

  • IpgeolocationSdk::ValidationError
  • IpgeolocationSdk::SerializationError
  • IpgeolocationSdk::TransportError
  • IpgeolocationSdk::RequestTimeoutError
  • IpgeolocationSdk::ApiError
  • IpgeolocationSdk::BadRequestError
  • IpgeolocationSdk::UnauthorizedError
  • IpgeolocationSdk::NotFoundError
  • IpgeolocationSdk::MethodNotAllowedError
  • IpgeolocationSdk::PayloadTooLargeError
  • IpgeolocationSdk::UnsupportedMediaTypeError
  • IpgeolocationSdk::LockedError
  • IpgeolocationSdk::RateLimitError
  • IpgeolocationSdk::ClientClosedRequestError
  • IpgeolocationSdk::ServerError

Example:

beginclient.lookup_ip_geolocation(ip: "8.8.8.8")rescueIpgeolocationSdk::ApiError=>errorputserror.status_codeputserror.api_messageputserror.messageend

Troubleshooting

  • bulk lookup requires api_key in client config Bulk lookup does not support request-origin auth on its own.
  • single lookup requires api_key or request_origin in client config Set at least one authentication option before calling the single lookup methods.
  • XML output is not supported by typed methods Use lookup_ip_geolocation_raw or bulk_lookup_ip_geolocation_raw for XML output.
  • client is closed Create a new client after calling close.
  • TransportError or RequestTimeoutError Increase connect_timeout or read_timeout, or add your own retry logic.

Frequently Asked Questions

Can I pass a plain hash instead of a request object? Yes. All client methods accept either the typed request object or a plain hash with the same keys.
How do I look up my own public IP? Call lookup_ip_geolocation with no ip value.
How do I get XML? Use the raw methods with output: IpgeolocationSdk::ResponseFormat::XML.
How do I read bulk errors? Check result.success?. Success items use result.data. Error items use result.error.message.

Links

About

Official Ruby SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON/XML support.

Topics

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages