Unlock the hidden power of your apps.

Try Zapier Free!

Introducing Code Steps for Zaps: Calculate, Convert, Manipulate Data and More

Bryan Helmig
Bryan Helmig / February 4, 2016

Connect a few apps with Zapier, and you can build just about anything you want without code. But there are still times when you'll need code—perhaps to calculate a value, connect to a new API, manipulate text, and more.

Zapier's new Code integration—one of the features added along with our new Multi-step Zaps—lets you write simple code to do even more with your Zaps.

You don't even need to be a code wizard. We'll show you how to start using code in less than 5 minutes, even if you've never written a line of code before! And if you're a developer, you can use code in Zapier to make even more powerful apps.

Here's how.

Oh, and before you get confused by the JavaScript vs. Python vs. whatever other programming languages exist debate, just remember they all serve the same purpose: to tell the computer what you want it to do. So we'll just pick one of the easiest for the sake of these examples: Python!

Use Zapier's Code Integration to:

Getting Started

Multi-step Zaps

Zapier integrations used to only connect any two apps together. When one thing happens here, Zapier would make something else happen there.

But now, with our new Multi-step Zaps, you can do whatever you want when something happens. That gives you a perfect spot to add code to your Zaps. Whenever something happens—someone purchases an item from your store, fills out your form, sends you an email, or anything else—you can first have your Zap run a Code step to calculate or manipulate the data, and then send that along to other apps.

That way, you can fix international date formats, calculate order totals, format text, and much more. It'll make your Zapier integrations much more powerful and useful, and help you do even more work automatically.

So let's get started.

Basic Math

Let's say you want to do something simple, like calculate a total price after tax—it's straightforward, but involves a little bit of math. That isn't a problem at all, since programming languages are great at math!

First, make a Zap that connects to the app that has the price info, then add the Code action and set the "Input" section to provide both a total and a tax_rate_percent for use in our code:

Input section for Zapier Code

Now that the input data is defined, we can write the code to work with that data and return output data—aka the total:

# we can only do math on numbers (int or float in python)
original_total = float(input['total'])
tax_rate = float(input['tax_rate_percent']) / 100
# now let's calculate the value!
tax_owed = original_total * tax_rate
# simply add it up...
after_tax_total = original_total + tax_owed
# ...and return it!
return {'after_tax_total': round(after_tax_total, 2)}

Now any step you add after this Code step can use a field called "After Tax Total", which you can insert from the + box as you would any other field. For example, you might do this in a follow-up step:

Using a Code value

Remember, too, that the names of the values are completely up to you. You can also return as few or as many values as you like—so feel free to be creative!

But wait, there's more! You aren't limited to math or other simple "input to output" conversions with Zapier's Code integration. You can also pull in data from an API or service Zapier doesn't directly support, using requests.

Basic API Usage

Let's say we're selling umbrellas in our online store—wouldn't it be cool to include the weather for the person who purchased an umbrella in a followup email? We could say something like "Thanks for buying an umbrella - looks like you might need it this Friday! ;-)". All you'll need to know is what the weather will be this Friday.

The first step in Zapier is to add the required data—a postal code to look up the weather in their area—to the "Input" field like this:

add postal code to Code

Now we can use the zip code in an API call to OpenWeatherMap with an included library called requests:

# let's get our variables ready to make an API call
zc = input['zip_code']
url = 'http://api.openweathermap.org/data/2.5/weather?zip=' + zc + ',us'
# let's make the actual API call...
response = requests.get(url)
response.raise_for_status() # optional but good practice in case the call fails!
# ..and let's return the JSON for use in the next step
return response.json()

Then, just like the basic math example, we can use the weather report in future steps—so you could add the weather to an email template, or add a filter to your Zap to only send an email if it's going to rain.

You could even write more specialized code to read the response information and generate cute messages for use in future steps—or anything else you could dream up!

Basic Information Storage

Let's say we want to do something special for our 1000th purchase—maybe we'll setup a zap that sends the customer an email with a 100% off coupon for their next order!

That would be a little tricky, because we need to keep track of the number of items sold—which means we need something special like long term memory (or state, as programmers might call it).

Don't worry! Zapier's Code integration has some cool tricks up its sleeve. We can use a built-in tool or library called StoreClient to save a record of each purchase. Here is an example:

store = StoreClient('any secret')

count = store.get('items sold') or 0
count += 1
store.set('items sold', count)

return {'items sold count': count}

Now all future steps in your Zap have the helpful value "Items Sold Count". Then, you can use a filter to restrict the zap from running when it isn't equal to 1000, like this:

Zapier filter

Or you could also use the count in future templates, like this:

StoreClient in template

You can store any type of data you like—numbers, strings, or even complex data structures like lists or dictionaries—as long as it is something you could list in JSON. And if you are feeling extra adventurous, you can share your secret across zaps (or even across Zapier accounts) to coordinate in style!

Speed Round!

Now that you've got the basics of using Code in Zapier, let's look at a handful of quick examples—which will hopefully get your mind racing with more ideas of how you could use code in Zaps.

Ready? Let's go!

Extract Email Addresses

Let's say you have a big blob of text in input['textBlob'], perhaps from the body of an email message, and you just want to grab the first email address in there…

import re
emails = re.findall(r'[\w._-]+@[\w._-]+\.[\w._-]+', input['textBlob'])
return {
    'firstEmail': emails[0] if emails else None

Convert Date Formats

Let's say you have a date in input['someDate'] and it looks like "Jun 1 2005", but you need it to look like "01/06/2005" instead (day/month/year)…

from datetime import datetime
some_date = datetime.strptime(input['someDate'], '%b %d %Y')
return {
    'newDate': some_date.strftime('%d/%m/%Y')

Capitalize a Name

Let's say you have a name in input['name'] and it needs to be capitalized…

return {
    'capName': input['name'].title()

Split a Name

Let's say you have a first and last name in your input['fullName'] and it needs to be split up into first name and last name fields…

if ' ' in input['fullName']:
    first, last = input['fullName'].split(' ', 1)
    first, last = input['fullName'], None # fallback
return {
    'firstName': first,
    'lastName': last

Combine Names

Let's say you have a first and last name in your input['firstName'] and input['lastName'], but need it to be combined into one full name…

return {
    'fullName': input['firstName'] + ' ' + input['lastName']

Code Anything You Want in Zapier

Once you get started with Zapier Code, you'll find that you have more control over your apps than ever before. Zapier users have already used Code to create Slack bots, games, and so much more!

Want to see even more examples of how to use Code in Zapier, with sample code to do currency conversions, bulk operations, and more? Go visit our Code (Python) documentation or Code (JavaScript) documentation.

Then, share what you've made with Zapier Code in the comments below!

Photo of Lawrence Watkins

“Zapier helps me build processes and automation into my business like a programmer without having to learn to code.”

Lawrence Watkins, co-founder of Great Black Speakers

Try Zapier Today
Wufoo, Google Sheets & Mailchimp

Build workflows with your apps.

Try Zapier Free

Connect apps. Automate tasks. Get more done.

Try Zapier Free
Load Comments...

Comments powered by Disqus


Take the Work out of Workflow

Zapier is the easiest way to automate powerful workflows with more than 750 apps.