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

Introduction

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 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-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
 */

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

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.

{{snippet-php-language-integrate}}

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/breinify-api/{version}/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.

{{snippet-php-language-config}}

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).

 

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": [ "NATIONAL_FEDERAL" ],
        "source": "Government",
        "holiday": "Christmas Day (observed on December 26)"
    }, {
        "types": [ "STATE_FEDERAL" ],
        "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
    },
    "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": []
}

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

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)")
   }

 

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)”) }
“`

{{snippet-php-language-geocoding}}

 

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.

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)")
   }

{{snippet-php-language-pagevisit-activity}}

 

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)")
}

{{snippet-php-language-login-activity}}

 

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)")
   }

{{snippet-php-language-purchase-activity}}

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 performedfrom 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/segmentactivity. In the “Headers” for the hook, set your API key with an apiKey header.

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.