Skip to content

Commit 7ee631c

Browse files
committed
SDK for IP-Geolocation and Timezone information is completed
1 parent 2325965 commit 7ee631c

File tree

3 files changed

+313
-0
lines changed

3 files changed

+313
-0
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Files
2+
Test.py
3+
4+
# Directories
5+
__pycache__

IPGeolocation.py

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
import requests
2+
import json
3+
4+
from requests import RequestException
5+
6+
class GeolocationParams:
7+
def __init__(self):
8+
self.__ipAddress = ""
9+
self.__fields = ""
10+
self.__excludes = ""
11+
self.__lang = "en"
12+
self.__ipAddresses = []
13+
14+
def setIPAddress(self, ipAddress: str):
15+
self.__ipAddress = ipAddress
16+
17+
def getIPAddress(self) -> str:
18+
return self.__ipAddress
19+
20+
def setFields(self, fields: str):
21+
self.__fields = fields
22+
23+
def getFields(self) -> str:
24+
return self.__fields
25+
26+
def setExcludes(self, excludes: str):
27+
self.__excludes = excludes
28+
29+
def getExcludes(self) -> str:
30+
return self.__excludes
31+
32+
def setLang(self, lang: str = "en"):
33+
self.__lang = lang
34+
35+
def getLang(self) -> str:
36+
return self.__lang
37+
38+
def setIPAddresses(self, ipAddresses: [] = []):
39+
if len(ipAddresses) > 50:
40+
ValueError("Maximum number of IP addresses for bulk lookup cannot be more than 50.")
41+
else:
42+
self.__ipAddresses = ipAddresses
43+
44+
def getIPAddresses(self) -> []:
45+
return self.__ipAddresses
46+
47+
def getURLParams(self) -> dict:
48+
urlParams = {}
49+
50+
if self.__ipAddress:
51+
urlParams["ip"] = self.__ipAddress
52+
53+
if self.__fields:
54+
urlParams["fields"] = self.__fields
55+
56+
if self.__excludes:
57+
urlParams["excludes"] = self.__excludes
58+
59+
if self.__lang:
60+
urlParams["lang"] = self.__lang
61+
62+
return urlParams
63+
64+
class TimezoneParams:
65+
def __init__(self):
66+
self.__ipAddress = ""
67+
self.__timezone = ""
68+
self.__latitude = 0.0
69+
self.__longitude = 0.0
70+
self.__lang = "en"
71+
72+
def setIPAddress(self, ipAddress: str):
73+
self.__ipAddress = ipAddress
74+
75+
def getIPAddress(self) -> str:
76+
return self.__ipAddress
77+
78+
def setTimezone(self, timezone: str):
79+
self.__timezone = timezone
80+
81+
def getTimezone(self) -> str:
82+
return self.__timezone
83+
84+
def setCoordinates(self, latitude: float, longitude: float):
85+
self.__latitude = latitude
86+
self.__longitude = longitude
87+
88+
def getLatitude(self) -> float:
89+
return self.__latitude
90+
91+
def getLongitude(self) -> float:
92+
return self.__longitude
93+
94+
def setLang(self, lang: str = "en"):
95+
self.__lang = lang
96+
97+
def getLang(self) -> str:
98+
return self.__lang
99+
100+
def getURLParams(self) -> dict:
101+
urlParams = {}
102+
103+
if self.__ipAddress:
104+
urlParams["ip"] = self.__ipAddress
105+
106+
if self.__latitude and self.__longitude:
107+
urlParams["lat"] = self.__latitude
108+
urlParams["long"] = self.__longitude
109+
110+
if self.__timezone:
111+
urlParams["tz"] = self.__timezone
112+
113+
if self.__lang:
114+
urlParams["lang"] = self.__lang
115+
116+
return urlParams
117+
118+
class IPGeolocationAPI:
119+
def __init__(self, apiKey):
120+
if not apiKey:
121+
raise ValueError("API key is not provided.")
122+
else:
123+
self.__urlParams = {"apiKey": apiKey}
124+
125+
def getApiKey(self):
126+
return self.__apiKey
127+
128+
def getGeolocation(self, geolocationParams: GeolocationParams = None):
129+
if geolocationParams != None:
130+
if len(geolocationParams.getIPAddresses()) > 0:
131+
requestData = json.dumps({"ips": geolocationParams.getIPAddresses()})
132+
return self.__post("ipgeo-bulk", requestData, {**self.__urlParams, **geolocationParams.getURLParams()})
133+
else:
134+
return self.__get("ipgeo", {**self.__urlParams, **geolocationParams.getURLParams()})
135+
else:
136+
return self.__get("ipgeo", self.__urlParams)
137+
138+
def getTimezone(self, timezoneParams: TimezoneParams = None):
139+
if timezoneParams:
140+
return self.__get("timezone", {**self.__urlParams, **timezoneParams.getURLParams()})
141+
else:
142+
return self.__get("timezone", self.__urlParams)
143+
144+
def __get(self, path: str, urlParams: dict = {}) -> dict:
145+
url = "https://api.ipgeolocation.io/{0}".format(path)
146+
jsonResponse = None
147+
148+
try:
149+
response = requests.get(url, params=urlParams)
150+
jsonResponse = response.json()
151+
152+
if response.status_code != 200:
153+
print("HTTP Get Request Failed: status_code={0}, response={1}".format(response.status_code, jsonResponse))
154+
except RequestException as e:
155+
print(e)
156+
except ValueError as e:
157+
print(e)
158+
159+
return jsonResponse
160+
161+
def __post(self, path: str, requestData: str = "", urlParams: dict = {}) -> []:
162+
url = "https://api.ipgeolocation.io/{0}".format(path)
163+
jsonResponse = None
164+
165+
try:
166+
response = requests.post(url, params=urlParams, data=requestData)
167+
jsonResponse = response.json()
168+
169+
if response.status_code != 200:
170+
print("HTTP Post Request Failed: status_code={0}, response={1}".format(response.status_code, jsonResponse))
171+
except RequestException as e:
172+
print(e)
173+
except ValueError as e:
174+
print(e)
175+
176+
return jsonResponse

README.md

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# IP Geolocation API Python SDK
2+
3+
## Introduction
4+
5+
[IPGeolocation API](https://ipgeolocation.io) is the solution to identify country code (ISO2 and ISO3 standard), country name, continent code, continent name, country capital, state/province, district, city, zip code, latitude and longitude of city, is country belongs to Europian Union, calling code, top level domain (TLD), languages, country flag, internet service provider (ISP), connection type, organization, geoname ID, currency code, currency name, time zone ID, time zone offset, current time in the time zone, is time zone in daylight saving time, and total daylight savings. This document provides important information to help you get up to speed with IPGeolocation API using IP Geolocation API Typescript SDK.
6+
7+
Developers can use this Typescript SDK for software and web projects related to, but not limited to:
8+
9+
1. Display native language and currency
10+
2. Redirect based on the country
11+
3. Digital rights management
12+
4. Web log stats and analysis
13+
5. Auto-selection of country, state/province and city on forms
14+
6. Filter access from countries you do not do business with
15+
7. Geo-targeting for increased sales and click-through
16+
17+
## Quick Start Guide
18+
19+
You need a valid 'IPGeolocation API key' to use this SDK. [Sign up](https://ipgeolocation.io/signup) here and get your free API key if you don't have one.
20+
21+
## System Requirements
22+
23+
Internet connection is required to run this component. This SDK uses ```requests``` module that you need to install before it. Here is the command to install ```requests``` module:
24+
25+
```bash
26+
pip install requests --upgrade --user
27+
```
28+
29+
## Basic Usage
30+
31+
### Setup API
32+
33+
```python
34+
from IPGeolocation import IPGeolocationAPI
35+
36+
# Create IPGeolocationAPI object. Constructor takes one parameter.
37+
# 1) API key ()
38+
ipgeolocationAPI = IPGeolocationAPI("YOUR_API_KEY")
39+
```
40+
41+
### Geolocation Lookup
42+
43+
```python
44+
from IPGeolocation import GeolocationParams
45+
46+
# Get complete geolocation for the calling machine's IP address
47+
geolocation = ipgeolocationApi.getGeolocation()
48+
print(geolocation)
49+
50+
# Get complete geolocation in Russian** for IP address (1.1.1.1)
51+
geolocationParams = GeolocationParams()
52+
geolocationParams.setIPAddress("1.1.1.1")
53+
geolocationParams.setLang("ru")
54+
55+
# getGeolocation method returns valid JSON that contains IPGeolocation API response
56+
geolocation = ipgeolocationAPI.getGeolocation(geolocationParams)
57+
58+
# Get custom geolocation (only "geo, time_zone and currency" fields/objects) for an IP address (1.1.1.1)
59+
geolocationParams = GeolocationParams()
60+
geolocationParams.setIPAddress("1.1.1.1")
61+
geolocationParams.setFields("geo,time_zone,currency")
62+
63+
geolocation = ipgeolocationAPI.getGeolocation(geolocationParams)
64+
65+
# Exclude fields/obejects from complete geolocation in Italian language
66+
geolocationParams = GeolocationParams()
67+
geolocationParams.setExcludes("continent_name,country_code3,time_zone")
68+
geolocationParams.setLang("it")
69+
70+
geolocation = ipgeolocationAPI.getGeolocation(geolocationParams)
71+
```
72+
73+
### Bulk Geolocations Lookup
74+
75+
```python
76+
# Query geolocation in German** for multiple IP addresses and all fields
77+
geolocationParams = GeolocationParams()
78+
geolocationParams.setLang("de")
79+
geolocationParams.setIPAddresses(["1.1.1.1", "2.2.2.2", "3.3.3.3"])
80+
81+
geolocations = ipgeolocationAPI.getGeolocation(geolocationParams)
82+
print(geolocations)
83+
84+
# Specify the required fields/objects for multiple IP addresses
85+
geolocationParams = GeolocationParams()
86+
geolocationParams.setIPAddresses(["1.1.1.1", "2.2.2.2", "3.3.3.3"])
87+
geolocationParams.setFields("geo")
88+
89+
geolocations = ipgeolocationAPI.getGeolocation(geolocationParams)
90+
```
91+
92+
### Timezone API
93+
94+
```python
95+
from IPGeolocation import TimezoneParams
96+
97+
# Get time zone information by time zone ID
98+
timezoneParams = TimezoneParams()
99+
timezoneParams.setTimezone("America/Los_Angeles")
100+
101+
timezone = ipgeolocationAPI.getTimezone(timezoneParams)
102+
print(timezone)
103+
104+
# Get time zone information by latitude and longitude of the location
105+
timezoneParams = TimezoneParams()
106+
timezoneParams.setCoordinates(37.1838139, -123.8105225)
107+
108+
timezone = ipgeolocationAPI.getTimezone(timezoneParams)
109+
110+
# Get time zone information for IP address (1.1.1.1) and geolocation information Japanese**
111+
timezoneParams = TimezoneParams()
112+
timezoneParams.setIPAddress("1.1.1.1")
113+
114+
timezone = ipgeolocationAPI.getTimezone(timezoneParams)
115+
116+
# Query time zone information for calling machine's IP address
117+
timezone = ipgeolocationAPI.getTimezone()
118+
```
119+
120+
** IPGeolocation provides geolocation information in the following languages:
121+
122+
* English (en)
123+
* German (de)
124+
* Russian (ru)
125+
* Japanese (ja)
126+
* French (fr)
127+
* Chinese Simplified (cn)
128+
* Spanish (es)
129+
* Czech (cs)
130+
* Italian (it)
131+
132+
By default, geolocation information is returned in English. Response in a language other than English is available to paid users only.

0 commit comments

Comments
 (0)