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
- 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 - Provide the needed information, it is appropriate to enter
N/A
forCompany Name
. Please provide a short description, i.e., what you are planning to do with the key and click on theSend Request
button.
Please provide the requested information and explain what you are going to do with the key. - After a short time, you receive an email with your credentials.
- Go back to https://www.breinify.com and use the credentials to login.
Please use the username and password sent to you via email. - 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. - 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 theVerification 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 key | 938D-3120-64DD-413F-BB55-6573-90CE-473A | ||
Secret | utakxp7sm6weo5gvk7cytw== |
Type | Name | Description | Schema |
---|---|---|---|
Body | body required |
The body represents the plain object containing the further information for the request. | 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 |
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 |
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 |
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 |
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 beundefined
.{ "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.
source
- What type of source that the information was retrieved from. Current sources are: Government, United Nations, Public Information, Unknown.holiday
- The name of the holiday.types
- A list of categories the holiday falls under. Current categories are:- FEDERAL - These are official holidays recognized by a country.
- STATE - Official holidays recognized by states.
- UN_SPECIAL_DAY - These are all the international days currently observed by the United Nations. See: http://www.un.org/en/sections/observances/international-days
- CIVIC - A day that is legally recognized and celebrated as a holiday in a particular sovereign state or jurisdictional subdivision of such, e.g., a state or a province.
- CIVIL_RIGHTS - Day observing the rights of various groups of people (children, women, ethnic groups, disabled, etc).
- CULTURAL - Cultural holidays are those which celebrate or recognize the cultures of certain ethnic groups.
- EDUCATIONAL - Holidays (or vacations) in school or academics.
- HALLMARK - Holiday that is perceived to be associated with significant commercial activity. The holiday can also exist to commemorate a traditionally or historically significant event, or may even come from religious/cultural/historic backgrounds.
- HISTORIC - Days celebrated due to some historic significance or event that the holiday recognizes.
- MAJOR - Any holiday that is perceived to be widely recognized and have an impact on businesses or peoples’ behavior during the day.
- RELIGIOUS - Holidays with a religious origin, or which are associated with religious activities.
- SPECIAL_DAY - Just an otherwise special day
- OFFSET_HOLIDAY - Some holidays are generally attached to the weekend, despite when the actual holiday is. For example, if the Fourth of July is on a Sunday, it may be "Observed on” the following monday even if it was “originally on” the sunday. These holidays are recorded with the type OFFSET_HOLIDAY as, while they are not actually the holiday, they may be treated as a holiday in some cases.
Location Return Fields
The following are the fields that may be returned in the location portion of the temporal data response.
country
- The 2 letter ISO 3166 country code of the country.state
- The ISO 3166-2 state code.city
- The name of the city.granularity
- The granularity of the resolved location (city, state, or country).lon
- The longitude of the resolved location.lat
- The latitude of the resolved location.
Weather Return Fields
The following are the fields that may be returned in the weather portion of the temporal data response.
precipitation.precipitationType
- Additional, optional data that describes the type of precipitation , can be: snow, hail, sleet, rain, or none.precipitation.precipitationAmount
- Additional, optional data that describes how many milimeters of precipitation there have been in the last hour.measuredAt.lat
- The approximate latitude of the weather station the data was collected at.measuredAt.lon
- The approximate longitude of the weather station the data was collected at.lastMeasured
- Unix timestamp of when this weather data was collected.temperatureC
- Temperature in degrees Celsius.temperatureF
- Temperature in degrees Fahrenheit.temperature
- Temperature in degrees Celsius.windStrength
- The wind speed, in kilometers/hour.cloudCover
- The percentage of the sky covered in clouds.description
- A human readable description of the weather.
Time Return Fields
The following are the fields that may be returned in the time portion of the temporal data response.
localFormatIso8601
- The ISO 8601 formatted string of the current local time.timezone
- The timezone name, for example, America/Los_Angeles.localDayName
- The day of week of the current local time (Monday, Tuesday, etc).localYear
- The year value of the current local time.localMonth
- The 1-12 month value of the current local time.localDay
- The 1-31 day value of the current local time.localHour
- The 0-23 hour value of the current local time.localMinute
- The 0-59 minute value of the current local time.localSecond
- The 0-59 second value of the current local time.epochFormatIso8601
- The ISO 8601 formatted string of the current unix time.epoch
- The current unix time, the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.epochDayName
- The day of week of the current unix time (Monday, Tuesday, etc).epochYear
- The year value of the current unix time.epochMonth
- The 1-12 month value of the current unix time.epochDay
- The 1-31 day value of the current unix time.epochHour
- The 0-23 hour value of the current unix time.epochMinute
- The 0-59 minute value of the current unix time.epochSecond
- The 0-59 second value of the current unix time.
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 viaresult.getLocation().getGeoJson("CITY")
. If a shape is not available, thegetGeoJson(...)
method returnsnull
.
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 viaresult.getLocation().getGeoJson("CITY")
. If a shape is not available, thegetGeoJson(...)
method returnsnil
.
// 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 |
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 |
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 |
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 |
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 |
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 |
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.
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 |
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 |
Name | Description | Schema |
---|---|---|
numRecommendations optional |
How many recommendations we should give the user. | integer(int32) |
recommendationCategories optional |
Category to recommend for | < string > array |
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 |
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 |
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 |
Name | Description | Schema |
---|---|---|
responseMessage optional |
Further details regarding the response result. | string |
responseResult optional |
List of recommended products. | < object > array |
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:
dataIdExternal
- The client’s id for the recommended itemrecommendationWeight
- The recommender’s weight for the itemadditionalData
- Additional data supplied by the client