Skip to main content
RapidDev - Software Development Agency
replit-integrationsStandard API Integration

How to Integrate Replit with TikTok Ads

To integrate Replit with TikTok Ads, register a TikTok Marketing API developer app to get your App ID, Secret, and access token, store them in Replit Secrets (lock icon πŸ”’), and call the TikTok Marketing API from your Python or Node.js backend to create campaigns, manage ad groups, upload creatives, and retrieve performance analytics. Deploy with Autoscale for on-demand ad operations.

What you'll learn

  • How to register a TikTok Marketing API developer app and obtain API credentials
  • How to authenticate to the TikTok Marketing API using an access token from Replit Secrets
  • How to create campaigns, ad groups, and ads programmatically in Python and Node.js
  • How to retrieve TikTok ad performance metrics and build custom reporting pipelines
  • How to automate TikTok ad campaign management workflows from your Replit backend
Book a free consultation
4.9Clutch rating ⭐
600+Happy partners
17+Countries served
190+Team members
Intermediate14 min read30 minutesMarketingMarch 2026RapidDev Engineering Team
TL;DR

To integrate Replit with TikTok Ads, register a TikTok Marketing API developer app to get your App ID, Secret, and access token, store them in Replit Secrets (lock icon πŸ”’), and call the TikTok Marketing API from your Python or Node.js backend to create campaigns, manage ad groups, upload creatives, and retrieve performance analytics. Deploy with Autoscale for on-demand ad operations.

Why Connect Replit to TikTok Ads?

TikTok's advertising platform has grown into a critical performance marketing channel, particularly for brands targeting audiences under 35. The TikTok Marketing API enables developers to automate campaign management at scale: creating campaigns programmatically, adjusting bids based on performance data, uploading creative assets in bulk, and building custom dashboards that aggregate TikTok data alongside other ad platforms.

The most impactful use cases for Replit integration are performance reporting automation and bulk campaign management. A Replit backend can pull daily TikTok ad metrics, aggregate them with Facebook and Google Ads data, and push combined reports to Smartsheet or Slack β€” eliminating the manual dashboard-checking routine for marketing teams. Alternatively, it can create campaigns from a structured template when a new product launches, setting targeting, budget, and creative parameters automatically.

TikTok's Marketing API uses OAuth 2.0 for authentication, but for single-advertiser automation you can generate a long-lived access token from the developer portal that does not require repeated OAuth authorization. This token, stored in Replit Secrets (lock icon πŸ”’ in the sidebar), authenticates all API calls from your server-side code. Never expose the access token in client-side JavaScript β€” it provides full access to your TikTok Ads account including the ability to spend budget.

Integration method

Standard API Integration

You connect Replit to TikTok Ads by registering a developer application in the TikTok Marketing API portal to obtain API credentials, storing them in Replit Secrets, and calling the TikTok Marketing API from your server-side Python or Node.js code. The API covers campaign management, ad group targeting, creative uploads, and reporting. Authentication uses a long-lived access token obtained via OAuth 2.0 and included in all request headers.

Prerequisites

  • A Replit account with a Python or Node.js project created
  • A TikTok Ads Manager account with an active advertiser account (advertiser_id)
  • A TikTok developer account at business.tiktok.com/portal to create a Marketing API app
  • Basic familiarity with REST APIs, ad platform concepts (campaign/ad group/ad hierarchy), and JSON
  • Node.js 18+ or Python 3.10+ (both available on Replit by default)

Step-by-step guide

1

Register a TikTok Marketing API App and Get Credentials

Navigate to the TikTok Marketing API portal at business.tiktok.com/portal. Sign in with your TikTok business account. In the developer console, click 'Create App' and fill in the application details: - App Name: 'Replit Marketing Integration' or similar - App Type: 'Standard API' for most use cases - Industry and description as appropriate - Redirect URI: your Replit app URL for OAuth callbacks (e.g., https://your-repl.repl.co/oauth/callback) After creating the app, navigate to its settings. You will find: - App ID: your application identifier - App Secret: your application secret (keep this confidential) For generating an access token for your own advertiser account without going through the full OAuth flow each time, TikTok provides a long-lived token generation option in the developer portal. Look for 'Generate Token' or 'Access Token' in the app settings. This generates a token that is valid for 24 hours (some configurations provide longer-lived tokens). Also note your Advertiser ID β€” this is visible in your TikTok Ads Manager URL when you are logged in (it looks like a long numeric ID). You will need this for all API calls that manage campaigns.

Pro tip: TikTok's Marketing API has two environments: sandbox and production. The sandbox lets you test API calls without spending real budget. Create a sandbox advertiser account in the developer portal and test all your integration code against the sandbox before switching to production credentials.

Expected result: You have a TikTok App ID, App Secret, access token, and advertiser ID ready to add to Replit Secrets.

2

Store TikTok Marketing API Credentials in Replit Secrets

Open your Replit project and click the lock icon πŸ”’ in the left sidebar to open the Secrets pane. Add the following secrets: - Key: TIKTOK_APP_ID β€” Value: your TikTok Marketing API App ID - Key: TIKTOK_APP_SECRET β€” Value: your App Secret - Key: TIKTOK_ACCESS_TOKEN β€” Value: your access token - Key: TIKTOK_ADVERTISER_ID β€” Value: your TikTok Ads advertiser ID Click 'Add Secret' after each entry. Replit encrypts these values and injects them as environment variables at runtime. They never appear in your file tree or Git history. Access them in Python with os.environ['TIKTOK_ACCESS_TOKEN'] and in Node.js with process.env.TIKTOK_ACCESS_TOKEN. Restart your Repl after adding secrets. The access token provides full access to your TikTok Ads account, including the ability to create campaigns, spend budget, and read all advertising data. Treat it with the same care as a production database password. Never commit it to source code.

Pro tip: TikTok access tokens have an expiry date. When building production integrations, implement token refresh logic using your App ID and Secret, or schedule a periodic token refresh. Set a calendar reminder to refresh the token before it expires to avoid service interruption.

Expected result: TIKTOK_APP_ID, TIKTOK_APP_SECRET, TIKTOK_ACCESS_TOKEN, and TIKTOK_ADVERTISER_ID appear in the Replit Secrets pane.

3

Create Campaigns and Retrieve Analytics with Python

The TikTok Marketing API base URL is https://business-api.tiktok.com/open_api/v1.3. All requests use the Access-Token header (not Authorization: Bearer β€” this is a TikTok-specific convention). The advertiser_id is passed as a query parameter or in the request body depending on the endpoint. TikTok Ads are organized in a three-level hierarchy: Campaign (objective and total budget) > Ad Group (targeting, schedule, bid) > Ad (creative β€” video + text). You create them in this order. The Python module below shows creating a campaign, retrieving campaign performance data, and managing ad group status. Install requests with pip install requests.

tiktok_ads_client.py
1import os
2import requests
3from datetime import datetime, timedelta
4from typing import Optional
5
6ACCESS_TOKEN = os.environ["TIKTOK_ACCESS_TOKEN"]
7ADVERTISER_ID = os.environ["TIKTOK_ADVERTISER_ID"]
8BASE_URL = "https://business-api.tiktok.com/open_api/v1.3"
9
10# TikTok uses Access-Token header, not Authorization: Bearer
11HEADERS = {
12 "Access-Token": ACCESS_TOKEN,
13 "Content-Type": "application/json"
14}
15
16def api_get(endpoint: str, params: dict = None) -> dict:
17 """Make a GET request to the TikTok Marketing API."""
18 if params is None:
19 params = {}
20 params['advertiser_id'] = ADVERTISER_ID
21 response = requests.get(f"{BASE_URL}/{endpoint}", params=params, headers=HEADERS)
22 response.raise_for_status()
23 data = response.json()
24 if data.get('code') != 0:
25 raise Exception(f"TikTok API error: {data.get('message')} (code: {data.get('code')})")
26 return data.get('data', {})
27
28def api_post(endpoint: str, payload: dict) -> dict:
29 """Make a POST request to the TikTok Marketing API."""
30 payload['advertiser_id'] = ADVERTISER_ID
31 response = requests.post(f"{BASE_URL}/{endpoint}", json=payload, headers=HEADERS)
32 response.raise_for_status()
33 data = response.json()
34 if data.get('code') != 0:
35 raise Exception(f"TikTok API error: {data.get('message')} (code: {data.get('code')})")
36 return data.get('data', {})
37
38def create_campaign(
39 name: str,
40 objective: str = "TRAFFIC", # AWARENESS, TRAFFIC, APP_PROMOTION, LEAD_GENERATION, CONVERSIONS
41 budget_mode: str = "BUDGET_MODE_INFINITE",
42 budget: float = 0
43) -> dict:
44 """
45 Create a TikTok ad campaign.
46 Returns campaign data including campaign_id.
47 """
48 payload = {
49 "campaign_name": name,
50 "objective_type": objective,
51 "budget_mode": budget_mode,
52 "operation_status": "DISABLE" # Start paused, enable manually after review
53 }
54 if budget > 0:
55 payload["budget"] = budget
56 payload["budget_mode"] = "BUDGET_MODE_DAY"
57
58 return api_post("campaign/create/", payload)
59
60def get_campaigns(status_filter: str = "ALL") -> list:
61 """List all campaigns for the advertiser."""
62 data = api_get("campaign/get/", {"primary_status": status_filter})
63 return data.get('list', [])
64
65def get_campaign_report(
66 campaign_ids: list,
67 start_date: str, # YYYY-MM-DD
68 end_date: str,
69 metrics: list = None
70) -> list:
71 """
72 Retrieve performance metrics for specified campaigns.
73 Default metrics: impressions, clicks, spend, conversions, ROAS.
74 """
75 if metrics is None:
76 metrics = [
77 "campaign_name", "spend", "impressions", "clicks",
78 "ctr", "cpc", "conversions", "cost_per_conversion",
79 "total_complete_payment_roas"
80 ]
81 payload = {
82 "report_type": "BASIC",
83 "dimensions": ["campaign_id"],
84 "metrics": metrics,
85 "data_level": "AUCTION_CAMPAIGN",
86 "start_date": start_date,
87 "end_date": end_date,
88 "filtering": [
89 {"field_name": "campaign_ids", "filter_type": "IN",
90 "filter_value": str(campaign_ids)}
91 ],
92 "page_size": 100
93 }
94 return api_post("report/integrated/get/", payload).get('list', [])
95
96def update_ad_group_status(ad_group_id: str, status: str) -> dict:
97 """Enable or pause an ad group. status: 'ENABLE' or 'DISABLE'"""
98 return api_post("adgroup/status/update/", {
99 "adgroup_ids": [ad_group_id],
100 "operation_status": status
101 })
102
103# Example usage
104if __name__ == "__main__":
105 # List all campaigns
106 campaigns = get_campaigns()
107 print(f"Total campaigns: {len(campaigns)}")
108 for c in campaigns[:5]:
109 print(f" {c['campaign_id']}: {c['campaign_name']} [{c['primary_status']}]")
110
111 # Get last 7 days performance report
112 today = datetime.now()
113 start = (today - timedelta(days=7)).strftime("%Y-%m-%d")
114 end = today.strftime("%Y-%m-%d")
115
116 if campaigns:
117 campaign_ids = [c['campaign_id'] for c in campaigns[:5]]
118 report = get_campaign_report(campaign_ids, start, end)
119 for row in report:
120 dims = row.get('dimensions', {})
121 metrics = row.get('metrics', {})
122 print(f"Campaign {dims.get('campaign_id')}: "
123 f"Spend=${metrics.get('spend', 0)} | "
124 f"Impressions={metrics.get('impressions', 0)} | "
125 f"ROAS={metrics.get('total_complete_payment_roas', 'N/A')}")

Pro tip: TikTok returns API errors with HTTP status 200 but a non-zero 'code' field in the JSON response. Always check the 'code' field in the response (not just the HTTP status) and raise an exception if it is not 0. The 'message' field provides a human-readable error description.

Expected result: Running the Python script lists your TikTok campaigns and prints a 7-day performance summary with spend and impression data.

4

Build a Campaign Management Server with Node.js

A Node.js Express server provides endpoints for creating campaigns on demand and retrieving performance reports. This is useful when integrating TikTok Ads management into a marketing dashboard or triggering campaign creation from other business systems. The server handles the TikTok-specific response format (all responses return HTTP 200 with a code field) and exposes clean endpoints for frontend or other service consumption. Install dependencies with npm install express axios.

server.js
1const express = require('express');
2const axios = require('axios');
3
4const app = express();
5app.use(express.json());
6
7const ACCESS_TOKEN = process.env.TIKTOK_ACCESS_TOKEN;
8const ADVERTISER_ID = process.env.TIKTOK_ADVERTISER_ID;
9const BASE_URL = 'https://business-api.tiktok.com/open_api/v1.3';
10
11const ttHeaders = {
12 'Access-Token': ACCESS_TOKEN,
13 'Content-Type': 'application/json'
14};
15
16async function tiktokGet(endpoint, params = {}) {
17 const response = await axios.get(`${BASE_URL}/${endpoint}`, {
18 headers: ttHeaders,
19 params: { ...params, advertiser_id: ADVERTISER_ID }
20 });
21 const { code, message, data } = response.data;
22 if (code !== 0) throw new Error(`TikTok API error: ${message} (code: ${code})`);
23 return data;
24}
25
26async function tiktokPost(endpoint, payload) {
27 const response = await axios.post(`${BASE_URL}/${endpoint}`, {
28 ...payload,
29 advertiser_id: ADVERTISER_ID
30 }, { headers: ttHeaders });
31 const { code, message, data } = response.data;
32 if (code !== 0) throw new Error(`TikTok API error: ${message} (code: ${code})`);
33 return data;
34}
35
36// GET /campaigns β€” list all campaigns
37app.get('/campaigns', async (req, res) => {
38 try {
39 const data = await tiktokGet('campaign/get/');
40 res.json({
41 total: data.page_info?.total_number || 0,
42 campaigns: data.list || []
43 });
44 } catch (error) {
45 console.error('TikTok error:', error.message);
46 res.status(500).json({ error: error.message });
47 }
48});
49
50// POST /campaigns β€” create a new campaign
51app.post('/campaigns', async (req, res) => {
52 const { name, objective, dailyBudget } = req.body;
53 if (!name || !objective) {
54 return res.status(400).json({ error: 'name and objective are required' });
55 }
56 try {
57 const payload = {
58 campaign_name: name,
59 objective_type: objective,
60 operation_status: 'DISABLE' // Start paused for review
61 };
62 if (dailyBudget) {
63 payload.budget = dailyBudget;
64 payload.budget_mode = 'BUDGET_MODE_DAY';
65 } else {
66 payload.budget_mode = 'BUDGET_MODE_INFINITE';
67 }
68 const data = await tiktokPost('campaign/create/', payload);
69 res.json({ success: true, campaignId: data.campaign_id });
70 } catch (error) {
71 console.error('TikTok error:', error.message);
72 res.status(500).json({ error: error.message });
73 }
74});
75
76// GET /report?startDate=YYYY-MM-DD&endDate=YYYY-MM-DD β€” performance report
77app.get('/report', async (req, res) => {
78 const { startDate, endDate } = req.query;
79 if (!startDate || !endDate) {
80 return res.status(400).json({ error: 'startDate and endDate query params required (YYYY-MM-DD)' });
81 }
82 try {
83 const data = await tiktokPost('report/integrated/get/', {
84 report_type: 'BASIC',
85 dimensions: ['campaign_id'],
86 metrics: ['campaign_name', 'spend', 'impressions', 'clicks', 'ctr', 'cpc', 'conversions'],
87 data_level: 'AUCTION_CAMPAIGN',
88 start_date: startDate,
89 end_date: endDate,
90 page_size: 50
91 });
92 res.json({ rows: data.list || [] });
93 } catch (error) {
94 console.error('TikTok error:', error.message);
95 res.status(500).json({ error: error.message });
96 }
97});
98
99app.listen(3000, '0.0.0.0', () => {
100 console.log('TikTok Ads integration server running on port 3000');
101});

Pro tip: Always create campaigns in DISABLE (paused) status and review them in TikTok Ads Manager before enabling them. TikTok's ad policies require creative review, and activating a campaign programmatically before review may result in the campaign being rejected, wasting your budget setup.

Expected result: The Express server starts on port 3000. GET /campaigns lists your TikTok campaigns and GET /report returns performance metrics for the specified date range.

Common use cases

Automated Campaign Creation on Product Launch

When a new product is launched in your e-commerce system, a Replit backend automatically creates a TikTok campaign with optimized settings, configures ad groups targeting relevant interest categories and demographics, and uploads product video creatives β€” launching the campaign minutes after product creation without manual Ad Manager setup.

Replit Prompt

Build a Flask endpoint that receives a product launch webhook, creates a TikTok Awareness campaign via the Marketing API with a daily budget and target audience based on product category, and returns the campaign ID and initial status.

Copy this prompt to try it in Replit

Cross-Platform Performance Dashboard

A Replit scheduled job pulls TikTok ad performance data (impressions, clicks, conversions, spend, ROAS) daily across all active campaigns, normalizes it alongside Facebook and Google Ads data, and writes the combined report to a Smartsheet or sends it as a formatted Slack message to the marketing team.

Replit Prompt

Create a Python script that fetches the last 7 days of TikTok ad metrics from the Marketing API, aggregates spend and ROAS by campaign, formats the results as a readable report, and posts it to a Slack channel using the TIKTOK_ACCESS_TOKEN and SLACK_BOT_TOKEN from Replit Secrets.

Copy this prompt to try it in Replit

Budget Pacing and Bid Optimization

A Replit service monitors TikTok campaign spend throughout the day and automatically adjusts daily budgets or bids based on pacing rules β€” increasing budgets for high-performing ad groups when ROAS exceeds threshold and pausing underperforming creatives β€” without requiring manual intervention from the media buyer.

Replit Prompt

Write a Python script that retrieves TikTok ad group performance every 4 hours, identifies ad groups with ROAS below 1.5, pauses those ad groups via the API, and sends an alert with the paused ad groups list to a monitoring Slack channel.

Copy this prompt to try it in Replit

Troubleshooting

All API responses return HTTP 200 but with code 40001 or 40002 and 'invalid access token'

Cause: The access token has expired, was revoked, or is not included in the correct header. TikTok uses 'Access-Token' as the header name, not 'Authorization: Bearer'.

Solution: Verify TIKTOK_ACCESS_TOKEN is set in Replit Secrets and that the header is set as 'Access-Token: YOUR_TOKEN' (not Authorization). If the token has expired, generate a new one from the TikTok developer portal or implement token refresh using your App ID and Secret.

typescript
1# Correct TikTok header format
2HEADERS = {
3 "Access-Token": os.environ["TIKTOK_ACCESS_TOKEN"], # NOT 'Authorization: Bearer'
4 "Content-Type": "application/json"
5}

Campaign creation returns code 40300 'permission denied' or 'no permission to operate'

Cause: The access token does not have permission to perform write operations on the specified advertiser account, or the advertiser_id belongs to a different account than the token was issued for.

Solution: Verify that TIKTOK_ADVERTISER_ID matches the advertiser account associated with your access token. In TikTok Ads Manager, the advertiser ID is visible in account settings. If your token was generated for a sandbox account, it cannot be used for production campaigns.

Report endpoint returns an empty list even though campaigns have been running

Cause: The date range is incorrect (future dates or too far in the past), the campaign IDs in the filter are wrong, or the report_type/data_level combination does not match the campaigns' buying type.

Solution: Verify the date range is in the past and in YYYY-MM-DD format. Remove the campaign_ids filter to get all campaigns first, then narrow down. Use 'AUCTION' campaigns with data_level 'AUCTION_CAMPAIGN' for standard campaigns, or 'REACH_FREQUENCY' for reservation campaigns.

typescript
1# Start without filters to verify data is available
2payload = {
3 "report_type": "BASIC",
4 "dimensions": ["campaign_id"],
5 "metrics": ["campaign_name", "spend", "impressions"],
6 "data_level": "AUCTION_CAMPAIGN",
7 "start_date": "2026-03-01", # Use a known past date
8 "end_date": "2026-03-30",
9 "page_size": 100
10 # No filtering initially
11}

Rate limit error: code 40100 or HTTP 429 after many requests

Cause: TikTok Marketing API has rate limits of approximately 100 requests per minute per access token for most endpoints. Bulk operations that loop through many campaigns or ad groups can hit this limit quickly.

Solution: Add delays between batches of API calls and implement exponential backoff for 429 responses. For reporting, use the report endpoint with multiple dimensions in a single call rather than querying each campaign separately.

typescript
1import time
2
3def api_post_with_retry(endpoint, payload, max_retries=3):
4 for attempt in range(max_retries):
5 try:
6 return api_post(endpoint, payload)
7 except Exception as e:
8 if '40100' in str(e) or '429' in str(e):
9 wait_time = (2 ** attempt) * 5 # 5s, 10s, 20s
10 print(f"Rate limited. Waiting {wait_time}s before retry...")
11 time.sleep(wait_time)
12 else:
13 raise
14 raise Exception("Max retries exceeded")

Best practices

  • Always store TIKTOK_ACCESS_TOKEN and TIKTOK_ADVERTISER_ID in Replit Secrets β€” access tokens provide full account access including budget spending
  • Use 'Access-Token' as the header name for authentication, not 'Authorization: Bearer' β€” this is TikTok-specific and a common integration mistake
  • Check the 'code' field in every API response regardless of HTTP status β€” TikTok returns errors as HTTP 200 with a non-zero code value
  • Create campaigns in DISABLE (paused) status and review them in Ads Manager before enabling, to ensure creative compliance before budget is spent
  • Monitor token expiry and implement automated token refresh before expiry to prevent integration downtime
  • Use sandbox advertiser accounts for all testing and development β€” production campaigns spend real money
  • Batch reporting requests to retrieve all campaign metrics in a single API call with multiple dimensions rather than making per-campaign calls
  • Deploy on Replit Autoscale for HTTP-triggered campaign management and use Reserved VM for scheduled performance monitoring and pacing adjustment scripts

Alternatives

Frequently asked questions

How do I connect Replit to TikTok Ads?

Register a developer app at business.tiktok.com/portal, generate an access token, and add TIKTOK_ACCESS_TOKEN and TIKTOK_ADVERTISER_ID to Replit Secrets (lock icon πŸ”’ in the sidebar). Use the 'Access-Token' header (not Authorization) when calling the TikTok Marketing API from your Python or Node.js backend.

Does the TikTok Marketing API require OAuth for every request?

For single-advertiser automation, you can generate a long-lived access token from the TikTok developer portal that authenticates API calls without repeated OAuth flows. Full OAuth 2.0 is needed when building apps where multiple advertisers connect their TikTok accounts to your platform.

Why do TikTok API calls return HTTP 200 even when there is an error?

TikTok Marketing API uses HTTP 200 for all responses and communicates errors via the 'code' field in the JSON response body. A code of 0 means success; any other code indicates an error. Always check the 'code' and 'message' fields in every response.

Can I retrieve TikTok ad performance data from Replit for custom reporting?

Yes. Use the POST /report/integrated/get/ endpoint with your date range, dimensions (campaign_id, ad_group_id, or ad_id), and desired metrics (spend, impressions, clicks, conversions, ROAS). The endpoint returns structured data you can aggregate into custom dashboards or push to other tools.

What TikTok ad campaign objectives can I create via the API?

The Marketing API supports all TikTok campaign objectives: REACH, VIDEO_VIEWS, TRAFFIC, APP_PROMOTION, LEAD_GENERATION, CONVERSIONS, CATALOG_SALES, and COMMUNITY_INTERACTION. Use the objective_type parameter when creating campaigns.

What deployment type should I use on Replit for TikTok Ads integrations?

Use Autoscale deployment for HTTP-triggered endpoints that create campaigns or respond to external events. Use Reserved VM for scheduled optimization jobs that check performance metrics every few hours and automatically adjust bids or pause underperforming ad groups.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation β€” no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.