How to Use Python in Zapier With Code by Zapier

Code by Zapier lets you run a short Python script inside a Zap when built-in tools are not enough. Here is how inputs and outputs work, with examples you can adapt and the limits to plan around.

To use Python in Zapier, add a Code by Zapier step, choose Run Python, map the values you need into the Input Data fields, and write a short script that reads them from the input_data dictionary and returns a dictionary called output. Each key you return becomes a field you can use in later steps. Zapier python steps are best for small pieces of logic that Formatter, Filters and Paths can’t express cleanly.

This guide explains how inputs and outputs work, shows a few patterns worth copying, and covers the limits and debugging habits that save you from fragile code steps.

When to use a Zapier Python step

A code step is powerful, but every line of code is something another person has to understand later. Use it when:

  • One value depends on several fields and conditions at once.
  • You need to parse a structure Formatter can’t, such as a JSON string inside a field.
  • You need to call an API with a simple request and use part of the response.
  • A chain of Formatter steps has grown so long that one short script would be clearer.

Don’t use it when a built-in tool already does the job. Lowercasing an email or reformatting a date belongs in Formatter, where anyone can read it.

How to add a Python code step

  1. In the Zap editor, add an action step and choose Code by Zapier.
  2. Choose the Run Python event.
  3. In Input Data, add one field per value you need. Give each a simple name, such as email or amount, and map a value from an earlier step.
  4. Write your script in the Code box.
  5. Test the step and check the output fields.
  6. Map those output fields into later steps.

Code can also be used as a trigger, but most businesses use it as an action in the middle of a Zap.

How input_data and output work

Two rules cover most of what you need to know.

Inputs arrive as text. Everything in input_data is a string, even if it looks like a number. Convert values before doing math, and handle empty values, because a missing field may arrive as an empty string or not at all.

Outputs are a dictionary. Assign a dictionary to output (or return one). Keep the keys simple and the values to text, numbers or true/false, so later steps can map them easily.

A minimal example that builds a greeting name with a safe fallback:

first = (input_data.get('first_name') or '').strip()

if first:
    greeting = first.title()
else:
    greeting = 'there'

output = {'greeting_name': greeting}

Note the use of input_data.get() instead of input_data['first_name']. If the key is missing, get() returns None rather than raising an error, and the or '' turns that into an empty string.

Pattern 1: calculate a value from several fields

A typical use is computing a lead score or an order category from several inputs. Here is a simple lead score using company size, budget and the type of help requested:

def to_int(value):
    try:
        return int(float(str(value).replace(',', '').strip()))
    except ValueError:
        return 0

size = to_int(input_data.get('company_size'))
budget = to_int(input_data.get('budget'))
need = (input_data.get('need') or '').lower()

score = 0
if size >= 50:
    score += 2
if budget >= 10000:
    score += 2
if 'automation' in need or 'integration' in need:
    score += 1

route = 'sales' if score >= 3 else 'nurture'

output = {'score': score, 'route': route}

The route value is easy to branch on. A Paths step with two simple rules (“route exactly matches sales”, “route exactly matches nurture”) is far easier to read than five overlapping conditions. Our guide to building branching logic with Zapier Paths covers that next step.

Pattern 2: parse JSON hidden in a text field

Some apps send structured data as a single text field. Python’s built-in json module turns it into something you can work with:

import json

raw = input_data.get('payload') or '{}'

try:
    data = json.loads(raw)
except json.JSONDecodeError:
    data = {}

items = data.get('items', [])
skus = [str(item.get('sku', '')) for item in items]

output = {
    'customer_email': data.get('customer', {}).get('email', ''),
    'item_count': len(items),
    'skus': ', '.join(skus),
}

Joining a list into one comma-separated value keeps the output easy to map. If the downstream app needs real line items, combine this with Formatter’s line-item utilities.

Pattern 3: call a simple API

Zapier’s documentation says Python code steps include the standard library and the requests library. That lets you make a simple HTTP call:

import requests

email = (input_data.get('email') or '').strip().lower()

response = requests.get(
    'https://api.example.com/v1/lookup',
    params={'email': email},
    timeout=10,
)

if response.ok:
    result = response.json()
    output = {'found': True, 'account_id': result.get('id', '')}
else:
    output = {'found': False, 'status': response.status_code}

Keep two cautions in mind. First, Zapier warns against typing API keys in plain text in code steps, so for authenticated APIs used often, a private integration built on Zapier’s developer platform is safer. Second, if all you need is one request with no logic around it, a webhook action is simpler; see our guide to sending and catching webhooks.

Python or JavaScript in Zapier?

Code by Zapier offers both Run Python and Run JavaScript. Neither is better in general; pick the one your team can read. Zapier python steps suit people who already use Python for data work, and the syntax for parsing text and working with dictionaries is easy to follow. JavaScript steps suit teams that already maintain websites or front-end code.

The structure is similar either way: map Input Data, read the values in code, return an output object. The practical differences are in details, such as how you make HTTP requests and how the input object is named, so check the matching examples in Zapier’s help center for the language you choose.

Whichever you pick, stay consistent across your account. A business with half its code steps in each language doubles the knowledge needed to maintain them.

Limits to plan around

  • No package installs. You can’t add libraries with pip, so stick to the standard library and requests.
  • Run time and memory are limited, and the limits depend on your plan. Check Zapier’s current help center pages before writing anything that loops over large data or waits on slow APIs.
  • No saved state between runs. Each run starts fresh. If you need to remember something, store it in an app or a Zapier table.
  • Inputs are strings. Always convert and validate.
  • Code is visible to anyone who can edit the Zap, which is another reason to keep secrets out of it.

How to debug a Python code step

When a code step fails, Zap history shows the error message and the input it received. Work through these checks:

  1. Read the error line. Errors such as KeyError or ValueError point at a missing field or a failed conversion.
  2. Check the inputs. Compare the Input Data in the failed run to your test data. Often a field was empty or formatted differently.
  3. Make sure you set output. A script that never assigns output or returns a dictionary will fail.
  4. Return debug fields while testing. Add keys such as debug_raw to your output so you can see intermediate values in the test result. Remove them once it works.
  5. Test with ugly data. Blank fields, commas in numbers, accented names and very long text expose most bugs.

AI assistants can help you write or explain a snippet, and Zapier itself suggests using a trusted assistant to learn and debug code. Still, read every line before you publish, and test with real records.

Keep code steps maintainable

  • Put a comment at the top saying what the step does and which later steps use its output.
  • Use clear input names that match the source field.
  • Keep each code step to one job. Two short steps are easier to debug than one long one.
  • Store a copy of important scripts in your team’s documentation, along with the Zap name.

When to hand the code to a developer

A short script is fine for a business owner or ops lead to maintain. When code steps start handling payments, authentication, retries or large batches, the risk of silent failure grows. That is the point to bring in an experienced Zapier developer who can decide whether the logic belongs in a code step, a private integration or a small external service. You can also describe the workflow to us at support@growthscribe.com.

FAQ

Can I install Python packages in Code by Zapier?

No. You can’t install packages with pip. Zapier’s documentation says Python code steps include the standard library and the requests library, so design your code around those.

How do I pass data from earlier steps into my Python code?

Add fields in the Input Data section of the code step and map values from earlier steps into them. Inside your code, each field is available as a key in the input_data dictionary, and every value arrives as text.

How do I return data from a Python code step?

Assign a dictionary to a variable named output, or return a dictionary. Each key becomes a field you can map in later steps. Zapier’s docs also describe returning a list of dictionaries; check how that behaves in your Zap before relying on it.

Is it safe to put API keys in a code step?

Zapier advises against typing sensitive values like API keys in plain text in code steps. For repeated authenticated API calls, a private integration on Zapier’s developer platform is the safer route.

Kartik Ahuja

Kartik Ahuja

Kartik is a 3x Founder, CEO & CFO. He has helped companies grow massively with his fine-tuned and custom marketing strategies.

Kartik specializes in scalable marketing systems, startup growth, and financial strategy. He has helped businesses acquire customers, optimize funnels, and maximize profitability using high-ROI frameworks.

His expertise spans technology, finance, and business scaling, with a strong focus on growth strategies for startups and emerging brands.

Passionate about investing, financial models, and efficient global travel, his insights have been featured in BBC, Bloomberg, Yahoo, DailyMail, Vice, American Express, GoDaddy, and more.

Kartik Ahuja, founder of GrowthScribe

Have a challenge in mind?

Don’t overthink it. Just share what you’re building or stuck on — I'll take it from there.

LEADS --> Contact Form (Focused)
eg: grow my Instagram / fix my website / make a logo