How to Scrape YouTube Search Results with Swift

Extract search data from YouTube

🍎 Using Swift

Overview

Learn how to scrape YouTube search results using Swift. 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 YouTube
  • • 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:

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

Step 1: Install HTTP Client

Alamofire is an HTTP networking library for Swift

swift package
swift package add Alamofire

Step 2: API Implementation

Now let's make a request to the YouTube API using Swift. Replace YOUR_API_KEY with your actual API key.

Swift
import Foundation

class Scraper {
private static let API_KEY = "YOUR_API_KEY"
private static let BASE_URL = "https://api.scrapecreators.com"
private static let ENDPOINT_PATH = "/v1/youtube/search"
static func scrape(completion: @escaping (Result<String, Error>) -> Void) {
// Build query parameters
var components = URLComponents(string: BASE_URL + ENDPOINT_PATH)!
components.queryItems = [
URLQueryItem(name: "query", value: "example_value"),
URLQueryItem(name: "uploadDate", value: "example_value"),
URLQueryItem(name: "sortBy", value: "relevance"),
URLQueryItem(name: "filter", value: "all"),
URLQueryItem(name: "continuationToken", value: "4qmFsgKrCBIYVUNkRkpXVWE0M3NtUm00SXBIQnB"),
URLQueryItem(name: "includeExtras", value: "false")
]
guard let url = components.url else {
completion(.failure(NSError(domain: "Invalid URL", code: -1, userInfo: nil)))
return
}
var request = URLRequest(url: url)
request.setValue(API_KEY, forHTTPHeaderField: "x-api-key")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "No data", code: -1, userInfo: nil)))
return

Step 3: Testing Your Code

API Parameters

This endpoint accepts the following parameters:

queryRequired(string)

Search query

uploadDateOptional(select)

Upload date

sortByOptional(select)

Sort by

Example: relevance

filterOptional(select)

Filter by these options. Note this doesn't work when you use either 'uploadDate' or 'sortBy'. It basically only works when you have a query.

Example: all

continuationTokenOptional(string)

Continuation token to get more videos. Get 'continuationToken' from previous response.

Example: 4qmFsgKrCBIYVUNkRkpXVWE0M3NtUm00SXBIQnB

includeExtrasOptional(string)

This will get you the like + comment count and the description. To get the full details of the video, use the /v1/youtube/video endpoint. *This will slow down the response slightly.*

Example: false

Run Your Code

Execute your script to test the API connection. You should see a JSON response with YouTube 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
{
"videos": [
{
"type": "video",
"id": "BzSzwqb-OEE",
"url": "https://www.youtube.com/watch?v=BzSzwqb-OEE",
"title": "NF - RUNNING (Audio)",
"thumbnail": "https://i.ytimg.com/vi/BzSzwqb-OEE/hq720.jpg?sqp=-oaymwEnCNAFEJQDSFryq4qpAxkIARUAAIhCGAHYAQHiAQoIGBACGAY4AUAB&rs=AOn4CLCasEKav1CLqeSSE2IYDqjGiIMBGw",
"channel": {
"id": "UCoRR6OLuIZ2-5VxtnQIaN2w",
"title": "NFrealmusic",
"handle": "channel/UCoRR6OLuIZ2-5VxtnQIaN2w",
"thumbnail": "https://yt3.ggpht.com/J1_Si0TYNZ-991v09y8RpCh4_Z_ALwKmPgMYnJqjNhoglVtipf3oEN8LpzG1kS0qsv8Jptpmmg=s88-c-k-c0x00ffffff-no-rj"
},
"viewCountText": "14,860,541 views",
"viewCountInt": 14860541,
"publishedTimeText": "2 years ago",
"publishedTime": "2023-05-28T17:08:46.499Z",
"lengthText": "4:14",
"lengthSeconds": 254,
"badges": []
},
{
"type": "video",
"id": "-tLKoLN-dz4",
"url": "https://www.youtube.com/watch?v=-tLKoLN-dz4",
"title": "Not Alone, Racing the High Lonesome 100",
"thumbnail": "https://i.ytimg.com/vi/-tLKoLN-dz4/hq720.jpg?sqp=-oaymwEnCNAFEJQDSFryq4qpAxkIARUAAIhCGAHYAQHiAQoIGBACGAY4AUAB&rs=AOn4CLD1ziOa9dTFWSL6lyK6m6eO_uZkJg",
"channel": {
"id": "UCNKMpnM_Yvf6E-Hhf9btYqA",
"title": "Jeff Pelletier",
"handle": "JeffPelletier",
"thumbnail": "https://yt3.ggpht.com/YLRllcd7Q0iPYDIkJjXGEiOiJStz4KK7iepwcfTVK0yveHKqFSaLVzTvvZ0anO-SeUlXs1jNCIE=s68-c-k-c0x00ffffff-no-rj"
},
"viewCountText": "119,308 views",
"viewCountInt": 119308,

Verify Response Structure

Check that your response includes the expected fields:

  • videos(object)
  • channels(object)
  • playlists(object)
  • shorts(object)
  • shelves(object)
  • ... and 2 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 Swift to handle multiple requests concurrently and improve overall performance.

Common Use Cases

Market Research

Analyze YouTube search results to understand market trends, competitor analysis, and audience insights.

Content Analytics

Track performance metrics, engagement rates, and content trends across YouTube search results.

Lead Generation

Identify potential customers and business opportunities throughYouTube 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 YouTube 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 YouTube 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 YouTube 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 Swift frameworks?

Yes! This tutorial focuses on core Swift HTTP concepts that work with any framework. The API calls remain the same regardless of your specific Swift 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 Start Scraping?

Get started with 100 free API calls. No credit card required.