# Leetcode API (`taneja/leetcode-api-scraper`) Actor

Scrape LeetCode user profiles, problems, contests, and discussions. Get user stats, solved problems, contest ratings, submission history, activity heatmaps, daily challenges, and more - all without authentication.

- **URL**: https://apify.com/taneja/leetcode-api-scraper.md
- **Developed by:** [Raghav Taneja](https://apify.com/taneja) (community)
- **Categories:** Jobs, Developer tools, Lead generation
- **Stats:** 48 total users, 2 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.02 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## LeetCode API Scraper

Scrape LeetCode user profiles, problems, contests, and discussions data without authentication.

### Features

- **User Data**: Profiles, badges, solved problems, contest rankings, submission history, activity heatmaps
- **Problem Data**: Daily challenges, specific problems, problem lists with filters, official solutions
- **Contest Data**: All contests, upcoming contests, contest details, leaderboards
- **Discussion Data**: Trending discussions, topic details, comments

### Input

| Field | Type | Description |
|-------|------|-------------|
| `operation` | String | **Required**. The type of data to fetch |
| `username` | String | LeetCode username (for user operations) |
| `titleSlug` | String | Problem/contest slug (e.g., "two-sum") |
| `limit` | Integer | Number of items to fetch (default: 20) |
| `skip` | Integer | Items to skip for pagination |
| `year` | Integer | Year for calendar/heatmap data |
| `difficulty` | String | Filter: EASY, MEDIUM, HARD |
| `tags` | String | Comma-separated topic tags |
| `topicId` | Integer | Discussion topic ID |
| `page` | Integer | Page number for rankings |

### Operations

#### User Operations

- `userProfile` - Basic user profile
- `userSummary` - Complete user data in one call (recommended)
- `userBadges` - User badges
- `userSolved` - Solved problems with percentages
- `userContest` - Contest rating and stats
- `userContestHistory` - Contest participation history
- `userSubmissions` - Recent submissions (max 20)
- `userAcSubmissions` - Recent accepted submissions (max 20)
- `userCalendar` - Submission calendar
- `userHeatmap` - Activity heatmap (year/month/day breakdown)
- `userSkillStats` - Skill tags by category
- `userLanguageStats` - Programming language stats

#### Problem Operations

- `dailyProblem` - Today's daily challenge
- `selectProblem` - Get specific problem by titleSlug
- `problemList` - List problems with filters
- `officialSolution` - Get official solution for a problem

#### Contest Operations

- `allContests` - All LeetCode contests
- `upcomingContests` - Upcoming contests with countdown
- `contestDetail` - Specific contest details
- `contestRanking` - Contest leaderboard

#### Discussion Operations

- `trendingDiscussions` - Trending discussion topics
- `discussTopic` - Get discussion topic details
- `discussComments` - Get discussion comments

### Example Usage

#### Get User Summary

```json
{
  "operation": "userSummary",
  "username": "uwi"
}
```

#### Get Daily Problem

```json
{
  "operation": "dailyProblem"
}
```

#### Get Problem List with Filters

```json
{
  "operation": "problemList",
  "difficulty": "MEDIUM",
  "tags": "array,dynamic-programming",
  "limit": 50
}
```

#### Get Contest Ranking

```json
{
  "operation": "contestRanking",
  "titleSlug": "weekly-contest-350",
  "page": 1
}
```

### Output

Results are saved to the default dataset with this structure:

```json
{
  "operation": "userSummary",
  "success": true,
  "data": { /* LeetCode data */ },
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

### Limitations

- **Submission limit**: LeetCode's public API limits `userSubmissions` and `userAcSubmissions` to 20 items. Use `userSummary` for aggregate stats.
- **Rate limiting**: Implemented to avoid overloading LeetCode's servers
- **Premium content**: Some content may require LeetCode Premium subscription

### Notes

- Problem content is cleaned and formatted from HTML to readable text
- HTML entities (`\u003C`, `&lt;`, etc.) are properly decoded
- Solutions include video and code playground links
- Heatmaps include daily submission counts organized by year/month/day

### Cost

This Actor uses minimal compute resources as it only makes HTTP requests to LeetCode's GraphQL API.

### Support

For issues and feature requests, please open an issue in the repository.

# Actor input Schema

## `operation` (type: `string`):

Select what data you want to fetch from LeetCode

## `username` (type: `string`):

The LeetCode username to fetch data for (required for user-related operations)

## `titleSlug` (type: `string`):

The title slug of the problem or contest (e.g., 'two-sum' or 'weekly-contest-350')

## `limit` (type: `integer`):

Number of items to fetch (for submissions and problem lists)

## `skip` (type: `integer`):

Number of items to skip (for pagination)

## `year` (type: `integer`):

Year for calendar/heatmap data (optional, defaults to current year)

## `difficulty` (type: `string`):

Filter problems by difficulty level

## `tags` (type: `string`):

Filter problems by topic tags (comma-separated, e.g., 'array,string,dynamic-programming')

## `topicId` (type: `integer`):

The ID of the discussion topic (for discussTopic and discussComments operations)

## `page` (type: `integer`):

Page number for paginated results (contest rankings)

## `first` (type: `integer`):

Number of trending discussions to fetch

## `includeRawHtml` (type: `boolean`):

Include raw HTML content in addition to formatted text (for problems)

## Actor input object example

```json
{
  "operation": "userProfile",
  "username": "uwi",
  "titleSlug": "two-sum",
  "limit": 20,
  "skip": 0,
  "page": 1,
  "first": 20,
  "includeRawHtml": false
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "username": "uwi",
    "titleSlug": "two-sum"
};

// Run the Actor and wait for it to finish
const run = await client.actor("taneja/leetcode-api-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "username": "uwi",
    "titleSlug": "two-sum",
}

# Run the Actor and wait for it to finish
run = client.actor("taneja/leetcode-api-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "username": "uwi",
  "titleSlug": "two-sum"
}' |
apify call taneja/leetcode-api-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=taneja/leetcode-api-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/2xRNjH6ssbqPNj7I6/builds/xaSbs6MZZDqOmKULP/openapi.json
