Skip to content

A Python FastAPI implementation of the LeetCode API with GraphQL support using Strawberry.

License

Notifications You must be signed in to change notification settings

Techis-sg/Leetcode-API-Fastapi

Repository files navigation

LeetCode FastAPI Migration

A Python FastAPI implementation of the LeetCode API with GraphQL support using Strawberry.

License Python FastAPI REST API

πŸš€ Quick Start

Prerequisites

  • Python 3.9+
  • Poetry (for dependency management)
  • Docker (optional, for containerized deployment)

Installation

  1. Clone the repository

  2. Install dependencies:

    make install
  3. Copy environment configuration:

    cp .env.example .env
  4. Run the development server:

    make dev

The API will be available at:

πŸ“š Documentation

Complete Documentation Suite

Interactive Documentation

  • Swagger UI: /docs - Interactive API testing and exploration
  • ReDoc: /redoc - Clean, readable API documentation
  • GraphQL Playground: /graphql - Interactive GraphQL query interface

✨ Features

Core Features

  • 100% Backward Compatible: All existing TypeScript API endpoints work unchanged
  • FastAPI: Modern, fast web framework with automatic validation
  • GraphQL: Strawberry GraphQL integration alongside REST endpoints
  • Type Safety: Full type hints and Pydantic models
  • Async Support: Native asynchronous request handling

Enhanced Features

  • Auto-Generated Docs: Interactive OpenAPI/Swagger documentation
  • Advanced Error Handling: Structured error codes and detailed messages
  • Response Caching: Built-in caching with configurable TTL
  • Rate Limiting: IP-based rate limiting with customizable rules
  • Health Monitoring: Comprehensive health check endpoints

Developer Experience

  • Property-Based Testing: Comprehensive test suite with Hypothesis
  • Docker Support: Containerized deployment ready
  • Hot Reload: Development server with automatic reloading
  • Configuration Management: Environment-based configuration with validation

πŸ—οΈ Project Structure - High Level Overview

app/
β”œβ”€β”€ main.py                 # FastAPI application entry point
β”œβ”€β”€ api/routes/             # REST API endpoints
β”œβ”€β”€ core/                   # Configuration & dependencies
β”œβ”€β”€ services/               # Business logic layer
β”œβ”€β”€ models/                 # Pydantic data models
β”œβ”€β”€ clients/                # External API clients
β”œβ”€β”€ middleware/             # Custom middleware
β”œβ”€β”€ formatters/             # Data transformation
β”œβ”€β”€ graphql/                # GraphQL schema & resolvers
β”œβ”€β”€ queries/                # GraphQL query definitions
└── security/               # Security & monitoring

tests/                      # Test suites
docs/                       # API documentation
scripts/                    # Utility scripts

πŸ”„ Migration from TypeScript

Zero-Risk Migration

The Python FastAPI implementation maintains 100% backward compatibility:

  • βœ… Same Endpoints: All URLs and parameters identical
  • βœ… Same Response Format: Identical JSON structure
  • βœ… Same Behavior: Identical business logic and validation
  • βœ… No Code Changes: Existing client code works unchanged

Migration Steps

  1. Update Base URL: Point to new Python API endpoint
  2. Test Compatibility: Verify existing functionality works
  3. Explore New Features: Optionally use GraphQL and enhanced features

See the Migration Guide for detailed instructions.

πŸš€ API Examples

REST API

# Get user profile
curl https://your-api-domain.com/johndoe

# Get daily problem
curl https://your-api-domain.com/dailyProblem

# Get problems with filtering
curl "https://your-api-domain.com/problems?difficulty=Medium&limit=10"

# Get contests
curl https://your-api-domain.com/contests

GraphQL API

# Get user with specific fields
query {
  user(username: "johndoe") {
    username
    profile {
      ranking
      reputation
    }
    badges {
      name
      displayName
    }
  }
}

# Get daily problem
query {
  dailyProblem {
    date
    question {
      title
      difficulty
      topicTags {
        name
      }
    }
  }
}

🐳 Docker Deployment

Quick Start

# Build and run
make docker-build
make docker-run

# Development with hot reload
make docker-dev

Manual Docker Commands

# Build image
docker build -t leetcode-api-python .

# Run container
docker run -p 8000:8000 leetcode-api-python

# Run with environment file
docker run -p 8000:8000 --env-file .env leetcode-api-python

πŸ§ͺ Development

Code Quality

# Format code
make format

# Run linting
make lint

# Type checking
make type-check

Testing

# Run all tests
make test

# Run specific test types
make test-unit        # Unit tests only
make test-integration # Integration tests only
make test-property    # Property-based tests only

# Run with coverage
make test-cov

Pre-commit Hooks

# Install pre-commit hooks
make pre-commit-install

# Run pre-commit manually
make pre-commit-run

βš™οΈ Configuration

Configuration is managed through environment variables and the app/core/settings.py module.

Key Settings

# API Configuration
DEBUG=false
API_TITLE="LeetCode API"
API_VERSION="2.0.0"

# Feature Toggles
ENABLE_CACHING=true
ENABLE_RATE_LIMITING=true
ENABLE_GRAPHQL=true

# Performance Settings
CACHE_TTL=300                    # Cache time-to-live (seconds)
RATE_LIMIT_REQUESTS=120          # Requests per hour
RATE_LIMIT_WINDOW=3600           # Rate limit window (seconds)

# LeetCode API
LEETCODE_GRAPHQL_URL="https://leetcode.com/graphql"
LEETCODE_REFERER="https://leetcode.com"

πŸ“Š Performance & Monitoring

Built-in Monitoring

  • Health Check: /health endpoint for service monitoring
  • Metrics: Built-in performance and usage metrics
  • Logging: Structured logging with configurable levels
  • Rate Limiting: Automatic rate limit monitoring and enforcement

Performance Features

  • Async Processing: Native async/await for better concurrency
  • Response Caching: Intelligent caching reduces external API calls
  • Connection Pooling: Efficient HTTP client with connection reuse
  • Request Validation: Automatic input validation with Pydantic

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests and linting
  5. Submit a pull request

Development Guidelines

  • Follow PEP 8 style guidelines
  • Add type hints to all functions
  • Write tests for new functionality
  • Update documentation for API changes
  • Use conventional commit messages

οΏ½ Credits & Attribution

This project is a modern migration from TypeScript to Python FastAPI, inspired by and forked from the excellent work of:

Alfaarghya's alfa-leetcode-api

  • Original TypeScript/Node.js implementation
  • Foundation and API design

This Python FastAPI version maintains API compatibility while providing a Pythonic implementation with enhanced features like GraphQL support, improved type safety, and better async handling.

οΏ½πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ”— Links

  • Original TypeScript API: README.md
  • Interactive API Docs: /docs endpoint
  • GraphQL Playground: /graphql endpoint
  • Health Status: /health endpoint
  • Complete Documentation: docs/ directory

πŸ†˜ Support

  • Documentation: Check the docs/ directory for comprehensive guides
  • Interactive Testing: Use /docs and /graphql endpoints for API exploration
  • Health Monitoring: Use /health endpoint to verify service status
  • Issues: Report bugs and request features on GitHub

Migration Note: This Python implementation maintains 100% compatibility with the original TypeScript API while providing significant enhancements. See the Migration Guide for seamless transition instructions.

About

A Python FastAPI implementation of the LeetCode API with GraphQL support using Strawberry.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages