Last modified January 14, 2021 by Shelly Wolfe

Set user properties via API

The Swrve Events API enables you to send Swrve information that you know about your users, from outside the app, via the User API call. Use the User API call to set the value of custom user properties by making an API call to <app_id>.api.swrve.com (or <app_id>.eu-api.swrve.com for EU-configured apps).

This is useful if you want to send data when the user is not in the app, or to set a property that you know about your user from one of your other services. This method also enables you to manually put a user into a particular segment (the segment must already be set up) or set multiple user properties at the same time.

This article references Swrve’s URLs for all data and content stored in both our US and EU data centers. Click the relevant tab based on your app configuration. For more information, see How do I configure the Swrve SDK for EU data storage?

Prerequisites

This guide presents an area of advanced analysis, so ensure you have the following:

  • Fully instrumented Swrve into your app
  • The ID of the user(s)
  • The name and value of the user properties
  • Your app_id and api_key

An easy to way to set user properties for a group of users is with a simple script that reads a set of user IDs and properties from a CSV file and makes a series of API calls to Swrve. For example:

userID,gender,location
user123,F,England
user456,M,Canada
user789,F,France

An example Python script is provided below. The User API call is made with a simple HTTP POST request. This script requires the name of the CSV file as a command line parameter and for that CSV file to have a column with the name ‘userID’.

#!/usr/bin/env python

import argparse
import csv
import gzip
import logging
import requests

def check_headers(headers):
    if headers[0] != "swrve_user_id":
        print("first header should be swrve_user_id")
        return 1
    for i, y in enumerate(headers):
        headers[i] = str(y)
    return 0

def process_file(file_name, eu, app_id, api_key, header):
    API_URL_ROOT = 'http://%i.eu-api.swrve.com/1/user' % (app_id)
    if eu == False:
        API_URL_ROOT = 'http://%i.api.swrve.com/1/user' % (app_id)
    conn = requests.Session()
    num_rows_processed = 0

    if file_name.endswith('.gz') != True and file_name.endswith('.csv') != True:
        print('Only gzip and csv files supported')
        raise RuntimeError

    f = gzip.open(file_name) if file_name.endswith('.gz') else open(file_name)
    reader = csv.reader(f)

    print('Processing file %s' % file_name)
    for row in reader:
        if len(row) != len(header):
            print('Row with incorrect number of columns. Got %i but expected %i. Row %s' % (len(header), len(row), str(row)))
            raise RuntimeError

        payload = {
            'api_key': api_key,
            'user_initiated': 'false',
            'user': row[0]
        }
        for i in xrange(1, len(header)):
            payload[header[i]] = row[i]

        try:
            r = conn.post(API_URL_ROOT, params=payload)
            r.raise_for_status()
        except Exception, e:
            print('Error sending sending user property. Error: %s' % (str(e)))
            raise RuntimeError

        num_rows_processed += 1
        if num_rows_processed % 1000 == 0:
            print('%i processed' % num_rows_processed)

    print('Processing complete. %s users processed.' % num_rows_processed)

def upload_properties(eu, app_id, api_key, header, filename):
    header = header.split(',')
    num = check_headers(header)
    if num != 0:
        return num

    process_file(filename, eu, app_id, api_key, header)

    return 0


def str2bool(v):
    return v.lower() in ("yes", "y", "true", "1")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.register('type', 'bool', str2bool)
    parser.add_argument('--eu',        required=True, type='bool')
    parser.add_argument('--app_id',    required=True, type=int)
    parser.add_argument('--api_key',   required=True)
    parser.add_argument('--header',    required=True)
    parser.add_argument('--filename',  required=True)
    args = parser.parse_args()

    exit(upload_properties(args.eu, args.app_id, args.api_key, args.header, args.filename))

Testing

To confirm that your user properties were set correctly, include a QA user in your user properties file and then check for the user properties in the QA log.

Because the user has not triggered this user update themselves and are not necessarily active, you don’t want the user property event to affect the DAU or MAU figures. To prevent this, include an additional flag called user_initiated that is set to false, as shown in the script above.

The Swrve User API call is part of the Swrve Events API. For more information, see the Swrve Events API guide.