A minimal scraping serverless API that returns trending videos based on a query, sorted by view count in descending order.
This is a Next.js API, it uses zero external dependencies outside of Next itself. The entire API is contained within api/search/route.ts, making it easy to plug into existing projects.
- An
/api/searchendpoint that scrapes YouTube search results - Returns
JSONwith title, link, channel, thumbnail, and views - In-memory cache speeds up repeated requests
- Configurable settings for cache TTL and min/max result limit
- A
GETrequest is made to/api/searchwith a search term. - The server checks the in-memory cache; if a result exists, it returns cached data.
- If no cache, it scrapes the YouTube search results page, extracts embedded
JSON(ytInitialData), parses video info, and sorts by view count. - The result is cached and sent back as a
JSONresponse.
Query parameters:
q: Search termlimit(optional): Number of results (defaults to 1, maximum defaults to 4, all configurable)
Example local request using curl:
curl "http://localhost:3000/api/search?q=lofi&limit=4"Example response:
{
"videos": [
{
"title": "Lofi Chill Beats",
"link": "https://www.youtube.com/watch?v=abc123",
"channel": "Lofi Girl",
"thumbnail": "https://i.ytimg.com/vi/abc123/hqdefault.jpg",
"views": 1250000
},
...
]
}Returned fields:
title: Video title textlink: Full YouTube video URLchannel: Uploaderโs namethumbnail: Thumbnail image URLviews: View count as number
Config variables can be found at the start of route.ts:
// Query limiting
const DEFAULT_LIMIT = 1;
const MAX_LIMIT = 4;
// Caching
const CACHE_TTL = 12 * 60 * 60 * 1000; // 12 hoursClone the repository:
git clone https://github.com/yourusername/yt-trend-scraper-api.git
cd serverless-trending-apiInstall dependencies:
npm installTest the development server
npm run devTest http://localhost:3000/api/search?q=test to verify itโs running.
This project is licensed under the MIT License. See the LICENSE file for more information.