Mixpanel Import API

Alex Egg,

If you have a bunch of data you want to import into mixpanel you have to use their import API which is rather hastily documented here:

https://mixpanel.com/docs/api-documentation/importing-events-older-than-5-days

For example, I had a bunch of Order events that I needed to backload into mix panel for the month of January. Using ruby client I did something like this:

$mix = Mixpanel::Tracker.new(ENV.fetch('MIXPANEL_TOKEN')
API_KEY = ENV.fetch("MIXPANEL_API_KEY")

def track_order(order)
  
  order_hash={
    'DeliveryPoint' => order.delivery_point.name,
    'DeliveryArea' => order.delivery_point.delivery_area.name,
    'total' => order.total,
    'tip' => order.gratuity_total,
    "Items purchased"=> order.items,
    'time' => order.created_at.to_i
  }

  $mix.import(API_KEY, order.user.id, 'Order', order_hash);
  
end
  
orders  = Order.where("created_at BETWEEN '2016-01-17' AND '2016-02-11 18:57:38.488478'")
orders.each do |order|
  track_order(order)
end
  

The important part is using the import method instead of the track method. There are 3 important caveats when using this import api:

  1. You must specify the time attribute as the time your event occurred in the past in unix time, e.g.: order.created_at.to_i
  2. You must use your mix panel API Key as the first function argument. This is NOT your project token which you use of for normal even tracking, it is your API Key which up until this point I didn’t use anywhere else. If you don’t use it the ruby client silently fails!
  3. You must initialize the event collection first. In my example I am importing Order events. If I never did a normal track event on Order they won’t import. If you are importing events that you have never sent before using mix panel track, just send a blank one to allow you to import.

Permalink: mixpanel-import-api

Tags:

Last edited by Alex Egg, 2016-02-11 20:48:33
View Revision History