Tutorial Β· TikTok Ad Library

πŸ“± Kotlin Step-by-step

How to scrape TikTok Ad Library search results
with Kotlin.

Extract search data from TikTok Ad Library. Real code, real responses, real production patterns β€” paste it into your project and ship.

Overview

Learn how to scrape TikTok Ad Library search results using Kotlin. This comprehensive guide will walk you through the entire process, from setup to implementation.

What You'll Learn

  • β€’ Setting up your development environment
  • β€’ Installing the required HTTP client
  • β€’ Authenticating with the ScrapeCreators API
  • β€’ Making requests to TikTok Ad Library
  • β€’ Handling responses and errors
  • β€’ Best practices for production use

What You'll Get

  • β€’ Access to search results data
  • β€’ JSON formatted responses
  • β€’ Real-time data access
  • β€’ Scalable solution
  • β€’ Error handling patterns
  • β€’ Performance optimization tips

Prerequisites

1. API Key

First, you'll need a ScrapeCreators API key to authenticate your requests.

Sign up at app.scrapecreators.com to get your free API key with 100 requests.

2. Development Environment

Make sure you have the following installed:

  • β€’ Kotlin and its dependencies
  • β€’ A code editor (VS Code, Sublime, etc.)
  • β€’ Basic understanding of API requests
  • β€’ Command line interface access

Step 1: Install HTTP Client

OkHttp is an HTTP client for Kotlin/Java

gradle
implementation "com.squareup.okhttp3:okhttp:4.9.3"

Step 2: API Implementation

Now let's make a request to the TikTok Ad Library API using Kotlin. Replace YOUR_API_KEY with your actual API key.

Kotlin
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.net.URI
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

class Scraper {
    companion object {
        private const val API_KEY = "YOUR_API_KEY"
        private const val BASE_URL = "https://api.scrapecreators.com"
        private const val ENDPOINT_PATH = "/v1/tiktok/ad-library/search"
        
        @JvmStatic
        fun main(args: Array<String>) {
            try {
                val result = scrape()
                println("Response: $result")
            } catch (e: Exception) {
                println("Error: ${e.message}")
            }
        }
        
        fun scrape(): String {
            val client = HttpClient.newHttpClient()
            
            // Build query parameters
            val params = mapOf(
                "region" to "US",
                "period" to "30",
                "query" to "spotify",
                "order_by" to "for_you",
                "industry" to "beauty_personal_care",
                "objective" to "traffic",
                "duration" to "under_10s",
                "likes" to "top_1_20",
                "ad_format" to "spark_ads",
                "ad_language" to "en",
                "cursor" to "3",
                "limit" to "20"
            )
            
            val queryString = params.entries.joinToString("&") { (key, value) ->
                "${key}=${URLEncoder.encode(value, StandardCharsets.UTF_8)}"
            }
            
            val url = "${BASE_URL}${ENDPOINT_PATH}?${queryString}"
            
            val request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("x-api-key", API_KEY)
                .header("Accept", "application/json")
                .GET()
                .build()
            
            val response = client.send(request, HttpResponse.BodyHandlers.ofString())
            
            if (response.statusCode() == 200) {
                return response.body()
            } else {
                throw RuntimeException("HTTP ${response.statusCode()}: ${response.body()}")
            }
        }
    }
}

Step 3: Testing Your Code

API Parameters

This endpoint accepts the following parameters:

regionOptional(select)

Country code. Defaults to US.

Example: US

periodOptional(select)

Time window for Top Ads.

Example: 30

queryOptional(string)

Optional keyword to search ad titles/content.

Example: spotify

order_byOptional(select)

Sort metric. Defaults to for_you.

Example: for_you

industryOptional(select)

Industry filter.

Example: beauty_personal_care

objectiveOptional(select)

Campaign objective filter.

Example: traffic

durationOptional(select)

Video duration filter.

Example: under_10s

likesOptional(select)

Likes percentile filter.

Example: top_1_20

ad_formatOptional(select)

Ad format filter.

Example: spark_ads

ad_languageOptional(select)

Ad language filter.

Example: en

cursorOptional(number)

Page number to fetch. Use the cursor returned from the previous response, like 3 for page 3.

Example: 3

limitOptional(number)

Number of ads to return, max 50. Defaults to 20.

Example: 20

Run Your Code

Execute your script to test the API connection. You should see a JSON response with TikTok Ad Library search results data.

βœ… Success: You should receive a structured JSON response containing the requested data.

Expected Response

Here's an example of the JSON response you'll receive:

Sample Response
{
  "success": true,
  "credits_remaining": 49996315011,
  "query": "",
  "region": "US",
  "period": 30,
  "ads": [
    {
      "ad_title": "I thought this was a gimmick until I tried it! A wrinkled shirt, one button, and a few minutes later... ready to wear. Tap the link in bio and see why everyone’s talking about Bellairon before it sells out. @Bellairon LLC ",
      "brand_name": "",
      "cost": 1,
      "ctr": 0.5,
      "favorite": false,
      "id": "7646829987799334920",
      "industry_key": "label_22108000000",
      "is_search": true,
      "like": 92,
      "objective_key": "campaign_objective_reach",
      "video_info": {
        "vid": "v12044gd0000d8erq07og65h1cq991gg",
        "duration": 89.767,
        "cover": "https://p16-common-sign.tiktokcdn.com/tos-maliva-p-0068c799-us/oIbqBdvfEAiFpgvAOgrQHCF5R0mkDDLiEfvQDS~tplv-noop.image?dr=18692&refresh_token=2ac068a9&x-expires=1781231816&x-signature=hLbBkguntM4oX9tgdnKMMDYixAA%3D&t=9276707c&ps=14f1eb3e&shp=9e36835a&shcp=317596d8&idc=my2&VideoID=v12044gd0000d8erq07og65h1cq991gg",
        "video_url": {
          "540p": "https://v16m-default.tiktokcdn.com/64e64ad32f68588eee511da0114f0f2e/6a2b70c8/video/tos/maliva/tos-maliva-ve-0068c799-us/oIN2GPIRgHAUBHOeNfLk2HBSERoJeIALGC3jAE/?a=0&bti=NTU4QDM1NGA%3D&&bt=315&ft=cApXJCz7ThWHK-z9LGZmo0P&mime_type=video_mp4&rc=Omk6ZWQ7Nzc7OGY8PGVnOkBpajQ8Zms5cjN1OzMzZzczNEBgNDAzXl9hXjMxLzEvXjFiYSNkNm4uMmQ0bmJhLS1kMS9zcw%3D%3D&vvpl=1&l=20260612043527C18C959B9A8CF584D398&btag=e00090000",
          "720p": "https://v16m-default.tiktokcdn.com/4ee4e5763b088d7d77e4a9f4fce502b6/6a2b70c8/video/tos/maliva/tos-maliva-ve-0068c799-us/ooEipQa9HbhJ4ChzASIngUPhBAdXiABIvxU2E/?a=0&bti=NTU4QDM1NGA%3D&&bt=877&ft=cApXJCz7ThWHK-z9LGZmo0P&mime_type=video_mp4&rc=ZTg3OTQ0NTQzZGVpNWg6NkBpajQ8Zms5cjN1OzMzZzczNEBhNC0yMDViNi8xLV9hX2AuYSNkNm4uMmQ0bmJhLS1kMS9zcw%3D%3D&vvpl=1&l=20260612043527C18C959B9A8CF584D398&btag=e00090000"
        },
        "width": 720,
        "height": 1280
      }
    },
    {
      "ad_title": "True Heroes go ALL IN or nothing. See yourself at the top!",
      "brand_name": "",
      "cost": 0,
      "ctr": 0.29,
      "favorite": false,
      "id": "7640089122220736530",
      "industry_key": "label_25100000000",
      "is_search": true,
      "like": 1115,
      "objective_key": "campaign_objective_conversion",
      "video_info": {
        "vid": "v10033g50000d8jbia7og65q0198frmg",
        "duration": 105.003,
        "cover": "https://p16-common-sign.tiktokcdn.com/tos-alisg-p-0051c001-sg/o8jPFEKAAIYhaBUQ6CM5tAZiBiKaaAuSi7Hzm~tplv-noop.image?dr=18692&refresh_token=3750a204&x-expires=1781231832&x-signature=RfXRGuG8N6d69HxYz2Z9XUKgdWU%3D&t=9276707c&ps=14f1eb3e&shp=9e36835a&shcp=317596d8&idc=my2&VideoID=v10033g50000d8jbia7og65q0198frmg",
        "video_url": {
          "1080p": "https://v16m-default.tiktokcdn.com/3dad0efc22921436631456d0eb262abc/6a2b70d8/video/tos/alisg/tos-alisg-ve-0051c001-sg/oEPIgOBQUJpQBtqKOFyFDfEMODsYfUAzNhBAIQ/?a=0&bti=NTU4QDM1NGA%3D&&bt=2989&ft=cApXJCz7ThWHK-z9LGZmo0P&mime_type=video_mp4&rc=OzU3NTU5ZTxlaDs0NmRoaEBpanU7NHQ5cmRlOzMzODYzNEBjMjBhYl5eXy0xMjY0L2MtYSNqYzYtMmQ0ZmdhLS1kMC1zcw%3D%3D&vvpl=1&l=20260612043527C18C959B9A8CF584D398&btag=e00088000",
          "360p": "https://v16m-default.tiktokcdn.com/6c204fed990c1083f8bbd68b500b660e/6a2b70d8/video/tos/alisg/tos-alisg-ve-0051c001-sg/oUYBAIDIFOzFBQOkIN1KABPDUsJQIQgfgqyOeE/?a=0&bti=NTU4QDM1NGA%3D&&bt=551&ft=cApXJCz7ThWHK-z9LGZmo0P&mime_type=video_mp4&rc=aDs3ZDRmNzM5OGg3NWZmOEBpanU7NHQ5cmRlOzMzODYzNEBgMS80NTAuXjQxXmBeYmNhYSNqYzYtMmQ0ZmdhLS1kMC1zcw%3D%3D&vvpl=1&l=20260612043527C18C959B9A8CF584D398&btag=e00088000",
          "480p": "https://v16m-default.tiktokcdn.com/c4a6191ed579f76eaf7b6a6611966b3b/6a2b70d8/video/tos/alisg/tos-alisg-ve-0051c001-sg/okAEI5qKBEgFlH2AAniQo8mC5AfH1KAIiAwHBA/?a=0&bti=NTU4QDM1NGA%3D&&bt=780&ft=cApXJCz7ThWHK-z9LGZmo0P&mime_type=video_mp4&rc=ODRmZWk6NzU1NDU4OWQ3NUBpanU7NHQ5cmRlOzMzODYzNEAwNDAwNS4xXl8xMDZiYTMyYSNqYzYtMmQ0ZmdhLS1kMC1zcw%3D%3D&vvpl=1&l=20260612043527C18C959B9A8CF584D398&btag=e00088000",
          "540p": "https://v16m-default.tiktokcdn.com/07591ee6ce0fc4ca315a41f1d87ee420/6a2b70d8/video/tos/alisg/tos-alisg-ve-0051c001-sg/oI2EoHAi5CI5ANF1AKQEmIHiqfs8qZBoABlAwn/?a=0&bti=NTU4QDM1NGA%3D&&bt=1063&ft=cApXJCz7ThWHK-z9LGZmo0P&mime_type=video_mp4&rc=ODZmPDQ5ZjY2NTw7NzQzOkBpanU7NHQ5cmRlOzMzODYzNEAuXmFjX2NhNjAxM140MzRiYSNqYzYtMmQ0ZmdhLS1kMC1zcw%3D%3D&vvpl=1&l=20260612043527C18C959B9A8CF584D398&btag=e00088000",
          "720p": "https://v16m-default.tiktokcdn.com/1404645b61626339c2e1d4c6df4ebb12/6a2b70d8/video/tos/alisg/tos-alisg-ve-0051c001-sg/okYmBiwEIK1QnHBHEAHu5oiSHAlWIAf52RAxAC/?a=0&bti=NTU4QDM1NGA%3D&&bt=1460&ft=cApXJCz7ThWHK-z9LGZmo0P&mime_type=video_mp4&rc=aDs5O2lpNTg0Mzc2NGc8N0BpanU7NHQ5cmRlOzMzODYzNEA2YGNhYmMuXjIxLWBfMV9eYSNqYzYtMmQ0ZmdhLS1kMC1zcw%3D%3D&vvpl=1&l=20260612043527C18C959B9A8CF584D398&btag=e00088000"
        },
        "width": 720,
        "height": 1280
      }
    }
  ],
  "pagination": {
    "has_more": true,
    "page": 1,
    "size": 20,
    "total_count": 326
  },
  "total": 326,
  "has_more": true,
  "cursor": 2
}

Verify Response Structure

Check that your response includes the expected fields:

  • βœ“success(boolean)
  • βœ“credits_remaining(number)
  • βœ“query(string)
  • βœ“region(string)
  • βœ“period(number)
  • ... and 5 more fields

Best Practices

1

Error Handling

Implement comprehensive error handling and retry logic for failed requests. Log errors properly for debugging.

2

Caching

Cache responses when possible to reduce API calls and improve performance. Consider data freshness requirements.

3

Security

Never expose your API key in client-side code. Use environment variables and secure key management practices.

Performance Tips

Batch Requests

When scraping multiple search results, consider batching requests to maximize throughput while staying within rate limits.

Async Processing

Use asynchronous processing in Kotlin to handle multiple requests concurrently and improve overall performance.

Common Use Cases

Market Research

Analyze TikTok Ad Library search results to understand market trends, competitor analysis, and audience insights.

Content Analytics

Track performance metrics, engagement rates, and content trends across TikTok Ad Library search results.

Lead Generation

Identify potential customers and business opportunities throughTikTok Ad Library data analysis.

Troubleshooting

Common Errors

401 Unauthorized

Check your API key is correct and properly formatted in the x-api-key header.

402 Payment Required

You ran out of credits and need to buy more.

404 Not Found

The resource might not exist or be private.

500 Server Error

Temporary server issue. Implement retry logic with exponential backoff.

Frequently Asked Questions

How much does it cost to scrape TikTok Ad Library search results?

ScrapeCreators offers 100 free API calls to get started. After that, pricing starts at $10 for 5k requests with volume discounts available.

Is it legal to scrape TikTok Ad Library data?

Scraping publicly available data is fair game, and we only collect public data. So anything that you can see in an incognito browser is what we collect.

How fast can I scrape TikTok Ad Library search results?

There is no rate limit! So you can scrape as fast as you want!

What data format does the API return?

All API responses are returned in JSON format, making it easy to integrate with any programming language or application.

Can I use this with other Kotlin frameworks?

Yes! This tutorial focuses on core Kotlin HTTP concepts that work with any framework. The API calls remain the same regardless of your specific Kotlin setup.

How do I handle large datasets?

For large datasets, implement pagination, use streaming responses where available, and consider storing data in a database for efficient querying.

Related Tutorials

Ready to ship?

Get the API key. Run the code.

100 free API calls. No credit card. Same endpoint, same response shape.

Same endpoint, different language

Pick another stack.