To integrate Replit with LeadSquared, obtain your Access Key and Secret Key from the LeadSquared API settings, store both in Replit Secrets (lock icon π), and use the LeadSquared REST API from an Express or Flask server to capture leads, log activities, retrieve lead scores, and trigger automation rules for your sales pipeline.
Why Integrate LeadSquared with Replit?
LeadSquared is built for sales-execution teams in high-velocity verticals like education, healthcare, and financial services β industries where lead volume is high and rapid follow-up is critical to conversion. The LeadSquared API lets your Replit backend act as a lead capture pipeline: when a prospect fills out a form, registers for a webinar, or downloads an asset from your website, your server immediately creates a lead in LeadSquared with all relevant attributes, triggers the appropriate automation rule, and logs the originating activity.
Lead scoring is one of LeadSquared's strongest features. By logging detailed activity data through the API (page visits, content downloads, email opens, meeting attendance), you give the scoring engine the signals it needs to rank leads accurately. This is especially valuable when you are pulling activity data from external systems β your Replit server acts as the bridge that converts events from other tools into LeadSquared activity logs, enriching lead scores automatically.
LeadSquared's authentication model is notably simpler than OAuth-based CRMs: every API request includes your Access Key and Secret Key as query parameters. This means there is no token refresh logic to implement and no redirect flows to manage β just straightforward HMAC-signed or plain key-based requests. The tradeoff is that your keys must be protected carefully since they do not expire, making Replit Secrets (lock icon π) the essential protection layer.
Integration method
Replit connects to LeadSquared via the LeadSquared REST API using an Access Key and Secret Key stored in Replit Secrets. Your Express or Flask backend can capture leads from web forms, log sales activities, retrieve and update lead scores, and trigger LeadSquared automation rules. LeadSquared's API uses simple query-string authentication, making it straightforward to implement with standard HTTP clients.
Prerequisites
- A LeadSquared account with API access enabled (check Settings > API & Webhooks)
- Access Key and Secret Key from the LeadSquared API settings page
- A Replit account with a Node.js or Python Repl created
- Basic knowledge of REST APIs, HTTP POST requests, and JSON
- Familiarity with Express (Node.js) or Flask (Python) for server-side routing
Step-by-step guide
Obtain your LeadSquared API credentials
Obtain your LeadSquared API credentials
Log in to your LeadSquared account and go to Settings (gear icon in the top right) > API & Webhooks > API Access. LeadSquared will display your Access Key and Secret Key. If you do not see this menu, your account may not have API access enabled β contact your LeadSquared account manager or check your plan includes API access. Copy both keys immediately. The Access Key is your public identifier (similar to a username), while the Secret Key is the sensitive value (similar to a password) β both are required for every API call. You will also need your LeadSquared host URL, which is the base URL of your LeadSquared account (e.g., https://api.leadsquared.com for US accounts, or a region-specific URL for other data centers). Check the API documentation link in your LeadSquared settings to confirm the correct base URL for your data center. The full API base URL format is typically https://api.leadsquared.com/v2 for US accounts. Note that LeadSquared's API uses these credentials as query parameters on every request (accessKey and secretKey), not in an Authorization header β this is an older but valid authentication pattern. Store LEADSQUARED_ACCESS_KEY, LEADSQUARED_SECRET_KEY, and LEADSQUARED_HOST in Replit Secrets.
1# Python β verify LeadSquared connection (verify.py)2import requests3import os45ACCESS_KEY = os.environ['LEADSQUARED_ACCESS_KEY']6SECRET_KEY = os.environ['LEADSQUARED_SECRET_KEY']7HOST = os.environ.get('LEADSQUARED_HOST', 'https://api.leadsquared.com')89# Test connection by fetching a single lead (lightweight request)10params = {11 'accessKey': ACCESS_KEY,12 'secretKey': SECRET_KEY13}14response = requests.get(15 f'{HOST}/v2/LeadManagement.svc/Leads.GetByPaging',16 params={**params, 'start': 0, 'size': 1}17)18if response.status_code == 200:19 data = response.json()20 print(f'Connection successful. Status: {data.get("Status")}')21else:22 print(f'Connection failed: {response.status_code} - {response.text}')Pro tip: LeadSquared has different API base URLs for different regions (US, India, EU, AU). Using the wrong base URL will result in 404 errors even with valid credentials. Confirm your region's API endpoint from your LeadSquared account settings.
Expected result: The verification script returns 'Connection successful' and a Status of 'Success'. Your credentials are working and the LeadSquared host URL is correct.
Store credentials in Replit Secrets
Store credentials in Replit Secrets
Open the Replit Secrets panel by clicking the lock icon (π) in the left sidebar. Add three secrets: LEADSQUARED_ACCESS_KEY (your access key from the API settings), LEADSQUARED_SECRET_KEY (your secret key β this is sensitive, treat it like a password), and LEADSQUARED_HOST (your account's API base URL, e.g., https://api.leadsquared.com). Because LeadSquared passes credentials as URL query parameters, they could appear in server logs if not handled carefully. In your application code, always construct the credentials object from environment variables and append them to the request URL programmatically β never log the full request URL including credentials to the console. Replit Secrets are AES-256 encrypted and only accessible to your Repl at runtime. Install required packages: for Python add requests and flask to requirements.txt; for Node.js run npm install express axios in the Shell.
1// Node.js β Replit Secrets verification (check-secrets.js)2const required = ['LEADSQUARED_ACCESS_KEY', 'LEADSQUARED_SECRET_KEY', 'LEADSQUARED_HOST'];3let allOk = true;4for (const key of required) {5 const val = process.env[key];6 if (!val) {7 console.error(`MISSING: ${key} β add it via Replit Secrets (lock icon π)`);8 allOk = false;9 } else {10 console.log(`OK: ${key} (${val.length} chars)`);11 }12}13if (allOk) console.log('All LeadSquared secrets verified.');Pro tip: Never log the full API request URL when it contains accessKey and secretKey parameters. Use partial logging that shows only the endpoint path to avoid accidentally exposing credentials in deployment logs.
Expected result: All three LeadSquared secrets are present in the Replit Secrets panel. The verification script confirms they are all loaded and non-empty without printing sensitive values.
Create and capture leads
Create and capture leads
The LeadSquared lead creation API is a POST request to /v2/LeadManagement.svc/Lead.Create with a JSON body containing an array of lead attributes. Each attribute is an object with SchemaName (the field's API name) and Value. Standard lead fields include FirstName, LastName, EmailAddress, Phone, mx_Source (lead source), and any custom fields defined in your LeadSquared account schema. You can get a list of all available lead fields by calling the GetLeadFields API endpoint. The API supports creating a single lead or multiple leads in bulk (up to 200 per call for bulk operations). For web form capture, use the single lead creation endpoint and include a Source activity so LeadSquared tracks where the lead originated. The response includes the created lead's LeadId, which you should store for subsequent activity logging. Build an Express or Flask endpoint that acts as the form submission handler and immediately proxies the data to LeadSquared, returning a clean JSON response to the frontend.
1// Node.js β lead capture endpoint (index.js)2const express = require('express');3const axios = require('axios');45const app = express();6app.use(express.json());78const ACCESS_KEY = process.env.LEADSQUARED_ACCESS_KEY;9const SECRET_KEY = process.env.LEADSQUARED_SECRET_KEY;10const HOST = process.env.LEADSQUARED_HOST || 'https://api.leadsquared.com';1112const lsParams = { accessKey: ACCESS_KEY, secretKey: SECRET_KEY };1314app.post('/capture-lead', async (req, res) => {15 const { firstName, lastName, email, phone, source } = req.body;16 if (!email) return res.status(400).json({ error: 'email is required' });1718 const leadData = [19 { SchemaName: 'FirstName', Value: firstName || '' },20 { SchemaName: 'LastName', Value: lastName || '' },21 { SchemaName: 'EmailAddress', Value: email },22 { SchemaName: 'Phone', Value: phone || '' },23 { SchemaName: 'mx_Source', Value: source || 'Website Form' }24 ];2526 try {27 const response = await axios.post(28 `${HOST}/v2/LeadManagement.svc/Lead.Create`,29 leadData,30 { params: lsParams }31 );32 const leadId = response.data.Message?.Id;33 console.log(`Lead created: ${leadId}`);34 res.json({ success: true, leadId });35 } catch (err) {36 console.error('LeadSquared error:', err.response?.data || err.message);37 res.status(500).json({ error: 'Failed to create lead' });38 }39});4041app.listen(3000, '0.0.0.0', () => console.log('Lead capture server running'));Pro tip: Use LeadSquared's 'Lead.CreateOrUpdate' endpoint instead of 'Lead.Create' if you want to upsert leads β it creates a new lead if the email doesn't exist or updates the existing lead if it does, preventing duplicate entries from repeat form submissions.
Expected result: A POST to /capture-lead with a valid email returns a JSON response with success: true and the new lead's ID. The lead appears in your LeadSquared dashboard within seconds.
Log activities against leads
Log activities against leads
Activity logging is central to LeadSquared's lead scoring and automation engine. When you log activities against a lead (email opens, webinar attendance, demo requests, page views), LeadSquared uses those signals to update the lead's score and potentially trigger automation rules like assigning the lead to a different sales rep, sending a follow-up email, or moving the lead to a new pipeline stage. The activity logging API endpoint is POST /v2/ProspectActivity.svc/Activity.Push. The request body is an array of activity objects, each containing the lead identifier (typically EmailAddress or LeadId), an ActivityEvent (mapped to a numeric event code or a custom event name), and optional Activity Notes. LeadSquared has predefined system activity codes (e.g., 1 = Email Sent, 2 = Email Opened, 3 = Email Clicked) and allows custom activity events defined in your account. You can retrieve your custom activity codes from Settings > Lead Activity > Custom Activities in the LeadSquared dashboard. Build an activity logging function that accepts the lead identifier, event type, and metadata and fires the API call β this function becomes the core of any event-driven integration.
1# Python β log activity against a lead (log_activity.py)2import requests3import os45ACCESS_KEY = os.environ['LEADSQUARED_ACCESS_KEY']6SECRET_KEY = os.environ['LEADSQUARED_SECRET_KEY']7HOST = os.environ.get('LEADSQUARED_HOST', 'https://api.leadsquared.com')89params = {'accessKey': ACCESS_KEY, 'secretKey': SECRET_KEY}1011def log_activity(email, event_code, note=''):12 """13 Log an activity against a lead identified by email.14 event_code: integer (system codes) or custom event name15 """16 payload = [{17 'RelatedProspectId': email,18 'ActivityEvent': event_code,19 'ActivityNote': note,20 'ActivityDateTime': None # None uses current time21 }]22 response = requests.post(23 f'{HOST}/v2/ProspectActivity.svc/Activity.Push',24 json=payload,25 params=params26 )27 if response.status_code == 200:28 result = response.json()29 print(f'Activity logged: {result.get("Status")}')30 return result31 else:32 print(f'Error {response.status_code}: {response.text}')33 return None3435# Example: Log a 'Webinar Attended' activity (use your custom event code)36log_activity(37 email='test@example.com',38 event_code=208, # Replace with your custom activity event code39 note='Attended product overview webinar on 2026-03-30'40)Pro tip: Ask your LeadSquared account admin for the list of custom activity event codes defined in your account. Using an invalid event code will result in an error; using the wrong code will log the activity under the wrong event type, affecting lead scoring.
Expected result: The activity logging script returns a success status and the activity appears in the lead's activity timeline in the LeadSquared dashboard.
Search leads and retrieve lead scores
Search leads and retrieve lead scores
The LeadSquared search API allows you to find leads by field values, retrieve their current lead scores, and pull custom field data for downstream processing. The main search endpoint is POST /v2/LeadManagement.svc/Leads.GetByEmailAddress for email-based lookup, or POST /v2/LeadManagement.svc/Leads.GetByCriteria for multi-field searches. The lead score is typically available as the mx_LeadScore field in the returned lead object. Build a Replit endpoint that accepts a search criteria object and returns matching leads with their scores β this can power a scoring dashboard, a sales rep app, or a lead routing engine that assigns high-scoring leads to senior reps and lower-scoring leads to junior reps. Deploy as an Autoscale deployment if this endpoint needs to be called by external systems; use a Reserved VM deployment if you run scheduled scoring reports that need to run at fixed intervals regardless of inbound traffic.
1// Node.js β search leads and get scores (search-leads.js)2const axios = require('axios');34const ACCESS_KEY = process.env.LEADSQUARED_ACCESS_KEY;5const SECRET_KEY = process.env.LEADSQUARED_SECRET_KEY;6const HOST = process.env.LEADSQUARED_HOST || 'https://api.leadsquared.com';7const params = { accessKey: ACCESS_KEY, secretKey: SECRET_KEY };89async function searchLeadByEmail(email) {10 const response = await axios.get(11 `${HOST}/v2/LeadManagement.svc/Lead.GetByEmailAddress`,12 { params: { ...params, emailaddress: email } }13 );14 return response.data;15}1617async function getLeadsByScore(minScore) {18 const criteria = [19 {20 Attribute: 'mx_LeadScore',21 Operator: 'GreaterThan',22 Value: String(minScore)23 }24 ]25 const response = await axios.post(26 `${HOST}/v2/LeadManagement.svc/Leads.GetByCriteria`,27 criteria,28 { params: { ...params, start: 0, size: 50 } }29 );30 return response.data;31}3233(async () => {34 // Example: get leads with score > 5035 const result = await getLeadsByScore(50);36 const leads = result.Leads || [];37 console.log(`Found ${leads.length} leads with score > 50`);38 leads.forEach(lead => {39 const name = `${lead.FirstName || ''} ${lead.LastName || ''}`.trim();40 const score = lead.mx_LeadScore || 0;41 console.log(` ${name} (${lead.EmailAddress}) β Score: ${score}`);42 });43})();Pro tip: LeadSquared's search API returns a maximum of 1000 leads per call. For large datasets, use the start and size parameters to paginate through results. Track the total count returned in the first call to determine how many pages to fetch.
Expected result: The search script returns a list of leads with lead scores above the specified threshold. Lead data includes name, email, and current score fields.
Common use cases
Website Lead Capture to LeadSquared
When a visitor submits a lead generation form on your website, your Replit backend receives the form data via POST, validates the required fields, and immediately creates a new lead in LeadSquared with all captured attributes (name, email, phone, source, campaign). The lead is also tagged with the landing page URL as the activity source so sales reps know which campaign generated the prospect.
Build an Express server with a POST /capture-lead endpoint that receives form data (first name, last name, email, phone, source), validates required fields, creates a LeadSquared lead with those attributes plus a 'Website Form' source tag, and returns a 200 with the created lead ID. Store LEADSQUARED_ACCESS_KEY and LEADSQUARED_SECRET_KEY in Replit Secrets.
Copy this prompt to try it in Replit
Activity Logger from External Tools
When a lead watches a product webinar (tracked by a video platform), downloads a whitepaper (tracked by your asset management system), or completes an onboarding step (tracked by your app), your Replit middleware receives these events and logs them as activities against the corresponding lead in LeadSquared. This enriches lead scores and triggers follow-up automation rules.
Build a Flask endpoint at /log-activity that accepts a JSON payload with lead email, activity type, and metadata, looks up the lead ID in LeadSquared by email, and posts a new activity log entry to the LeadSquared activities API. Include error handling for leads not found.
Copy this prompt to try it in Replit
Lead Score Reporting Dashboard
A scheduled Replit job queries LeadSquared for all leads in specific pipelines, retrieves their current scores and last activity dates, and writes the data to a Google Sheet or Slack message as a daily lead quality report. Sales managers can see at a glance which leads have warmed up and need immediate outreach.
Build a Python script that fetches all leads with a score above 50 from LeadSquared using the search API, formats their name, email, score, and last activity into a readable table, and prints the report. Store API credentials in Replit Secrets and schedule via Replit's scheduled deployments.
Copy this prompt to try it in Replit
Troubleshooting
All API calls return 'Please provide valid accessKey and secretKey' error
Cause: The credentials are either incorrect, being passed in the wrong format, or the LEADSQUARED_HOST environment variable points to the wrong regional API endpoint.
Solution: Verify that LEADSQUARED_ACCESS_KEY and LEADSQUARED_SECRET_KEY in Replit Secrets exactly match the values shown in LeadSquared Settings > API & Webhooks. Also confirm you are using the correct regional API host URL β US accounts use api.leadsquared.com but other regions have different URLs.
1// Correct: pass as query params2const params = {3 accessKey: process.env.LEADSQUARED_ACCESS_KEY,4 secretKey: process.env.LEADSQUARED_SECRET_KEY5};6await axios.post(url, body, { params });Lead.Create returns success but the lead does not appear in LeadSquared
Cause: The API may have returned a success status but the email address field was empty or malformed, causing the lead to be created without an identifier and filtered from default views.
Solution: Always include a valid EmailAddress in your lead creation payload β it is the primary identifier. Check the API response's Message.Id field to confirm the lead was actually created. Use the GetByEmailAddress endpoint to verify the lead exists after creation.
1// Always validate email before API call2if (!email || !email.includes('@')) {3 return res.status(400).json({ error: 'Valid email required for lead creation' });4}Activity logging returns success but lead score does not change
Cause: The activity event code used does not have a score weight configured in LeadSquared's scoring rules, or the scoring rules require multiple activities before awarding points.
Solution: Check the lead scoring configuration in LeadSquared Settings > Lead Scoring to verify which activity events are configured to add score points. Use the event codes that match your configured scoring rules. Contact your LeadSquared admin if activity codes need to be added to the scoring model.
GetByCriteria search returns 0 results despite leads existing that match the criteria
Cause: The field name in the Attribute parameter may be incorrect (e.g., using 'LeadScore' instead of 'mx_LeadScore'), or the Operator string is not matching the expected API format.
Solution: Use the GetLeadFields API endpoint to get the exact SchemaName for each field. LeadSquared custom fields typically have an 'mx_' prefix. Verify the Operator string against the LeadSquared API documentation β supported operators include 'Equal', 'NotEqual', 'GreaterThan', 'LessThan', 'Contains'.
Best practices
- Store LEADSQUARED_ACCESS_KEY, LEADSQUARED_SECRET_KEY, and LEADSQUARED_HOST in Replit Secrets (lock icon π) β credentials passed as query parameters are especially risky to hardcode
- Never log full API request URLs since they contain accessKey and secretKey as query parameters β log only the endpoint path and response status
- Use Lead.CreateOrUpdate instead of Lead.Create to prevent duplicate leads from repeat form submissions by the same email address
- Cache the list of custom activity event codes in your application β fetching them from the API on every request is unnecessary and wastes rate limit quota
- Add email format validation before calling the LeadSquared lead creation API β invalid emails cause silent failures that are hard to debug
- Deploy as Autoscale for form capture endpoints that need to be always available; use Scheduled deployments for periodic score reporting jobs
- Paginate through search results using start and size parameters β never assume a single API call returns all matching leads
- Log the LeadId returned from every lead creation call so you can reference it in subsequent activity logging calls without needing a secondary lookup
Alternatives
HubSpot offers a broader inbound marketing suite with a more developer-friendly OAuth 2.0 API, making it a better choice if you need marketing automation alongside CRM.
Freshsales is part of the Freshworks suite with a simpler API key authentication model and strong integrations with Freshdesk support tickets.
Pipedrive provides a visual sales pipeline with a clean REST API, better suited for teams that prioritize deal tracking over lead scoring and routing.
Salesforce is the enterprise CRM standard with more powerful customization and a larger ecosystem, though its API is significantly more complex to integrate than LeadSquared's.
Frequently asked questions
How do I connect Replit to LeadSquared?
Obtain your Access Key and Secret Key from LeadSquared Settings > API & Webhooks, store both in Replit Secrets (lock icon π), and make HTTP requests to the LeadSquared REST API from your Express or Flask server, passing the credentials as query parameters on every request.
Does Replit work with LeadSquared for free?
LeadSquared API access is included in paid LeadSquared plans. Replit's free tier supports development and testing, but you will need a Replit Autoscale deployment for always-available lead capture endpoints. Check your LeadSquared plan's API access limits before building high-volume integrations.
How do I store the LeadSquared API key in Replit?
Click the lock icon (π) in the Replit sidebar to open Secrets. Add LEADSQUARED_ACCESS_KEY and LEADSQUARED_SECRET_KEY with the values from your LeadSquared API settings. Access them in Python with os.environ['KEY'] or in Node.js with process.env.KEY. Never add them as URL query parameters directly in code strings.
How do I prevent duplicate leads in LeadSquared from Replit?
Use the Lead.CreateOrUpdate endpoint instead of Lead.Create. This upserts the lead β if a lead with the same email address already exists, it updates the existing record rather than creating a duplicate. Always use a unique identifier (email address) as the deduplication key.
Can I trigger LeadSquared automation rules from Replit?
Yes. Posting activities against a lead via the Activity.Push API can trigger LeadSquared automation rules that are configured to fire when specific activities are logged. Score-based automation rules trigger automatically when lead scores are updated by activity logging. You can also use the Automation API endpoints to directly trigger specific automation flows.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation