NAV Navbar
Logo
Java JavaScript Node.js Python iOS PHP cURL

Introduction

Overview

The Breinify API provides features like geocoding, reverse geocoding, weather and events look up, holidays determination, and analytics. Within the following paragraphs the different endpoints, their provided functionality, the concrete requests, and examples are provided.

You selected the documentation for the Java language utilizing the Java library. The library is deployed under the MIT License and is available as open-source project on GitHub. The library is compatible with Java 8 and above.

/*
 * I'm an example snippet of the Java library. The following
 * documentation should help you to get started with the library.
 * Even more examples and documentation can be found at:
 *
 * https://github.com/Breinify/brein-api-library-java
 */

You selected the documentation for the JavaScript language utilizing the JavaScript Browser library. The library is deployed under the MIT License and is available as open-source project on GitHub.

/*
 * I'm an example snippet of the JavaScript library. The following
 * documentation should help you to get started with the library.
 * Even more examples and documentation can be found at:
 *
 * https://github.com/Breinify/brein-api-library-javascript-browser
 */

You selected the documentation for Node.js library. The library is deployed under the MIT License and is available as open-source project on GitHub.

/*
 * I'm an example snippet of the Node.js library. The following
 * documentation should help you to get started with the library.
 * Even more examples and documentation can be found at:
 *
 * https://github.com/Breinify/brein-api-library-node
 */

You selected the documentation for the Python language for Python 3. The library is deployed under the MIT License and is available as an open-source project on GitHub.

"""
  I'm an example snippet of the Python library. The following
  documentation should help you to get started with the library.
  Even more examples and documentation can be found at:
  https://github.com/Breinify/brein-api-library-python
"""

You selected the documentation for the Swift language utilizing the iOS library. The library is deployed under the MIT License and is available as open-source project on GitHub. The library is compatible with Swift 3.

/*
 * I'm an example snippet of the iOS library. The following
 * documentation should help you to get started with the library.
 * Even more examples and documentation can be found at:
 *
 * https://github.com/Breinify/brein-api-library-ios
 */

You selected the documentation for PHP library. The library is deployed under the MIT License and is available as open-source project on GitHub.

/*
 * I'm an example snippet of the PHP library. The following
 * documentation should help you to get started with the library.
 * Even more examples and documentation can be found at:
 *
 * https://github.com/Breinify/brein-api-library-php
 */

You selected the documentation for curl. curl is a tool to transfer data from or to a server, using one of the supported protocols. The command is designed to work without user interaction.

 # curl is available by default on many systems. If it is not available
 # on yours, please search for instructions using Google.
 #
 # You can easily check if curl is available by typing curl in your
 # console.
 $ curl
 curl: try 'curl --help' or 'curl --manual' for more information

There are libraries for different languages available. The libraries are designed to simplify the implementation effort needed to a minimum.

Language GitHub Repository
Java brein-api-library-java
JavaScript (Browser) brein-api-library-javascript-browser
JavaScript (Node.js) brein-api-library-node
Python brein-api-library-python
PHP brein-api-library-php
Ruby brein-api-library-ruby
Java (Android) brein-api-library-android
iOS brein-api-library-ios
Shell (cURL) brein-api-library-curl

This documentation provides code-snippets for each of these libraries. Just select your favorite language on the top right and follow the instructions.

Getting Started

Breinify uses API keys to allow access to the API. You can sign up for a free API key at https://www.breinify.com.

If you decide to use an API key with a secret, be sure that you don’t show the secret in publicly accessible areas such as client-side code, GitHub, or jsFiddle. Additionally, you may limit the usage of an API key to specific domains (ip-addresses) to increase security. The following step-by-step guide illustrates how to retrieve your own API key.

Request an API Key

  1. Go to https://www.breinify.com and click on Request A Demo.



    Breinify’s site, the ‘Request A Demo’ button is located on the top, highlighted in blue

  2. Provide the needed information, it is appropriate to enter N/A for Company Name. Please provide a short description, i.e., what you are planning to do with the key and click on the Send Request button.



    Please provide the requested information and explain what you are going to do with the key.

  3. After a short time, you receive an email with your credentials.


  4. Go back to https://www.breinify.com and use the credentials to login.



    Please use the username and password sent to you via email.

  5. Click on Keys and retrieve the needed information about your API key. Further configuration can be applied, but are not necessarily covered by this documentation.



    The create account already contains one API key.

  6. To check the settings of the created key click on the row of it. Depending on the used library it is recommended to enable the Verification Signature or not. If the Verification Signature is enabled, the library needs to know the secret (which should never be publically available) to sign the requests send to the endpoint. How to set and use the secret is explained later (and depending on the library) in this documentation.



    Further settings for an API key (including the setting to specify if a signature is required).

In this documentation, the following API key (and secret) is used within the examples:

API key938D-3120-64DD-413F-BB55-6573-90CE-473A
Secretutakxp7sm6weo5gvk7cytw==

Integrate the Library

The library is available on Maven Central. You can add it to your Maven project by adding the following dependency and replacing the property ${CURRENT_VERSION}, with the current version of the library or the version you would like to use.

<dependency>
  <groupId>com.breinify</groupId>
  <artifactId>brein-api-library-java</artifactId>
  <version>${CURRENT_VERSION}</version>
</dependency>

The library utilizes a query engine, to send requests to the API endpoint. Currently, two query engines are supported: UniRest (recommended) or Jersey. By default, none of the engines is added as dependency, thus it is necessary to pick and add one of the two and add its dependency as well.

<dependency>
    <groupId>com.mashape.unirest</groupId>
    <artifactId>unirest-java</artifactId>
    <version>1.4.9</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.19.1</version>
</dependency>

There are multiple ways on how to integrate the library within your project. The library is available on bower, jsdelivr (CDN), npm, or as download from GitHub.

Using Bower

The library can be installed via bower, further information about bower can be found here.

bower install breinify-api --save

jsdelivr (CDN)

The library can be loaded directly within the html code from . jsdelivr. Please replace the {version} placeholder with the version you would like to use. To see a list of all available version have a look here

<script src="https://cdn.jsdelivr.net/breinify-api/{version}/breinify-api.min.js" type="text/javascript"></script>

To use the most current SNAPSHOT version, you can also use the following URL. This URL should only be used for developing purposes (see also rawgit.com).

<script src="https://rawgit.com/Breinify/brein-api-library-javascript-browser/master/dist/breinify-api.min.js" type="text/javascript" ></script>

Using npm

The library can be installed via npm, further information about npm can be found here. It should be mentioned that it is not recommended to use this library with Node.js, instead use the Node.js Library

npm install breinify-api --save

The library is distributed through Node.js package manager (npm).

npm install breinify-node --save

The recommended way to integrate the Brein library is to simply use pip.

pip3 install brein-api

Additionally, you can install the library from sorce (available on [Github](https://github.com/breinify/brein-api-library-python)) by running:

python3 setup.py install

The library is available on Cocoapods. You can add it as a typical pod dependency like this:

target 'MyApp' do
  pod 'BreinifyApi'
end

The library utilizes a query engine, to send requests to the API endpoint. Currently Alamofire is used for this. Furthermore IDZSwiftCommonCrypto is used as a wrapper for Apple’s CommonCrypto library. Both dependencies will automatically be included.

The library is available on Packagist. You can add it to your project using Composer.

composer require breinify/brein-engine-api

There is no special integration needed to use the commands mentioned here. The only requirement is curl, which should be already available on your OS or should be easy to install (use Google for instructions on how to install curl for your OS).

Note: The following commands can be used to check if needed tools are available on your system (i.e., curl and openssl (only needed if signagures are used)).

 $ curl -s -o /dev/null -w "%{http_code}" https://www.breinify.com
 200

$ echo -n “Message” | openssl dgst -binary -sha256 -hmac “secret” | openssl enc -base64 qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc= “`

Each language has different requirements and ways on how to integrate a library within an existing system or a project. Each Breinify library is provided through state-of-the-art and commonly used package and dependency management platforms (like Maven for Java, npm for Node.js, bower for JavaScript). To integrate the selected library within your project, it is recommended to use the appropriate and described way on the left. Nevertheless, if you need the library to be available on another distribution system, please let us know and request an integration.

Configure the Library

The Java library is configured through a single call of Breinify.setConfig(...). The configuration can be changed at any time by calling the method. It is also recommended that the library’s resources will be released when the application shutdowns or the library is not used anymore by calling Breinify.shutdown().

Note: If working in a multi-threaded environment, it is not recommended to change the configuration within the different threads, otherwise it is impossible to foresee, which configuration will be used.

Breinify.setConfig("938D-3120-64DD-413F-BB55-6573-90CE-473A", 
                   "utakxp7sm6weo5gvk7cytw==");
/*
 * After the configuration is set, you can use the library 
 * (multi-threading is supported). After the library is not used
 * anymore, it is recommended to release the used resources.
 */
Breinify.shutdown();

The default configuration of the library auto-detects, which engine should be used to fire the queries to the API. By default, the library has two engines available one based on `UniRest` and the other one based on `Jersey`. To use the auto-detection, you simply have to add the dependency (see Integrate the Library).

It is recommended to use the JavaScript library without any signature (i.e., the Verification Signature in the UI is disabled and no secret is needed). For a full list of all possible settings have a look here.

Breinify.setConfig({ 
    'apiKey': '938D-3120-64DD-413F-BB55-6573-90CE-473A' 
});

The configuration must be performed prior to any other usage, thus it is recommended to place the specified code right after the library is loaded, e.g.:

<script src="https://cdn.jsdelivr.net/npm/breinify-api@{version}/dist/breinify-api.min.js" type="text/javascript"></script>
<script type="text/javascript">
Breinify.setConfig({ 
    'apiKey': '938D-3120-64DD-413F-BB55-6573-90CE-473A' 
});
</script>

It is also possible to use, e.g., the jQuery ready-method and make sure that the configuration is called prior to any other usage of the library.

$(document).ready(function() {
    Breinify.setConfig({ 
        'apiKey': '938D-3120-64DD-413F-BB55-6573-90CE-473A' 
    });
});

Another solution is to use the onload-method to execute the configuration script right after the library is loaded.

<script onload="function() { Breinify.setConfig({...}); }" src="https://cdn.jsdelivr.net/breinify-api/{version}/breinify-api.min.js" type="text/javascript"></script>

It is recommended to use the Node.js library with a signature (i.e., the Verification Signature in the UI should be enabled and the secret is needed).

Whenever a Breinify instance is created, the configuration has to be specified.

var Breinify = require('breinify-node');
var breinify = new Breinify({ 
    'apiKey': '938D-3120-64DD-413F-BB55-6573-90CE-473A',
    'secret': 'utakxp7sm6weo5gvk7cytw==' 
});

Within this documentation the usage of the variable breinify indicates that a configured instance of Breinify is used.

To configure the Python library, either supply your API key:

from breinify import Breinify
brein = Breinify('938D-3120-64DD-413F-BB55-6573-90CE-473A')

or with an API key and the key’s secret, if required

brein = Breinify('938D-3120-64DD-413F-BB55-6573-90CE-473A',
                 'utakxp7sm6weo5gvk7cytw==')

It is recommended that you configure a secret key for use with the Python library.

The iOS library is configured through a single call of Breinify.setConfig(...). The configuration can be changed at any time by calling the method. It is also recommended that the library’s resources will be released when the application shutdowns or the library is not used anymore by calling Breinify.shutdown().

Note: If working in a multi-threaded environment, it is not recommended to change the configuration within the different threads, otherwise it is impossible to foresee, which configuration will be used.

Breinify.setConfig("938D-3120-64DD-413F-BB55-6573-90CE-473A", 
                   secret: "utakxp7sm6weo5gvk7cytw==")
/*
 * After the configuration is set, you can use the library 
 * (multi-threading is supported). After the library is not used
 * anymore, it is recommended to release the used resources.
 */
Breinify.shutdown()

The Alamofire library is used for any HTTP communication.

It is recommended to use the PHP library with a signature (i.e., the Verification Signature in the UI should be enabled and the secret is needed).

Whenever a Breinify instance is created, the configuration has to be specified.

$breinify = new Breinify("938D-3120-64DD-413F-BB55-6573-90CE-473A", "utakxp7sm6weo5gvk7cytw==");

Within this documentation the usage of the variable breinify indicates that a configured instance of Breinify is used.

When using the command line to request or provide data, there is no special configuration needed.

Note: In the following examples, none of the requests is using a verification signature. If your API key is configured to use a verification signature, you have to add a signature to each request.

 # create the signature for a message sent at 1504832119 (unix time-stamp)
 $ echo -n "1504832119--" | openssl dgst -binary -sha256 -hmac "utakxp7sm6weo5gvk7cytw==" | openssl enc -base64
 eaAPIRpDxxt3uk7TCqScnE7xcPacT9YERwNOedvmSS0=

# now use the signature to send in the request $ curl –ipv4 -X POST https://api.breinify.com/temporaldata \ -H "cache-control: no-cache” \ -H “Content-Type: text/json; charset=utf-8” \ -d ‘{ “apiKey”: “938D-3120-64DD-413F-BB55-6573-90CE-473A”, “signature”: “eaAPIRpDxxt3uk7TCqScnE7xcPacT9YERwNOedvmSS0=”, “unixTimestamp”: 1504832119, “user”: {} }’ “`

In general, each library provides some way of configuration to, e.g., set the API key, the secret or endpoint specific settings. The configuration has to be performed prior to any other usage.

Temporal Data

Resolve Temporal Data

Request: Simple Request

The Java library offers several overloaded versions of the Breinify.temporalData(...) method. In addition, it offers the possibility to fire the request directly from the created request instance by calling execute(). The following examples (and also the use-cases) will introduce both types which are completely interchangable.

If a simple request is fired, the endpoint uses the client’s information (attached to the request, e.g., the ipAddress) to determine the different temporal information.

final BreinTemporalDataResult result = new BreinTemporalData()
    .setLocalDateTime()
    .execute();

Another possibility is to provide specific data. This is typically done, if some specific temporal data should be resolved, e.g., a location based on a free text, a pair of coordinates (latitude/longitude), or a specific ip-address. Have a look at the further use cases to see other examples.

final BreinTemporalDataResult result = new BreinTemporalData()
    .setLookUpIpAddress("204.28.127.66")
    .execute();

The library provides several setter methods to simplify the usage (e.g., the already used setLocalDateTime or setLookUpIpAddress). In addition, it is also possible to set these values using the more general setter methods, i.e., setAdditional(key, value), setUser(key, value), setLocation(key, value), or set(key, value). The above requests could also be performed using:

final BreinTemporalDataResult result = new BreinTemporalData()
    .setAdditional("localDateTime", 
        ZonedDateTime.now().format(BreinTemporalData.JAVA_SCRIPT_FORMAT))
    .execute();
final BreinTemporalDataResult result = new BreinTemporalData()
    .setAdditional("ipAddress", "204.28.127.66")
    .execute();

The JavaScript library offers several overloaded versions of the temporalData method.

Callback only

If a single callback is provided, the library retrieves other available information from the client automatically, e.g., the user-agent, the location (if and only if shared), or the ipAddress.

Breinify.temporalData(function(data) {
    console.log(data);
});

Providing a User Instance

Another possibility is to provide a user object manually. This is typically done, if some specific temporal data should be resolved, e.g., a location based on a free text, a pair of coordinates (latitude/longitude), or a specific ip-address. Have a look at the further use cases to see other examples.

var q = { additional: { ipAddress: '72.229.28.185' }}; 
Breinify.temporalData(q, function(data) {
    console.log(data);
});

The Node.js library offers several overloaded versions of the temporalData method.

Using Latitude/Longitude

It is possible to pass in a latitude/longitude pair.

var latitude = 37.7749;
var longitude = -122.4194;
breinify.temporalData(latitude, longitude, function(data) {
    console.log(data);
});

Using IP-Address

Another possibility is to just pass in an ip-address and resolve the temporal information available.

var ipAddress = '72.229.28.185';
breinify.temporalData(ipAddress, function(data) {
    console.log(data);
});

Using an Object

The most general solution is to pass in an object and specify the different known values to determine what can be resolved (but also what should be returned), based on the provided data. The further usage examples illustrate different possibilities.

var loc1 = { 
    'text': 'San Diego'
};
breinify.temporalData({ 'location': loc1 }, function(data) {
    console.log(data);
});
var loc2 = { 
    'latitude': 37.7749,
    'longitude': -122.4194
};
breinify.temporalData({ 'location': loc2 }, function(data) {
    console.log(data);
});

The Python library supports calls to temporal data by either passing a user object for a user who’s location you want to get information about, for example:

from breinify import User
user = User(ip="72.229.28.185")
info = brein.temporal_data(user=user)

or a description of the location itself, such as:

info = brein.temporal_data(location_free_text="san francisco, ca",
                           unixtime=1492538271)

The iOS library offers several overloaded versions of the Breinify.temporalData(...) method. In addition, it is also possible to split the configuration of the temporalData object and the execution of the request. In this case create an instance of class BreinTemporalData and use this as a parameter later in class Breinify.

If a simple request is fired, the endpoint uses the client’s information (attached to the request, e.g., the ipAddress) to determine the different temporal information.

do {          
     try Breinify.temporalData()
   } catch {
     print("Error is: \(error)")
}

Another possibility is to provide specific data. This is typically done, if some specific temporal data should be resolved, e.g., a location based on a free text, a pair of coordinates (latitude/longitude), or a specific ip-address. Have a look at the further use cases to see other examples.

do {
      let breinTemporalData = BreinTemporalData()
      breinTemporalData.setLookUpIpAddress("204.28.127.66")

      try Breinify.temporalData(breinTemporalData)
    } catch {
      print("Error is: \(error)")
    }    

The library provides several setter methods to simplify the usage (e.g., the already used setLookUpIpAddress).

We are still working on this part of the documentation.

When retrieving temporal data, it is necessary to provide some information via the data-body (using a POST request). These information include: your API key, a user instance specifying known information, and a signature if the API key uses verification signatures.

The first example uses the requesting ip-address to lookup temporal information.

 # if no verification signature is needed, you can retrieve information like that
 $ curl --ipv4 -X POST https://api.breinify.com/temporaldata \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "user": {} }'

It is also possible to lookup temporal information for a specific IP address.

 $ curl --ipv4 -X POST https://api.breinify.com/temporaldata \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "user": { "additional": { "ipAddress": "204.28.127.66" } } }'

There are multiple other values that can be passed in to determine temporal information about a specific location and/or time.

 

Description

This endpoint retrieves temporal data for a time-stamp, a location specified by free-text (geocoding) or a latitude/longitude pair (reverse-geocoding), or an ip-address. More specific the endpoint resolves temporal data like

to temporal information, i.e., any of the following:

HTTP Request: POST https://api.breinify.com/temporaldata

Parameters

Type Name Description Schema
Body body
required
The body represents the plain object containing the further information for the request. body

body

Name Description Schema
apiKey
required
The Breinify API key to be used. string
ipAddress
optional
The client’s requesting IP address (may be set manually, e.g., if the request was proxied through a server). string
signature
optional
Signature to authenticate a request, is only available if the the secret for the Breinify API key is configured. string
signatureType
optional
Type of encryption used for generating the signature, for example, HMAC. string
unixTimestamp
optional
The number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. integer(int64)
user
required
user

user

Name Description Schema
additional
required
Contains information known about a user, such as the time zone they are in, their local time, or information about their location additional

additional

Name Description Schema
ipAddress
optional
An ip-address used for look-up specific tasks, e.g., the user or service triggering the request may be interested to look-up a specific ip and not it’s own. string
localDateTime
optional
User’s local time string. The format should be something like ‘Wed Oct 26 2016 13:02:06 GMT-0700 (EDT)’. string
location
optional
Coordinate data for the user, requires either a latitude/longitude pair, a city, state, country triple, or text. location
timezone
optional
User’s time zone, should follow the tz database naming convention. Examples include: America/New_York and Europe/Paris. string
userAgent
optional
User agent string for the user. For example, ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36’. string

location

Name Description Schema
accuracy
optional
Number representing accuracy. number(double)
city
optional
The name of the city of the location to look up string
country
optional
The name of the country of the location to look up string
latitude
optional
User’s decimal latitude coordinate. number(double)
longitude
optional
User’s decimal longitude coordinate. number(double)
shapeTypes
optional
When supplied, the system will return the GeoJSON data for the given shapeTypes if they are valid. The values should be one of: COUNTRY, STATE, POSTAL, COUNTY, CITY, NEIGHBORHOOD (case-insensitive). This is only relevant if a longitude/latitude is given. < string > array
state
optional
The name of the state of the location to look up string
text
optional
A free text field describing a location, for example ‘NYC’ or ‘San Francisco, CA’ (US only) string

Responses

HTTP Code Description Schema
200 A successful response returns an object with relevant temporal data resolved for the user. Examples of types of data returned are: location of the user, the weather in their area, and holidays that are observed near the user. object
default Something went wrong. Response default

Response default

Name Description Schema
code
required
The error code for general server errors is 500. integer(int32)
fields
optional
Error fields. string
message
optional
Any details about why the error occurred. string

Temporal Data Response

Response: Full Sample Response

The following shows a sample response including all available information. A response may not include a specific information, e.g., if a location cannot be determined the response.location will be undefined.

{
    "holidays": [{
        "types": [ "FEDERAL" ],
        "source": "Government",
        "holiday": "Christmas Day (observed on December 26)"
    }, {
        "types": [ "STATE" ],
        "source": "Government",
        "holiday": "Christmas Day (observed on December 26)"
    }, {
        "types": [ "RELIGIOUS", "HALLMARK" ],
        "source": "Public Information",
        "holiday": "Christmas"
    }],
    "location": {
        "country": "US",
        "city": "San Diego",
        "granularity": "city",
        "lon": -117.1572551,
        "state": "CA",
        "lat": 32.7153292
    },
     "weather": {
        "precipitation": {
            "precipitationType": "none",
            "precipitationAmount": 0.0
        },
        "windStrength": 3.1,
        "temperatureC": 27.25,
        "lastMeasured": 1504640100,
        "temperature": 0.0,
        "cloudCover": 1.0,
        "description": "sky is clear",
        "temperatureF": 81.05,
        "measuredAt": {
            "lon": -117.1572,
            "lat": 32.7153
        }
    },
    "time": {
        "localMonth": 12,
        "localMinute": 34,
        "localSecond": 56,
        "localYear": 2016,
        "timezone": "America/Los_Angeles",
        "epochMonth": 12,
        "epoch": 1482669296,
        "localHour": 4,
        "epochYear": 2016,
        "epochDay": 25,
        "epochHour": 12,
        "localDayName": "Sunday",
        "epochDayName": "Sunday",
        "epochMinute": 34,
        "epochSecond": 56,
        "localDay": 25,
        "localFormatIso8601": "2016-12-25T04:34:56-08:00",
        "epochFormatIso8601": "2016-12-25T12:34:56+00:00"
    },
    "events": []
}

Documented here are the details for the fields returned in the temporal data response, for each of the sections: holidays, location, weather, time, events.

Holiday Return Fields

Holiday results will be given as a list of holiday maps. Each map will contain the following fields.

Location Return Fields

The following are the fields that may be returned in the location portion of the temporal data response.

Weather Return Fields

The following are the fields that may be returned in the weather portion of the temporal data response.

Time Return Fields

The following are the fields that may be returned in the time portion of the temporal data response.

Example Use Cases

Use Case: Resolve by IP-Address

This example shows how to request temporal information from an ip-address. In general, temporal information is more accurate for non-mobile devices. Nevertheless, mobile-devices may have access the coordinates, which help to increase the accuracy.

With the Java library it is really simple to resolve temporal information based on a client’s ip-address. The endpoint utilizes the requesting ip-address to determine, which information to return. Thus, the call does not need any additional data.

final BreinTemporalDataResult result = Breinify.temporalData();

Sometimes, it may be necessary to resolve a specific ip-address instead of the client’s one. To specify the ip-address to resolve, the library provides an overloaded version, i.e.,

final String ip = "72.229.28.185"; 
final BreinTemporalDataResult result = Breinify.temporalData(ip);

With the JavaScript library it is really simple to resolve temporal information based on a client’s ip-address. The endpoint utilizes the requesting ip-address to determine, which information to return. Thus, the call does not need any additional data.

Breinify.temporalData(function(data) {
    console.log(data);
});

Sometimes, it may be necessary to resolve a specific ip-address instead of the client’s one. To specify the ip-address to resolve, the library provides an overloaded version, i.e.,

var ip = '72.229.28.185'; 
Breinify.temporalData({ additional: { ipAddress: ip }}, function(data) {
    console.log(data);
});

In general, the ip-address can be simply passed as first parameter. If you would like to know more about your requesting client, you can also just pass in the requesting ip-address. There are several different ways (also depending on the used framework) available to determine your client’s ip, for example, see client-ip.

breinify.temporalData('72.229.28.185', function(data) {
    console.log(data);
});

Check the example on runkit, to try it yourself, see runkit (ip-address).

To specify the ip-address to resolve, simply pass it through the ip field temporal data request

info = brein.temporal_data(ip="72.229.28.185")

With the iOS library it is really simple to resolve temporal information based on a client’s ip-address. The endpoint utilizes the requesting ip-address to determine, which information to return. Thus, the call does not need any additional data.

do {
     try Breinify.temporalData()
   } catch {
     print("Error is: \(error)")
   }

Sometimes, it may be necessary to resolve a specific ip-address instead of the client’s one. To specify the ip-address to resolve, the library provides an overloaded version, i.e.,

do {
     let ip = "72.229.28.185"
     try Breinify.temporalData(ip)
   } catch {
     print("Error is: \(error)")
   }
// We are still working on this part of the documentation.

This example shows how to resolve temporal information for a specific ip-address.

 $ curl --ipv4 -X POST https://api.breinify.com/temporaldata \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "user": { "additional": { "ipAddress": "72.229.28.185" } } }'

 

Use Case: Example Geocoding

Geocoding describes the task to provide geographical coordinates corresponding to a location. A location can thereby be given by free text or a specific address (following a specific format).

final String text = "NYC";
final BreinTemporalDataResult result = new BreinTemporalData()
    .setLocation(text)
    .execute();
var text = 'NYC';
Breinify.temporalData({ additional: { location: {'text': text }}}, function(data) {
    // the location will be resolved to New York, NY, US
    console.log(data);
});
var location = { location: { text: 'Bemidji' }};
breinify.temporalData(location, function(data) {
    // the location will be resolved to Bemidji, Minnesota, USA
    console.log(data);
});

This example is also available on runkit, to try it yourself, see runkit (free-text).

text = 'NYC'
nyc_info = brein.temporal_data(location_free_text=text)
do {
   let breinTemporalData = BreinTemporalData()
       .setLocation(freeText: "NYC")

   try Breinify.temporalData(breinTemporalData,
       success: {
           (result: BreinResult) -> Void in
           print("Api Success : result is:\n \(result)")

           if let holiday = result.get("holidays") {
               print("Holiday is: \(holiday)")
           }
           if let weather = result.get("weather") {
               print("Weather is: \(weather)")
           }
           if let location = result.get("location") {
              print("Location is: \(location)")
           }
           if let time = result.get("time") {
              print("Time is: \(time)")
           }
           if let events = result.get("events") {
              print("Events are: \(events)")
           }                                   
       })
   } catch {
       print("Error is: \(error)")
   }        
// We are still working on this part of the documentation.
 $ curl --ipv4 -X POST https://api.breinify.com/temporaldata \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "user": { "additional": { "location": { "text": "NYC" } } } }'

 

Use Case: Example Reverse Geocoding

Reverse geocoding refers to the task of determining information for a specific pair of coordinates, i.e., latitude and longitude. The endpoint resolves the information and provides detailed information, like the city, country, or timezone. Furthermore, the library can provide geoJson objects representing the neighborhood, city, state, or zip-code.

final BreinTemporalDataResult result;
result = Breinify.temporalData(37.7609295, -122.4194155,
                               "STATE", "CITY", "NEIGHBORHOOD");
final BreinTemporalDataResult result;
result = new BreinTemporalData()
   .setLatitude(37.7609295)
   .setLongitude(-122.4194155)
   .addShapeTypes("CITY", "NEIGHBORHOOD")
   .execute();

The returned GeoJson instances can be read and used via result.getLocation().getGeoJson("CITY"). If a shape is not available, the getGeoJson(...) method returns null.

var location = {
    location: {
        latitude: 37.7609295,
        longitude: -122.4194155,
        shapeTypes: ['CITY', 'NEIGHBORHOOD']
    }
};
Breinify.temporalData({ additional: location }, function(data) {    
    /* 
     * The location will be resolved to San Francisco, CA, US.
     * In addition, it will contain the shapes of the 
     * neighborhood and the city the location points to.
     */
    console.log(data);
});

To reverse geocode a location it is possible to just pass the latitute and longitude and use the resolved information.

breinify.temporalData(37.7609295, -122.4194155, function(data) {   
    console.log(data);
});

In addition, it is possible to request GeoJson instances. To do so, a location must be specified, together with the shapes to return.

var loc = {
  latitude: 40.7608, 
  longitude: -111.8910,
  shapeTypes: ['CITY']
};
breinify.temporalData({ location: loc }, function(data) {
    console.log(data);
});

There are examples available on runkit. Have a look at Coordinations Example and GeoJson Example.

latitude = 37.7609295
longitude = -122.4194155
shapes = ['CITY', 'NEIGHBORHOOD', 'POSTAL']
location_info = brein.temporal_data(location_latitude=latitude,
                                    location_longitude=longitude,
                                    location_shapes=shapes)
do {
   let breinTemporalData = BreinTemporalData()
                    .setLatitude(37.7609295)
                    .setLongitude(-122.4194155)
                    .addShapeTypes(["CITY", "NEIGHBORHOOD"])

   try Breinify.temporalData(breinTemporalData,
      {
      // success
      (result: BreinResult) -> Void in
      print("Api Success : result is:\n \(result)")
      })
   } catch {
     print("Error")
   }

The returned GeoJson instances can be read and used via result.getLocation().getGeoJson("CITY"). If a shape is not available, the getGeoJson(...) method returns nil.

// We are still working on this part of the documentation.
 $ curl --ipv4 -X POST https://api.breinify.com/temporaldata \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "user": { "additional": { "location": { "latitude": 37.7609295, "longitude": -122.4194155 } } } }'

The presented use-cases are also available online, utilizing the JavaScript library:

Activity

Send Activities

Sending an activity can be as simple as just sending the information that a user with the email max@sample.com just logged in or as complex as capturing the fact that the same user just bought three products and each product’s price. Furthermore, a user may not even be known when visiting or using an app or a web-site the first time, thus different types of user information may be available. In the following some sample use cases illustrate how to utilize the library to send activities.

 

Use Case: Sending a PageVisit Activity (SessionId)

When calling the activity endpoint, it is assumed that it is a ‘fire and forget’ call, i.e., the endpoint is just informed that the activity happened, but the returned information is ignored. Thus, the implementation of Breinify.activity(...) does not return any information.

Breinify.activity(new MapBuilder<String>()
        .set("sessionId", "966542c6-2399-11e7-93ae-92361f002671"), 
        "pageVisit");

Nevertheless, sometimes (e.g., for logging or debugging purposes) it may be of benefit to see the returned value. The returned value can be read by utilizing a callback function, i.e.,

/*
 * In this example the `execute(...)` method is used with a callback, 
 * it is also possible ot use the Breinify.activity() method and
 * provide a callback.
 */
new BreinActivity()
    .setUser("sessionId", "966542c6-2399-11e7-93ae-92361f002671")
    .setActivityType("pageVisit")
    .execute((result) -> {
        // do something with the result, e.g., check the status
        // result.getStatus() == 200
    }));
var sId = Breinify.UTL.cookie.get('JSESSIONID');
Breinify.activity({ 'sessionId': sId }, 'pageVisit');
// the req object may be passed, e.g., using express:
//   app.post('/login', function(req, res) { ... });
breinify.activity({ 'sessionId': req.sessionID }, 'pageVisit');
from breinify import User
s_id = 'f600757f-3df7-4289-b06c-d2e6de80b6c1'
user = User(sessionid=s_id)
brein.send_activity(user, 'pageVisit')

When calling the activity endpoint, it is assumed that it is a ‘fire and forget’ call, i.e., the endpoint is just informed that the activity happened, but the returned information is ignored. Thus, the implementation of Breinify.activity(...) does not return any information.

// create a user of interest
let breinUser = BreinUser(email: "max@sample.com")
breinUser.setSessionId("966542c6-2399-11e7-93ae-92361f002671")

// invoke activity call
do {
      try Breinify.activity(breinUser, activityType: "login")
    } catch {
      print("Error is: \(error)")
}

Nevertheless, sometimes (e.g., for logging or debugging purposes) it may be of benefit to see the returned value. The returned value can be read by utilizing a callback function, i.e.,

/*
 * This example uses the success and failure callbacks.
 */
let breinUser = BreinUser(email: "max@sample.com")
breinUser.setSessionId("966542c6-2399-11e7-93ae-92361f002671")

// invoke activity call
do {
   try Breinify.activity(breinUser, activityType: "pageVisit",
       {
          // success block
          (result: BreinResult) -> Void in
          print("Api Success : result is:\n \(result)")
       },
       {
          // failure block
          (error: NSDictionary) -> Void in
          print("Api Failure : error is:\n \(error)")
       })
   } catch {
     print("Error is: \(error)")
   }
$user = new BreinUser();
$user->setSessionId("Rg3vHJZnehYLjVg7qi3bZjzg");
$user->setEmail("max@sample.net");

$activity->setUser($user);
$activity->addActivity("pageVisit", "category-info", "description");

$result = $breinify->sendActivity($activity);
 $ curl --ipv4 -X POST https://api.breinify.com/activity \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "activity": { "type": "pageVisit" }, "user": { "sessionId": "966542c6-2399-11e7-93ae-92361f002671" } }'

 

Use Case: Sending Login Activity (Email and SessionId)

Breinify.activity(new MapBuilder<String>()
        .set("email", "max@sample.com")
        .set("sessionId", "966542c6-2399-11e7-93ae-92361f002671"), "login");
var sId = Breinify.UTL.cookie.get('JSESSIONID');
var email = 'max@sample.com'; // typically read from an input field
Breinify.activity({ 'sessionId': sId, 'email': email }, 'login');
// the req object may be passed, e.g., using express:
//   app.post('/login', function(req, res) { ... });
var user = {
    'sessionId': req.sessionID,
    'email': req.body.email
};
breinify.activity(user, 'login');
s_id = 'f600757f-3df7-4289-b06c-d2e6de80b6c1'
email = 'max@sample.com' #typically read from an input field
user = User(email=email, sessionid=s_id)
brein.send_activity(user, 'login')
// create a user of interest
let breinUser = BreinUser(email: "max@sample.com")
breinUser.setSessionId("966542c6-2399-11e7-93ae-92361f002671")

// invoke activity call
do {
      try Breinify.activity(breinUser, activityType: "login")
    } catch {
      print("Error is: \(error)")
}
$user = new BreinUser();
$user->setSessionId("Rg3vHJZnehYLjVg7qi3bZjzg");
$user->setEmail("max@sample.net");

$activity->setUser($user);
$activity->addActivity("login", "category-info", "description");

$result = $breinify->sendActivity($activity);
 $ curl --ipv4 -X POST https://api.breinify.com/activity \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "user": { "email": "max@sample.com", "sessionId": "966542c6-2399-11e7-93ae-92361f002671" } }'

 

Use Case: Sending Purchase Activity (SessionId)

new BreinActivity()
        .setUser("sessionId", "966542c6-2399-11e7-93ae-92361f002671")
        .setActivityType("checkOut")
        .setTag("productPrices", new ArrayList<Double>(134.23, 15.13, 12.99))
        .setTag("productIds", new ArrayList<String>("125689", "982361", "157029"))
        .execute();
var sId = Breinify.UTL.cookie.get('JSESSIONID');
var tags = {
    'productIds': [ '125689', '982361', '157029' ],
    'productPrices': [ 134.23, 15.13, 12.99 ]
};
Breinify.activity({ 'sessionId': sId }, 'checkOut', tags);
// the req object may be passed, e.g., using express:
//   app.post('/login', function(req, res) { ... });
var sId = Breinify.UTL.cookie.get('JSESSIONID');
var tags = {
    'productIds': [ '125689', '982361', '157029' ],
    'productPrices': [ 134.23, 15.13, 12.99 ]
};
breinify.activity({ 'sessionId': req.sessionID }, 'checkOut', tags);
s_id = 'f600757f-3df7-4289-b06c-d2e6de80b6c1'
tags = {
    'productIds': ['125689', '982361', '157029'],
    'productPrices': [134.23, 15.13, 12.99]
}
user = User(sessionid=s_id)
brein.send_activity(user, 'checkOut', tags=tags)
let breinUser = BreinUser(email: "max@sample.com")
   .setSessionId("966542c6-2399-11e7-93ae-92361f002671")

let breinActivity = BreinActivity()
   .setTag("productPrices", [134.23, 15.13, 12.99] as AnyObject)
   .setTag("productIds", ["125689", "982361", "157029"] as AnyObject)

// invoke activity call
do {
     try Breinify.activity(breinActivity, user: breinUser, activityType: "checkOut")
   } catch {
     print("Error is: \(error)")
   }
$user = new BreinUser();
$user->setSessionId("Rg3vHJZnehYLjVg7qi3bZjzg");
$user->setEmail("max@sample.net");

$activity = new BreinActivity();
$activity->setUser($user);
$activity->addActivity("pageVisit", "", "");      
$activity->setUser($user);

// tag map
$tagMap = array();
$tagMap["productId"] ="123689";
$tagMap["productPrice"] = 134.23;

$activity->setTags($tagMap);

$engine = new BreinEngine();
$result = $engine->sendActivity($activity);
 $ curl --ipv4 -X POST https://api.breinify.com/activity \
     -H "cache-control: no-cache" \
     -H "Content-Type: text/json; charset=utf-8" \
     -d '{ "apiKey": "938D-3120-64DD-413F-BB55-6573-90CE-473A", "activity": { "type": "checkOut", "tags": { "productPrices": [ 134.23, 15.13, 12.99 ], "productIds": [ "125689", "982361", "157029" ] } }, "user": { "sessionId": "966542c6-2399-11e7-93ae-92361f002671" } }'

Description

Sends an activity to the engine utilizing the API. The call is done asynchronously as a POST request. It is important that a valid API-key is configured prior to using this function.

Parameters

Type Name Description Schema
Body body
required
The body is the root of each activity send in. Each activity consist of the user (performing the activity), the activity (providing information about the activity itself) and further information like the apiKey or a signature. body

body

Name Description Schema
activity
required
activity
apiKey
required
The Breinify API key to be used. string
ipAddress
optional
The client’s requesting IP address (may be set manually, e.g., if the request was proxied through a server). string
signature
optional
Signature to authenticate a request, is only available if the the secret for the Breinify API key is configured. string
signatureType
optional
Type of encryption used for generating the signature, for example, HMAC. string
unixTimestamp
optional
The number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. integer(int64)
user
required
user

activity

Name Description Schema
description
optional
A string with further information about the activity performed. Depending on the type of the activity, some typical descriptions are:the used search query (type === ‘search’), the name of the selected product (type === ‘selectProduct’), the item added or removed from the cart (type === ‘addToCart’ OR type === ‘removeFromCart’), and the amount or monetary value items (type === ‘checkout’). string
tags
optional
Tags must be a simple object, i.e., must be null or must be an object without any functions and just using simple types (e.g., boolean, string, number, null) or an array of simple types (of the same type), e.g., [‘A’, ‘B’, ‘C’]. string
type
optional
The type of the activity collected, i.e., one of search, login, logout, addToCart, removeFromCart, checkOut, selectProduct, or other. If not specified, the default other will be used. string

user

Name Description Schema
additional
optional
Contains information known about a user, such as the time zone they are in, their local time, or information about their location additional
dateOfBirth
optional
User’s date of birth as free text. string
email
optional
User’s email, should be a full, valid email. string
firstName
optional
User’s first name. string
lastName
optional
User’s last name. string
md5Email
optional
User’s MD5 email hash value. string
twitterId
optional
User’s Twitter ID. string

additional

Name Description Schema
ipAddress
optional
An ip-address overriding the client address, e.g., if the request is performed from a server, but the actual requesting client is using a different ip. string
localDateTime
optional
User’s local time string. The format should be something like ‘Wed Oct 26 2016 13:02:06 GMT-0700 (EDT)’. string
location
optional
Coordinate data for the user, requires either a latitude/longitude pair, or a city, state, country triple. location
timezone
optional
User’s time zone, should follow the tz database naming convention. Examples include: America/New_York and Europe/Paris. string
userAgent
optional
User agent string for the user. For example, ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36’. string

location

Name Description Schema
accuracy
optional
Number representing accuracy. number(double)
city
optional
The name of the city of the location to look up string
country
optional
The name of the country of the location to look up string
latitude
optional
User’s decimal latitude coordinate. number(double)
longitude
optional
User’s decimal longitude coordinate. number(double)
state
optional
The name of the state of the location to look up string

Responses

HTTP Code Description Schema
200 If an activity sending was successful, an empty dictionary will be returned. object
default Something went wrong. Response default

Response default

Name Description Schema
code
required
The error code for general server errors is 500. integer(int32)
fields
optional
Error fields. string
message
optional
Any details about why the error occurred. string

Send Activities using Segment

To send an activity to the Breinify system using Segment, you will need to add a webhook integration to Breinify’s API on your Segment account.

Add Webhook Integration

Log in to your Segment account and navigate to the source you wish to send activities for. This may be, for example, your website.

Select your source, and navigate to the “Integrations” for your source. Search and select the “Webhooks” integration option.

Under “Connection Settings”, add a webhook with the URL as https://api.breinify.com/activity/<API-KEY>/segment, where <API-KEY> should be replaced with your API key. For example, if my API key was A6AE-3F79-C6FF-46A7-95A1-445B-0A70-1C20, I would edit my webhook integration with the webhook URL https://api.breinify.com/activity/A6AE-3F79-C6FF-46A7-95A1-445B-0A70-1C20/segment as shown below.

Segment Webhook Settings

Press save, this will take you back to the display for your Webhook integration. If you have set your API key to use a verification signature, you now need to include the secret for your API key. To do so, go to the Optional Settings and enter your API key secret in the Shared Secret field.

Be sure to check that the integration has been activated by looking for a blinking green Live icon on your Webhook integration panel.

Also ensure that the appropriate Segment snippets have been added to your website or application.

Once everything is set in place, you can view some numbers on your activities in your Breinify account dashboard.

Recommendations

Requesting a product recommendation

Description

Retrieves a list of recommended products for the user supplied in the user object of the body.

Parameters

Type Name Description Schema
Body body
required
Required fields to do a recommendation lookup. The ‘recommendation’ object is optional, and if not supplied, will default to a number of recommendations returned of 3. body

body

Name Description Schema
apiKey
required
The Breinify API key to be used. string
recommendation
optional
Parameters set for making the recommendations. recommendation
signature
optional
Signature to authenticate a request, is only available if the the secret for the Breinify API key is configured. string
signatureType
optional
Type of encryption used for generating the signature, for example, HMAC. string
user
required
user

recommendation

Name Description Schema
numRecommendations
optional
How many recommendations we should give the user. integer(int32)
recommendationCategories
optional
Category to recommend for < string > array

user

Name Description Schema
additional
optional
Contains information known about a user, such as the time zone they are in, their local time, or information about their location additional
dateOfBirth
optional
User’s date of birth as free text. string
email
optional
User’s email, should be a full, valid email. string
firstName
optional
User’s first name. string
lastName
optional
User’s last name. string
md5Email
optional
User’s MD5 email hash value. string
twitterId
optional
User’s Twitter ID. string

additional

Name Description Schema
ipAddress
optional
An ip-address overriding the client address, e.g., if the request is performed from a server, but the actual requesting client is using a different ip. string
localDateTime
optional
User’s local time string. The format should be something like ‘Wed Oct 26 2016 13:02:06 GMT-0700 (EDT)’. string
location
optional
Coordinate data for the user, requires either a latitude/longitude pair, or a city, state, country triple. location
timezone
optional
User’s time zone, should follow the tz database naming convention. Examples include: America/New_York and Europe/Paris. string
userAgent
optional
User agent string for the user. For example, ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36’. string

location

Name Description Schema
accuracy
optional
Number representing accuracy. number(double)
city
optional
The name of the city of the location to look up string
country
optional
The name of the country of the location to look up string
latitude
optional
User’s decimal latitude coordinate. number(double)
longitude
optional
User’s decimal longitude coordinate. number(double)
state
optional
The name of the state of the location to look up string

Responses

HTTP Code Description Schema
200 A list of recommended items as well as available meta information. Response 200
default Something went wrong Response default

Response 200

Name Description Schema
responseMessage
optional
Further details regarding the response result. string
responseResult
optional
List of recommended products. < object > array

Response default

Name Description Schema
code
required
The error code for general server errors is 500. integer(int32)
fields
optional
Error fields. string
message
optional
Any details about why the error occurred. string

Recommendation response

The result of a recommendation request is a json with a single value, result which is a list of item objects. For example:

{
    "result": [{
            "dataIdExternal": "123",
            "recommendationWeight": 0.9,
            "additionalData": {
                "name": "some name",
                "clientSuppliedField": "some meta data"
            }
        },
        {
            "dataIdExternal": "234",
            "recommendationWeight": 0.87,
            "additionalData": {
                "name": "another name",
                "clientSuppliedField": "some meta data"
            }
        },
        {
            "dataIdExternal": "345",
            "recommendationWeight": 0.86,
            "additionalData": {
                "name": "third item name",
                "clientSuppliedField": "some meta data"
            }
        }
    ],
    "message": "Successful execution with nothing to report."
}

Where the fields are: