Skip to main content

Python bindings for Sift Science's API

Project description

Sift Python Bindings

Bindings for Sift's APIs -- including the Events, Labels, and Score APIs.

Installation

Set up a virtual environment with virtualenv (otherwise you will need to make the pip calls as sudo):

virtualenv venv
source venv/bin/activate

Get the latest released package from pip:

Python 2:

pip install Sift

Python 3:

pip3 install Sift

or install newest source directly from GitHub:

Python 2:

pip install git+https://github.com/SiftScience/sift-python

Python 3:

pip3 install git+https://github.com/SiftScience/sift-python

Documentation

Please see here for the most up-to-date documentation.

Changelog

Please see the CHANGELOG for a history of all changes.

Note, that in v2.0.0, the API semantics were changed to raise an exception in the case of error to be more pythonic. Client code will need to be updated to catch sift.client.ApiException exceptions.

Usage

Here's an example:

import json
import sift.client

client = sift.Client(api_key='<your API key here>', account_id='<your account ID here>')

# User ID's may only contain a-z, A-Z, 0-9, =, ., -, _, +, @, :, &, ^, %, !, $
user_id = "23056"

# Track a transaction event -- note this is a blocking call
properties = {
    "$user_id": user_id,
    "$user_email": "buyer@gmail.com",
    "$seller_user_id": "2371",
    "seller_user_email": "seller@gmail.com",
    "$transaction_id": "573050",
    "$payment_method": {
        "$payment_type": "$credit_card",
        "$payment_gateway": "$braintree",
        "$card_bin": "542486",
        "$card_last4": "4444"
    },
    "$currency_code": "USD",
    "$amount": 15230000,
}

try:
    response = client.track("$transaction", properties)
    if response.is_ok():
        print "Successfully tracked event"
except sift.client.ApiException:
    # request failed
    pass

# Track a transaсtion event and receive a score with percentiles in response (sync flow).
# Note: `return_score` or `return_workflow_status` must be set `True`.
properties = {
    "$user_id": user_id,
    "$user_email": "buyer@gmail.com",
    "$seller_user_id": "2371",
    "seller_user_email": "seller@gmail.com",
    "$transaction_id": "573050",
    "$payment_method": {
        "$payment_type": "$credit_card",
        "$payment_gateway": "$braintree",
        "$card_bin": "542486",
        "$card_last4": "4444"
    },
    "$currency_code": "USD",
    "$amount": 15230000,
}

try:
    response = client.track("$transaction", properties, return_score=True, include_score_percentiles=True, abuse_types=["promotion_abuse", "content_abuse", "payment_abuse"])
    if response.is_ok():
        score_response = response.body["score_response"]
        print(score_response)
except sift.client.ApiException:
    # request failed
    pass

# To include `warnings` field to Events API response via calling `track()` method, set it by the `include_warnings` param:
try:
    response = client.track("$transaction", properties, include_warnings=True)
    # ...
except sift.client.ApiException:
    # request failed
    pass

# Request a score for the user with user_id 23056
try:
    response = client.score(user_id)
    s = json.dumps(response.body)
    print s

except sift.client.ApiException:
    # request failed
    pass

try:
    # Label the user with user_id 23056 as Bad with all optional fields
    response = client.label(user_id, {
        "$is_bad": True,
        "$abuse_type": "payment_abuse",
        "$description": "Chargeback issued",
        "$source": "Manual Review",
        "$analyst": "analyst.name@your_domain.com"
    })
except sift.client.ApiException:
    # request failed
    pass

# Remove a label from a user with user_id 23056
try:
    response = client.unlabel(user_id, abuse_type='content_abuse')
except sift.client.ApiException:
    # request failed
    pass

# Get the status of a workflow run
try:
    response = client.get_workflow_status('my_run_id')
except sift.client.ApiException:
    # request failed
    pass

# Get the latest decisions for a user
try:
    response = client.get_user_decisions('example_user')
except sift.client.ApiException:
    # request failed
    pass

# Get the latest decisions for an order
try:
    response = client.get_order_decisions('example_order')
except sift.client.ApiException:
    # request failed
    pass

# Get the latest decisions for a session
try:
    response = client.get_session_decisions('example_user', 'example_session')
except sift.client.ApiException:
    # request failed
    pass

# Get the latest decisions for a piece of content
try:
    response = client.get_content_decisions('example_user', 'example_content')
except sift.client.ApiException:
    # request failed
    pass

# The send call triggers the generation of a OTP code that is stored by Sift and email/sms the code to the user.
send_properties = {
	"$user_id": "billy_jones_301",
	"$send_to": "billy_jones_301@gmail.com",
	"$verification_type": "$email",
	"$brand_name": "MyTopBrand",
	"$language": "en",
	"$site_country": "IN",
	"$event": {
		"$session_id": "SOME_SESSION_ID",
		"$verified_event": "$login",
		"$verified_entity_id": "SOME_SESSION_ID",
		"$reason": "$automated_rule",
		"$ip": "192.168.1.1",
		"$browser": {
			"$user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
		}
	}
}
try:
    response = client.verification_send(send_properties)
except sift.client.ApiException:
    # request failed
    pass

# The resend call generates a new OTP and sends it to the original recipient with the same settings.
resend_properties = {
	"$user_id": "billy_jones_301",
	"$verified_event": "$login",
	"$verified_entity_id": "SOME_SESSION_ID"
}
try:
    response = client.verification_resend(resend_properties)
except sift.client.ApiException:
    # request failed
    pass

# The check call is used for verifying the OTP provided by the end user to Sift.
check_properties = {
	"$user_id": "billy_jones_301",
    "$code": 123456,
	"$verified_event": "$login",
	"$verified_entity_id": "SOME_SESSION_ID"
}
try:
    response = client.verification_check(check_properties)
except sift.client.ApiException:
    # request failed
    pass

Testing

Before submitting a change, make sure the following commands run without errors from the root dir of the repository:

python -m unittest discover
python3 -m unittest discover

Integration testing app

For testing the app with real calls it is possible to run the integration testing app, it makes calls to almost all our public endpoints to make sure the library integrates well. At the moment, the app is run on every merge to master

How to run it locally

  1. Add env variable ACCOUNT_ID with the valid account id
  2. Add env variable API_KEY with the valid Api Key associated from the account
  3. Run the following under the project root folder
# uninstall the lib from the local env (if it was installed)
pip uninstall sift

# install the lib from the local source code
pip install ../sift-python

# run the app
python test_integration_app/main.py

5.6.0 2024-05-31

  • Added support for a warnings value in the fields query parameter

5.5.1 2024-02-22

  • Support for Python 3.12

5.5.0 2023-10-03

  • Score percentiles for Score API

5.4.0 2023-07-26

  • Support for Verification API

5.3.0 2023-02-03

  • Added support for score_percentiles

5.2.0 2022-11-07

  • Update PSP Merchant Management API

5.1.0 2022-06-22

  • Added return_route_info query parameter
  • Fixed decimal amount json serialization bug

5.0.2 2022-01-24

  • Fix usage of urllib for Python 2.7

5.0.1 2019-03-07

  • Update metadata in setup.py

5.0.0 2019-01-08

  • Add connection pooling

INCOMPATIBLE CHANGES INTRODUCED IN 5.0.0:

  • Removed support for Python 2.6

  • Fix url encoding for all endpoints

    Previously, encoding user ids in URLs was inconsistent between endpoints, encoded for some endpoints, unencoded for others. Additionally, when encoded in the URL path, forward slashes weren't encoded. Callers with workarounds for this bug must remove these workarounds when upgrading to 5.0.0.

  • Improved error handling

    Previously, illegal arguments passed to methods like Client.track() and failed calls resulting from server-side errors both raised ApiExceptions. Illegal arguments validated in the client now raise either TypeErrors or ValueErrors. Server-side errors still raise ApiExceptions, and ApiException has been augmented with metadata for handling the error.

4.3.0.0 2018-07-31

  • Add support for rescore_user and get_user_score APIs

4.2.0.0 2018-07-05

  • Add new query parameter force_workflow_run

4.1.0.0 2018-06-01

  • Add get session level decisions in Get Decisions APIs.

4.0.1 2018-04-06

  • Updated documentation in CHANGES.md and README.md

4.0.0.0 2018-03-30

  • Adds support for Sift Science API Version 205, including new $create_content and $update_content formats
  • V205 APIs are now called -- this is an incompatible change
    • Use version = '204' when constructing the Client to call the previous API version
  • Adds support for content decisions to Decisions API

INCOMPATIBLE CHANGES INTRODUCED IN API V205:

  • $create_content and $update_content have significantly changed, and the old format will be rejected
  • $send_message and $submit_review events are no longer valid
  • V205 improves server-side event data validation. In V204 and earlier, server-side validation accepted some events that did not conform to the published APIs in our developer documentation. V205 does not modify existing event APIs other than those mentioned above, but may reject invalid event data that were previously accepted. Please test your integration on V205 in sandbox before using in production.

3.2.0.0 2018-02-12

  • Add session level decisions in Apply Decisions APIs.
  • Add support for filtering get decisions by entity type session.

3.1.0.0 2017-01-17

  • Adds support for Get, Apply Decisions APIs

3.0.0.0 2016-07-19

  • Adds support for v204 of Sift Science's APIs
  • Adds Workflow Status API, User Decisions API, Order Decisions API
  • V204 APIs are now called by default -- this is an incompatible change (use version='203' to call the previous API version)

2.0.1.0 (2016-07-07)

  • Fixes bug parsing chunked HTTP responses

2.0.0.0 (2016-06-21)

  • Major version bump; client APIs have changed to raise exceptions in the case of API errors to be more Pythonic

1.1.2.1 (2015-05-18)

  • Added Python 2.6 compatibility
  • Added Travis CI
  • Minor bug fixes

1.1.2.0 (2015-02-04)

  • Added Unlabel functionaly
  • Minor bug fixes.

1.1.1.0 (2014-09-3)

  • Added timeout parameter to track, score, and label functions.

1.1.0.0 (2014-08-25)

  • Added Module-scoped API key.
  • Minor documentation updates.

0.2.0 (2014-08-20)

  • Added Label and Score functions.
  • Added Python 3 compatibility.

0.1.1 (2014-02-21)

  • Bump default API version to v203.

0.1.0 (2013-01-08)

  • Just the Python REST client itself.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Sift-5.6.0.tar.gz (13.8 kB view details)

Uploaded Source

File details

Details for the file Sift-5.6.0.tar.gz.

File metadata

  • Download URL: Sift-5.6.0.tar.gz
  • Upload date:
  • Size: 13.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.10.12

File hashes

Hashes for Sift-5.6.0.tar.gz
Algorithm Hash digest
SHA256 a06176d7be543b20c1c0b104c423c5708c4a1cb4cc8e0986dd2c61e3422a64a9
MD5 8ee68ec08a8733b0131fcf915a69acce
BLAKE2b-256 cf51118d67a186d831f2bd048aae2aa594f6526ed08f526182d0fdce1c163a51

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page