Getting started
Learn how to make your first request on the Particeep API
During this tutorial, we are going to use a test environment with a common API Key and secrets.
Please follow the instructions here to get your test, production key and secret.
To switch in between environments you just need to change the base URL, API key and secret. Everything else will work the exact same way.
NB: We will use the Particeep’s core API for this tutorial. Our insurance for API follows the same mechanisms for authorization;you just need to change the base URL and API key/secret. Click here to see the details.
Public access
- base url
- https://test-api.particeep.com
- key
- d6a53e1a-fc8e-4251-9dda-fabbce5f2a2c
- secret
- 9bb3c122-0272-4bed-a632-19d5d52c7b5e
Step 1 - First request
We are going to take care of your API first request. The sample code will be on Java, we will make available a sample in all main languages soon.
The first request is a health check of the api: it always return Ok
and doesn’t need any authentication.
NB: We will use the WS lib from the play framework to do the http request. We will use Play a lot of Particeep but you can easily achieve the same with another tool like Apache HttpClient or plain URL.openConnection from the JDK.
String url = "https://test-api.particeep.com/ping";
HttpResponse result = WS.url(url).get();
String result = result.getString();
System.out.println(result);
var request = require("request");
request("https://test-api.particeep.com/ping", function(error, response, body) {
console.log(body);
});
require 'net/http'
url = URI.parse('https://test-api.particeep.com/ping')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
#! /usr/bin/env python3
import requests
r = requests.get("https://test-api.particeep.com/ping")
print(r.content)
$response = http_get("https://test-api.particeep.com/ping");
echo $response
resp, err := http.Get("https://test-api.particeep.com/ping")
This request is helpful to verify that our server is running fine.
Then you should have a lip set up to do the remote request and then you are ready to go to the next step: Authentication.
Step 2 - Handling security
Try to do a request on https://test-api.particeep.com/v1/info
.
This is an endpoint, which returns to basic data on the API like on the current version. If You use the code from step 1, you should get 403
for the http code which means forbidden and the following body.
{
"error" : {
"hasError" : true,
"errors" : [
{
"message" : "error.api.invalid.key"
}
]
}
}
error.api.invalid.key
indicate that your credentials are not sent correctly : we will fix that
To get authentified we need to add 2 headers to our request : DateTime
and Authorization
DateTime’s header
DateTime is easy : it’s juste the current date in the iso 8601 format. E.g: 2015-10-19T11:04:18Z
With the help of the jodatime library, we can build it that way
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
private static String buildDateHeader() {
DateTime date = DateTime.now(DateTimeZone.UTC);
DateTimeFormatter format = ISODateTimeFormat.dateTimeNoMillis().withZoneUTC();
return format.print(date);
}
from datetime import datetime
def build_date_header():
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
function buildDateHeader() {
date_default_timezone_set('UTC');
return date('Y-m-d\TH:i:s\Z', time());
}
Autorization’s header
Now let’s build the autorization’s header
Basically the idea is to
- concatenate your api’s secret, api’s key and DateTime header
- take the bytes in UTF8
- sign-it with HmacSHA1
- encode the result in base64
Here is the code with comments for each step :
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
// you can find it in commons-codec-1.10.jar
import org.apache.commons.codec.binary.Base64;
public static String buildAuthorizationHeader(String apiKey, String apiSecret, String dateTime)
throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
//Concat your keys and DateTime in the following order : APISecret + APIKey + DateTime
String toSign = apiSecret + apiKey + dateTime;
//Get a list of bytes from the resulting string in UTF-8 format
byte[] messageBytes = toSign.getBytes("UTF-8");
//Get a list of bytes from your APISecret in UTF-8 format
byte[] secretBytes = apiSecret.getBytes("UTF-8");
//Sign 'messageBytes' with 'secretBytes' using SHA1.
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec signingKey = new SecretKeySpec(secretBytes, "HmacSHA1");
mac.init(signingKey);
byte[] result = mac.doFinal(messageBytes);
//Encode the resulting bytes in hexadecimal format.
char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
int len = result.length;
char[] hexChars = new char[len * 2];
for (int charIndex = 0, startIndex = 0; charIndex < hexChars.length;) {
int bite = result[startIndex++] & 0xff;
hexChars[charIndex++] = HEX_CHARS[bite >> 4];
hexChars[charIndex++] = HEX_CHARS[bite & 0xf];
}
// We use lowercase
String sign = new String(hexChars).toLowerCase();
//Encode the bytes of the result in base 64.
String signature = new String(Base64.encodeBase64(sign.getBytes("UTF-8")));
//Concat all results like this: PTP:APIKey:signature
String authorization = "PTP:" + apiKey + ":" + signature;
return authorization;
}
from hashlib import sha1
from base64 import urlsafe_b64encode
import hmac
def build_authorization_header(api_key, api_secret, date_time):
to_sign = api_secret + api_key + date_time
msg_bytes = bytes(to_sign, 'utf-8')
sec_bytes = bytes(api_secret, 'utf-8')
hasher = hmac.new(sec_bytes, msg_bytes, sha1)
hex_signature = hasher.hexdigest()
b64_signature = urlsafe_b64encode(bytes(hex_signature, 'utf-8'))
return ':'.join(["PTP",api_key,str(b64_signature, 'UTF-8')])
function buildAuthorizationHeader($apiKey, $apiSecret, $date) {
//Concat your keys and DateTime in the following order : APISecret + APIKey + DateTime
$toSign = $apiSecret . $apiKey . $date;
//Sign using SHA1.
$messageBytes = utf8_encode($toSign);
$secretBytes = utf8_encode($apiSecret);
$result = hash_hmac('sha1', $messageBytes, $secretBytes);
//Encode the result in base 64.
$signature = base64_encode($result);
//Concat all results like this: PTP:APIKey:signature
return "PTP:" . $apiKey . ':' . $signature;
}
Final request
Now we are putting everything together to get a working request
public static void test() {
String url = "http://test-api.particeep.com/v1/info";
String apiKey = "d6a53e1a-fc8e-4251-9dda-fabbce5f2a2c";
String apiSecret = "9bb3c122-0272-4bed-a632-19d5d52c7b5e";
String dateTime = buildDateHeader();
Map<String, String> headers = new HashMap<String, String>();
headers.put("DateTime", dateTime);
headers.put("Authorization", buildAuthorizationHeaderSafe(apiKey, apiSecret, dateTime));
HttpResponse rez = WS.url(url).headers(headers).get();
System.out.println("status: " + rez.getStatus());
System.out.println("json:" + rez.getString());
}
private static String buildAuthorizationHeaderSafe(String apiKey, String apiSecret, String dateTime) {
try {
return buildAuthorizationHeader(apiKey, apiSecret, dateTime);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
Logger.error(e, "Error while creating autorization header for Particeep's api");
return "";
}
}
import requests
def test():
url = "http://test-api.particeep.com/v1/info"
api_key = "d6a53e1a-fc8e-4251-9dda-fabbce5f2a2c"
api_secret = "9bb3c122-0272-4bed-a632-19d5d52c7b5e"
date_time = build_date_header()
headers={
"Authorization": build_authorization_header(api_key, api_secret, date_time),
"DateTime": date_time,
"Accept": "application/json"
}
http_response = requests.get(url, headers=headers)
print("status: %i" % http_response.status_code)
print("json: %s" % http_response.json())
function test() {
// Request using cURL library
$ch = curl_init();
$url = 'http://test-api.particeep.com/v1/info';
$apiKey = '52c5a6c5-accd-4b94-9e6a-fd2c8cc819e1';
$apiSecret = '3e3d430a-3f4e-489d-85e3-6d0d62e05b38';
$dateTime = buildDateHeader();
$headers = [
'api_key: 52c5a6c5-accd-4b94-9e6a-fd2c8cc819e1',
'Authorization: ' . buildAuthorizationHeader($apiKey, $apiSecret, $dateTime),
'DateTime: ' . $dateTime,
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec($ch);
curl_close($ch);
echo $server_output;
}
You should see this response on your console
status: 200
json: {"version":"1","debugEnable":true,"metaEnable":true}
Next steps
Now you know how to make a request with credentials to Particeep’s API. You may want to