Sign inSign up

vfraziers/ncccs-api

By vfraziers

•Updated over 1 year ago

Image
0

993

vfraziers/ncccs-api repository overview

⁠WebAdvisor Course API

A REST API for accessing NC Community Colleges WebAdvisor course information. This API provides programmatic access to course catalogs, subject categories, and detailed course information from the WebAdvisor system using Browserless for reliable web scraping.

⁠Features

  • Dynamic Subject Access: Automatically discovers and provides access to all available subject categories
  • Comprehensive Course Data: Returns detailed course information including descriptions, credits, prerequisites, and more
  • Browserless Integration: Uses Browserless service for reliable, scalable web scraping without local browser dependencies
  • Intelligent Caching: Built-in caching system to improve performance and reduce load on WebAdvisor
  • Rate Limiting: Prevents API abuse with configurable rate limiting
  • Search Functionality: Search courses across all subjects
  • RESTful Design: Clean, intuitive API endpoints following REST principles
  • Auto-generated Documentation: Interactive API documentation with Swagger UI

⁠API Endpoints

⁠Core Endpoints
  • GET / - API information and available endpoints
  • GET /health - Health check endpoint
  • GET /docs - Interactive API documentation (Swagger UI)
  • GET /redoc - Alternative API documentation (ReDoc)
⁠Subject and Course Endpoints
  • GET /api/subjects - Get all available subject categories
  • GET /api/subjects/{subject_code}/courses - Get all courses for a specific subject
  • GET /api/courses/{subject_code}/{course_number} - Get detailed information for a specific course
  • GET /api/search?query={term}&limit={number} - Search courses across all subjects
⁠Cache Management
  • GET /api/cache/info - Get cache statistics and information
  • DELETE /api/cache/clear - Clear all cached data (admin endpoint)

⁠Installation

⁠Prerequisites
  • Python 3.8 or higher
  • Browserless account and API token (or self-hosted Browserless instance)
⁠Setup
  1. Clone or download the project

    cd webadvisor-api
    
  2. Create a virtual environment

    python -m venv venv
    
    # On Windows
    venv\Scripts\activate
    
    # On macOS/Linux
    source venv/bin/activate
    
  3. Install dependencies

    pip install -r requirements.txt
    
  4. Configure environment variables

    cp .env.example .env
    # Edit .env file with your Browserless settings
    

    Required Environment Variables:

    • BROWSERLESS_URL: Your Browserless service URL (e.g., https://chrome.browserless.io)
    • BROWSERLESS_TOKEN: Your Browserless API token
  5. Run the API

    # Development mode
    uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
    
    # Production mode
    uvicorn app.main:app --host 0.0.0.0 --port 8000
    

The API will be available at http://localhost:8000

⁠Browserless Setup

⁠Option 1: Browserless Cloud Service
  1. Sign up at browserless.io⁠
  2. Get your API token from the dashboard
  3. Set BROWSERLESS_URL=https://chrome.browserless.io and BROWSERLESS_TOKEN=your_token in your .env file
⁠Option 2: Self-hosted Browserless
  1. Deploy Browserless using Docker:
    docker run -p 3000:3000 browserless/chrome
    
  2. Set BROWSERLESS_URL=http://localhost:3000 in your .env file
  3. No token required for self-hosted instances

⁠Usage Examples

⁠Get All Subjects
curl http://localhost:8000/api/subjects

Response:

{
  "subjects": [
    {
      "code": "ACC",
      "name": "Accounting"
    },
    {
      "code": "AGR",
      "name": "Agriculture"
    }
  ],
  "total_subjects": 2,
  "last_updated": "2025-01-11T15:00:00Z"
}
⁠Get Courses for a Subject
curl http://localhost:8000/api/subjects/ACC/courses

Response:

{
  "subject_code": "ACC",
  "courses": [
    {
      "subject_code": "ACC",
      "course_number": "120",
      "course_title": "Principles of Financial Accounting",
      "credits": 4.0,
      "description": "This course introduces basic financial accounting concepts...",
      "prerequisites": ["MAT 143 or equivalent"],
      "corequisites": [],
      "lecture_hours": 3.0,
      "lab_hours": 2.0,
      "work_experience_hours": 0.0,
      "course_type": "Curriculum",
      "transferability": "Transfers to UNC system",
      "last_updated": "2025-01-11T15:00:00Z"
    }
  ],
  "total_courses": 1,
  "last_updated": "2025-01-11T15:00:00Z"
}
⁠Search Courses
curl "http://localhost:8000/api/search?query=accounting&limit=10"
⁠Get Specific Course
curl http://localhost:8000/api/courses/ACC/120

⁠Configuration

The API can be configured using environment variables. Copy .env.example to .env and modify as needed:

⁠Required Settings
  • BROWSERLESS_URL: Browserless service URL
  • BROWSERLESS_TOKEN: Browserless API token (if using cloud service)
⁠Optional Settings
  • API_HOST: Host to bind the API (default: 0.0.0.0)
  • API_PORT: Port to run the API (default: 8000)
  • CACHE_TTL_SUBJECTS: Cache TTL for subjects in seconds (default: 86400)
  • CACHE_TTL_COURSES: Cache TTL for courses in seconds (default: 3600)
  • RATE_LIMIT_MAX_REQUESTS: Max requests per window (default: 100)
  • RATE_LIMIT_WINDOW_SECONDS: Rate limit window in seconds (default: 3600)

⁠Architecture

⁠Components
  • FastAPI: High-performance web framework for the REST API
  • Browserless: Cloud-based browser automation service for reliable web scraping
  • BeautifulSoup: Parses HTML content and extracts structured data
  • Pydantic: Data validation and serialization
  • In-memory Caching: Reduces load on WebAdvisor and improves response times
  • Rate Limiting: Prevents abuse and ensures fair usage
⁠Data Flow
  1. Client makes API request
  2. Rate limiter checks if request is allowed
  3. Cache is checked for existing data
  4. If cache miss, Browserless scraper extracts data from WebAdvisor
  5. Data is parsed, validated, and cached
  6. JSON response is returned to client
⁠Benefits of Browserless
  • No Local Dependencies: No need to install Chrome or manage WebDriver
  • Scalability: Handles multiple concurrent requests efficiently
  • Reliability: Professional-grade browser automation service
  • Maintenance-Free: No browser updates or compatibility issues
  • Resource Efficient: Offloads browser processing to dedicated service

⁠Performance Considerations

  • Caching: Subjects are cached for 24 hours, courses for 1 hour
  • Rate Limiting: 100 requests per hour per client by default
  • Browserless Optimization: Uses cloud-based browsers for optimal performance
  • Async Operations: FastAPI's async capabilities for concurrent requests

⁠Error Handling

The API includes comprehensive error handling:

  • 400 Bad Request: Invalid parameters or malformed requests
  • 404 Not Found: Requested resource doesn't exist
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server-side errors with detailed logging

⁠Monitoring and Logging

  • Structured logging with configurable levels
  • Cache statistics endpoint for monitoring
  • Health check endpoint for uptime monitoring
  • Request/response logging for debugging
  • Browserless request tracking

⁠Development

⁠Project Structure
webadvisor-api/
├── app/
│   ├── __init__.py
│   ├── main.py          # FastAPI application and routes
│   ├── models.py        # Pydantic data models
│   ├── scraper.py       # WebAdvisor scraping logic with Browserless
│   ├── cache.py         # Caching implementation
│   └── rate_limiter.py  # Rate limiting implementation
├── requirements.txt     # Python dependencies
├── .env.example        # Environment configuration template
└── README.md           # This file
⁠Running Tests
# Install test dependencies
pip install pytest pytest-asyncio httpx

# Run tests (when implemented)
pytest

⁠Deployment

⁠Docker Hub Deployment

This repository is configured with GitHub Actions to automatically build and publish Docker images to Docker Hub as vfraziers/ncccs-api.

⁠Automated Docker Publishing

The GitHub Actions workflow automatically:

  • Builds multi-platform Docker images (linux/amd64, linux/arm64)
  • Publishes to Docker Hub on pushes to main/master branch
  • Creates tagged releases for version tags (e.g., v1.0.0)
  • Updates the Docker Hub repository description
⁠Required GitHub Secrets

To enable automatic Docker Hub publishing, configure these secrets in your GitHub repository settings:

  1. Go to your GitHub repository → Settings → Secrets and variables → Actions
  2. Add the following repository secrets:
  • DOCKERHUB_USERNAME: Your Docker Hub username
  • DOCKERHUB_TOKEN: Your Docker Hub access token (not password)
⁠Creating a Docker Hub Access Token
  1. Log in to Docker Hub⁠
  2. Go to Account Settings → Security
  3. Click "New Access Token"
  4. Give it a descriptive name (e.g., "GitHub Actions")
  5. Copy the generated token and add it as DOCKERHUB_TOKEN secret
⁠Using the Published Image

Once published, you can use the Docker image:

# Pull and run the latest image
docker pull vfraziers/ncccs-api:latest
docker run -p 8000:8000 --env-file .env vfraziers/ncccs-api:latest

# Or use docker-compose with the published image
# Update docker-compose.yml to use: image: vfraziers/ncccs-api:latest
⁠Manual Docker Build

For local development or manual deployment:

# The existing Dockerfile builds the image
docker build -t webadvisor-api .
docker run -p 8000:8000 --env-file .env webadvisor-api
⁠Environment Variables for Production
# Production settings
API_DEBUG=False
BROWSERLESS_URL=https://chrome.browserless.io
BROWSERLESS_TOKEN=your_production_token
RATE_LIMIT_MAX_REQUESTS=1000
RATE_LIMIT_WINDOW_SECONDS=3600

⁠Cost Considerations

When using Browserless cloud service:

  • Monitor your usage through the Browserless dashboard
  • Implement appropriate caching to minimize browser requests
  • Consider rate limiting to control costs
  • Use the free tier for development and testing

⁠Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

⁠License

This project is provided as-is for educational and development purposes.

⁠Disclaimer

This API scrapes data from the NC Community Colleges WebAdvisor system. Please use responsibly and in accordance with the website's terms of service. The API includes rate limiting to prevent overwhelming the source system.

⁠Support

For issues, questions, or contributions, please refer to the project documentation or create an issue in the project repository.

⁠Troubleshooting

⁠Common Issues
  1. Browserless Connection Errors

    • Verify your BROWSERLESS_URL and BROWSERLESS_TOKEN
    • Check your Browserless account limits and usage
  2. Scraping Failures

    • WebAdvisor site structure may have changed
    • Check logs for specific error messages
    • Verify the site is accessible
  3. Performance Issues

    • Increase cache TTL values
    • Monitor Browserless usage and limits
    • Consider implementing request queuing for high load
⁠Debug Mode

Enable debug logging by setting LOG_LEVEL=DEBUG in your .env file for detailed request/response information.

Tag summary

Content type

Image

Digest

sha256:d260d6641…

Size

69.1 MB

Last updated

over 1 year ago

docker pull vfraziers/ncccs-api