Skip to content

Commit bd0d96a

Browse files
author
Cameron James
committed
Initial Commit
1 parent a9628c9 commit bd0d96a

File tree

5 files changed

+361
-0
lines changed

5 files changed

+361
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/vendor/
2+
public_html

README.md

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
# BigDataCloud PHP API Client
2+
3+
4+
A PHP client for connecting to the API services provided by [BigDataCloud](https://www.bigdatacloud.net)
5+
6+
7+
8+
## What API services does [BigDataCloud](https://www.bigdatacloud.net) offer?
9+
10+
BigDataCloud offers a range of extremely useful and fast APIs that can be utilised in both backend and frontend scenarios.
11+
From validating customer input live to the next generation of IP Geolocation technology, BigDataCloud has an API suitable to your needs.
12+
13+
For a full list of APIs, visit our [documentation area](https://www.bigdatacloud.net/ip-geolocation-apis).
14+
15+
You can access any and all BigDataCloud APIs with a free API Key.
16+
To get your API Key, just access your account and retrieve it from your [Account Dashboard](https://www.bigdatacloud.net/customer/account).
17+
If you are not yet a customer, it is completely free to join.
18+
19+
20+
21+
## Documentation
22+
23+
For documentation specific to this api client, please read below.
24+
For more specific documentation to the APIs available, including endpoints, request and response data, please visit our [documentation area](https://www.bigdatacloud.net/ip-geolocation-apis).
25+
26+
27+
28+
## Authentication / Identification
29+
30+
To use this API client you must have a BigDataCloud API Key.
31+
To get your personal key, just access your account and retrieve it from your [Account Dashboard](https://www.bigdatacloud.net/customer/account).
32+
If you are not yet a customer, it is completely free to join.
33+
34+
Simply provide this key when initiating the php api client, and it will be included in all requests to the BigDataCloud API Server.
35+
See the example below.
36+
37+
38+
39+
## Installation via Composer
40+
41+
`composer require bigdatacloudapi/php-api-client`
42+
43+
44+
45+
## Manual Installation
46+
47+
1. Download package, extract contents to relevant folder
48+
2. Require "(extracted-location)/src/Client.php" in your PHP script
49+
3. Initiate new client as in below example utilising \BigDataCloud\Api\ namespace
50+
51+
52+
53+
## Example usage
54+
55+
```php
56+
<?php
57+
58+
//Installed via Composer
59+
require_once __DIR__ . '/vendor/autoload.php';
60+
61+
//Installed manually
62+
//Using composer installed location for example, simply reference the /src/Client.php where extracted/installed instead.
63+
//require_once __DIR__ . '/vendor/bigdatacloudapi/php-api-client/src/Client.php';
64+
65+
$apiKey = "XXX"; // Your api key found at: https://www.bigdatacloud.net/customer/account
66+
67+
$client = new \BigDataCloud\Api\Client($apiKey);
68+
69+
70+
/*
71+
Can specify the api endpoint using either camelised magic methods, or by calling the communicate command directly.
72+
Example magic method: "GET" from "ip-geolocation-full" endpoint becomes: getIpGeolocationFull();
73+
*/
74+
75+
//$result=$client->communicate('ip-geolocation-full','GET',['ip'=>'8.8.8.8']);
76+
77+
$result=$client->getIpGeolocationFull(['ip'=>'8.8.8.8']);
78+
79+
var_dump($result);
80+
```
81+
82+
83+
## Example output
84+
85+
```javascript
86+
{
87+
"ip": "8.8.8.8",
88+
"country": {
89+
"isoAlpha2": "US",
90+
"isoAlpha3": "USA",
91+
"m49Code": 840,
92+
"isoName": "United States of America (the)",
93+
"isoAdminLanguages": [
94+
{
95+
"isoAlpha3": "eng",
96+
"isoAlpha2": "en",
97+
"isoName": "English"
98+
}
99+
],
100+
"unRegion": "Americas/Northern America",
101+
"currency": {
102+
"numericCode": 840,
103+
"code": "USD",
104+
"name": "US Dollar",
105+
"minorUnits": 2
106+
},
107+
"wbRegion": {
108+
"id": "NAC",
109+
"iso2Code": "XU",
110+
"value": "North America"
111+
},
112+
"wbIncomeLevel": {
113+
"id": "HIC",
114+
"iso2Code": "XD",
115+
"value": "High income"
116+
},
117+
"callingCode": "1",
118+
"countryFlagEmoji": "🇺🇸"
119+
},
120+
"location": {
121+
"isoPrincipalSubdivision": "California",
122+
"isoPrincipalSubdivisionCode": "US-CA",
123+
"city": "Mountain View",
124+
"postcode": "94043",
125+
"latitude": 37.42,
126+
"longitude": -122.09,
127+
"timeZone": {
128+
"ianaTimeId": "America/Los_Angeles",
129+
"displayName": "(UTC-08:00) Pacific Time (US & Canada)",
130+
"effectiveTimeZoneFull": "Pacific Daylight Time",
131+
"effectiveTimeZoneShort": "PDT",
132+
"UtcOffsetSeconds": -25200,
133+
"UtcOffset": "-07",
134+
"isDaylightSavingTime": true,
135+
"localTime": "2019-04-06T04:06:39.1691744"
136+
}
137+
},
138+
"lastUpdated": "2019-04-06T09:09:36.1877959Z",
139+
"network": {
140+
"registry": "ARIN",
141+
"registryStatus": "assigned",
142+
"registeredCountry": "US",
143+
"registeredCountryName": "United States of America (the)",
144+
"organisation": "Google LLC",
145+
"isReachableGlobally": true,
146+
"isBogon": false,
147+
"bgpPrefix": "8.8.8.0/24",
148+
"bgpPrefixNetworkAddress": "8.8.8.0",
149+
"bgpPrefixLastAddress": "8.8.8.255",
150+
"totalAddresses": 256,
151+
"carriers": [
152+
{
153+
"asn": "AS15169",
154+
"asnNumeric": 15169,
155+
"organisation": "Google LLC",
156+
"name": "GOOGLE",
157+
"registry": "ARIN",
158+
"registeredCountry": "US",
159+
"registeredCountryName": "United States of America (the)",
160+
"registrationDate": "2000-03-30",
161+
"registrationLastChange": "2012-02-25",
162+
"totalIpv4Addresses": 8698103,
163+
"totalIpv4Prefixes": 435,
164+
"totalIpv4BogonPrefixes": 0,
165+
"rank": 53,
166+
"rankText": "#53 out of 62,872"
167+
}
168+
],
169+
"viaCarriers": [
170+
{
171+
"asn": "AS7018",
172+
"asnNumeric": 7018,
173+
"organisation": "ATT Services Inc.",
174+
"registeredCountry": "US",
175+
"registeredCountryName": "United States of America (the)",
176+
"rank": 2
177+
},
178+
/*........*/
179+
{
180+
"asn": "AS31019",
181+
"asnNumeric": 31019,
182+
"organisation": "Paulus M. Hoogsteder trading as Meanie",
183+
"registeredCountry": "NL",
184+
"registeredCountryName": "Netherlands (the)",
185+
"rank": 51153
186+
}
187+
]
188+
},
189+
"confidence": "low",
190+
"confidenceArea": [
191+
{
192+
"latitude": 18.0256672,
193+
"longitude": -66.5275345
194+
},
195+
/*........*/
196+
{
197+
"latitude": 18.0256672,
198+
"longitude": -66.5275345
199+
}
200+
],
201+
"securityThreat": "unknown",
202+
"hazardReport": {
203+
"isKnownAsTorServer": false,
204+
"isKnownAsProxy": false,
205+
"isKnownAsMailServer": false,
206+
"isKnownAsPublicRouter": false,
207+
"isBogon": false,
208+
"isUnreachable": false
209+
}
210+
}
211+
```

composer.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "bigdatacloudapi/php-api-client",
3+
"description": "A PHP client wrapper for the BigDataCloud API",
4+
"minimum-stability": "dev",
5+
"license": "MIT",
6+
"require": {
7+
"php": ">=5.4",
8+
"ext-curl": "*"
9+
},
10+
"autoload": {
11+
"psr-4": {
12+
"BigDataCloud\\Api\\": "src/"
13+
}
14+
}
15+
}

composer.lock

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Client.php

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
<?php
2+
namespace BigDataCloud\Api;
3+
4+
class Client {
5+
public $includeTimer=0;
6+
public $apiKey;
7+
public $nameSpace;
8+
public $server='api.bigdatacloud.net';
9+
public $code;
10+
public $timeout=120;
11+
12+
public function __construct($apiKey,$nameSpace='data',$server=null) {
13+
if ($server) $this->server=$server;
14+
$this->apiKey=$apiKey;
15+
$this->nameSpace=$nameSpace;
16+
}
17+
18+
public function setIncludeTimer($includeTimer=1) {
19+
$this->includeTimer=$includeTimer;
20+
return $this;
21+
}
22+
23+
public function getIncludeTimer() {
24+
return $this->includeTimer;
25+
}
26+
27+
public function __call(string $name, Array $args=[]) {
28+
$key=$name;
29+
$key[0] = strtolower($key[0]);
30+
$key = preg_replace_callback('/([A-Z])/', function($c) {
31+
return '-'.strtolower($c[1]);
32+
}, $key);
33+
$key=explode('-',$key);
34+
$type=strtoupper(array_shift($key));
35+
switch($type) {
36+
case 'GET':
37+
case 'POST':
38+
case 'PUT':
39+
case 'PATCH':
40+
case 'DELETE':
41+
case 'HEAD':
42+
return $this->communicate(
43+
implode('-',$key),
44+
$type,
45+
count($args) ? $args[0] : null
46+
);
47+
break;
48+
}
49+
50+
throw new \BadMethodCallException('Method '.$name.' does not exist');
51+
}
52+
53+
public function communicate(string $endpoint,string $type,$payload=null) {
54+
$ch = curl_init();
55+
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
56+
$qs='';
57+
$headers=[];
58+
if (count($payload)) {
59+
switch($type) {
60+
case 'GET':
61+
case 'HEAD':
62+
case 'DELETE':
63+
$qs='?'.http_build_query($payload);
64+
break;
65+
case 'POST':
66+
case 'PUT':
67+
case 'PATCH':
68+
$headers[]='Content-Type:application/json';
69+
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($payload));
70+
break;
71+
}
72+
}
73+
curl_setopt($ch, CURLOPT_URL,"https://".$this->server."/".$this->nameSpace.'/'.$endpoint.$qs);
74+
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
75+
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
76+
if (!$payload || ($payload && !array_key_exists('key',$payload))) $headers[]='X-BDC-Key: '.$this->apiKey;
77+
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
78+
$timerStart=microtime(true);
79+
$response = curl_exec ($ch);
80+
$timerStop=microtime(true);
81+
$httpcode = $this->code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
82+
curl_close($ch);
83+
switch ($httpcode) {
84+
case 200:
85+
if (!$response) {
86+
throw new \Exception('Invalid or empty response returned from BDC API: '.print_r($response,1));
87+
}
88+
try {
89+
if ($response=json_decode($response,true)) {
90+
if ($this->getIncludeTimer()) {
91+
$response['__apiResponseTime']=round(($timerStop-$timerStart)*1000,2);
92+
}
93+
return $response;
94+
} else {
95+
throw new \Exception('Invalid JSON returned from BDC API: '.print_r($response,1));
96+
}
97+
} catch (\Exception $e) {
98+
throw new \Exception('Invalid JSON returned from BDC API: '.print_r($response,1));
99+
}
100+
break;
101+
case 404:
102+
return false;
103+
break;
104+
case 403:
105+
throw new \Exception('Permission denied accessing BDC API'."\n".print_r($response,1),$httpcode);
106+
break;
107+
default:
108+
throw new \Exception('Error communicating with the BDC API: '.print_r($response,1),$httpcode);
109+
break;
110+
}
111+
112+
}
113+
}

0 commit comments

Comments
 (0)