Skip to content

Instantly share code, notes, and snippets.

@clausd
Last active September 7, 2016 10:12
Show Gist options
  • Save clausd/4ffe5460a551964e59b36e05e5b5b76a to your computer and use it in GitHub Desktop.
Save clausd/4ffe5460a551964e59b36e05e5b5b76a to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
#
# Mixpanel, Inc. -- http://mixpanel.com/
#
# Python API client library to consume mixpanel.com analytics data.
#
# Copyright 2010-2013 Mixpanel, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# PATCH
# * Updated the library to python 3.5
# * Api endpoint was out of date
# * Fixet json parsing. Don't know if json.loads in python 2.7 supported JSONL - the 3.5 version does not, so breaks on
# new-line separated JSON chunks
import base64
import urllib
import urllib.request as urllib2
try:
import json
except ImportError:
import simplejson as json
class Mixpanel(object):
ENDPOINT = 'https://data.mixpanel.com/api'
VERSION = '2.0'
def __init__(self, api_secret):
self.api_secret = api_secret
def request(self, methods, params, http_method='GET', format='json'):
"""
methods - List of methods to be joined, e.g. ['events', 'properties', 'values']
will give us http://mixpanel.com/api/2.0/events/properties/values/
params - Extra parameters associated with method
"""
params['format'] = format
request_url = '/'.join([self.ENDPOINT, str(self.VERSION)] + methods)
if http_method == 'GET':
data = None
request_url = request_url + '/?' + self.unicode_urlencode(params)
else:
data = self.unicode_urlencode(params)
headers = {'Authorization': 'Basic {encoded_secret}'.format(encoded_secret=base64.b64encode(self.api_secret.encode('ascii')).decode())}
request = urllib2.Request(request_url, data, headers)
response = urllib2.urlopen(request, timeout=120)
# api returns not one json object but a list of newline separated json objects
return [json.loads(j) for j in response.read().decode().splitlines()]
def unicode_urlencode(self, params):
"""
Convert lists to JSON encoded strings, and correctly handle any
unicode URL parameters.
"""
if isinstance(params, dict):
params = list(params.items())
for i, param in enumerate(params):
if isinstance(param[1], list):
params[i] = (param[0], json.dumps(param[1]),)
return urllib.parse.urlencode(
[(k, v.encode('utf-8') if isinstance(v, str) else v) for k, v in params]
)
if __name__ == '__main__':
api = Mixpanel(api_secret='YOUR SECRET')
data = api.request(['events'], {
'event': ['pages'],
'unit': 'hour',
'interval': 24,
'type': 'general'
})
print(data)
@clausd
Copy link
Author

clausd commented Sep 7, 2016

The endpoint here is actually only for raw export - for the rest of the API change to

https://mixpanel.com/api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment