API Documentation

API Documentation

Introduction

The OpenNotes API provides programmatic access to the OpenNotes educational content platform. Use this API to browse, search, and integrate notes into your applications.

Base URL: https://open-notes.tebby2008-li.workers.dev

CORS Restriction: The API only allows requests from opennotes.pages.dev. To use this SDK from other domains, contact the API owner to whitelist your origin.

Authentication

The API supports optional Bearer token authentication for authenticated operations. For read-only access, requests may work without authentication if originating from an allowed origin.

Optional Headers

Header Value Required
Authorization Bearer {token} For authenticated actions
Content-Type application/json Recommended

Quick Start

Get up and running in minutes with this quick start guide.

1. Include the SDK

<script src="js/config.js"></script>
<script src="js/api-client.js"></script>

2. Make Your First Request

const response = await openNotesAPI.getNotes({
    limit: 10,
    sort: 'views'
});

console.log(response.items); // Array of notes
console.log(response.meta);  // Metadata including total views

3. Search for Notes

const results = await openNotesAPI.searchNotes('physics', {
    format: 'pdf',
    limit: 20
});

results.items.forEach(note => {
    console.log(note.title, note.auth);
});

Notes Endpoints

GET Get Notes List

Retrieve a list of all notes with optional filtering and sorting.

?type=list

Query Parameters

Parameter Type Description
typestringRequired. Must be "list"
sortstringSort order: relevance, views, downloads, updated, name
limitintegerNumber of results (default: 20, max: 100)
offsetintegerPagination offset (default: 0)
qstringSearch query
formatstringFilter by format: pdf, docx, pptx, etc.
authorstringFilter by author name
verifiedbooleanFilter to verified notes only

Example Request

const notes = await openNotesAPI.getNotes({
    sort: 'views',
    limit: 10,
    filters: { format: 'pdf' }
});

GET Get Single Note

Retrieve details for a specific note by ID or name.

?type=note&noteId={noteId}

const note = await openNotesAPI.getNote('IB Physics (Magnetism).pdf');
console.log(note.title, note.v, note.d);

GET Search Notes

Search for notes by keyword with advanced filtering.

// Simple search
const results = await openNotesAPI.searchNotes('calculus');

// Advanced search with filters
const physicsNotes = await openNotesAPI.searchNotes('physics', {
    format: 'pdf',
    verifiedOnly: true,
    sort: 'views',
    limit: 10
});

Counters Endpoints

POST Increment Views

Increment the view counter for a note. Call this when a user views a note.

?type=note&noteId={noteId}&counter=views

await openNotesAPI.incrementViews('AP Calculus AB Notes.pdf');

POST Increment Downloads

Increment the download counter for a note. Call this when a user downloads a note.

await openNotesAPI.incrementDownloads('AP Calculus AB Notes.pdf');

Statistics

Get comprehensive statistics about the notes collection.

const stats = await openNotesAPI.getStatistics();

console.log('Total Notes:', stats.totalNotes);
console.log('Total Views:', stats.totalViews);
console.log('Format Distribution:', stats.formats);
console.log('Top Authors:', stats.authors);

Statistics Object Properties

Property Type Description
totalNotesnumberTotal number of notes
totalViewsnumberTotal site-wide views
totalDownloadsnumberTotal downloads across all notes
verifiedNotesnumberCount of verified notes
formatsobjectNotes count by format
authorsobjectNotes count by author
topViewedNotesarrayTop 5 most viewed notes
topDownloadedNotesarrayTop 5 most downloaded notes

JavaScript SDK Installation

Include the SDK files in your HTML page:

<!-- Configuration -->
<script src="js/config.js"></script>

<!-- Core Modules -->
<script src="js/utils.js"></script>
<script src="js/events.js"></script>
<script src="js/api-client.js"></script>

<!-- UI Components -->
<script src="js/notes-browser.js"></script>
<script src="js/search.js"></script>
<script src="js/analytics.js"></script>

<!-- Feature Modules -->
<script src="js/favorites.js"></script>
<script src="js/export.js"></script>
<script src="js/theme.js"></script>

<!-- SDK Bundle -->
<script src="js/opennotes.js"></script>

API Client

The OpenNotesAPIClient class provides all core API functionality.

Creating a Custom Instance

// Use the default instance
const api = openNotesAPI;

// Or create a custom instance
const customApi = new OpenNotesAPIClient({
    apiUrl: 'https://open-notes.tebby2008-li.workers.dev',
    apiKey: null, // Optional - for authenticated requests
    timeout: 10000,
    retries: 3
});

Available Methods

Method Description
getNotes(options)Get list of notes with options
getNote(noteId)Get single note by ID
searchNotes(query, options)Search notes by keyword
getNotesByAuthor(author)Get notes by author
getNotesByFormat(format)Get notes by format
getTrendingNotes(limit)Get most viewed notes
incrementViews(noteId)Increment view counter
incrementDownloads(noteId)Increment download counter
getStatistics()Get comprehensive statistics
healthCheck()Check API availability

Events

// Listen for API events
openNotesAPI.on('request:start', (data) => {
    console.log('Request started:', data.url);
});

openNotesAPI.on('request:success', (data) => {
    console.log('Request succeeded:', data);
});

openNotesAPI.on('request:error', (data) => {
    console.error('Request failed:', data.error);
});

Notes Browser Component

Create interactive notes browsing interfaces easily.

const browser = new NotesBrowser('#container', {
    viewMode: 'grid',          // 'grid' or 'list'
    pageSize: 20,              // Notes per page
    showFilters: true,         // Show filter controls
    showSorting: true,         // Show sort dropdown
    showPagination: true,      // Show pagination controls
    enableFavorites: true,     // Enable favorites feature
    showThumbnails: true,      // Show note thumbnails
    
    // Callbacks
    onNoteClick: (note) => {
        console.log('Note clicked:', note);
    },
    onDownload: (note) => {
        console.log('Download started:', note);
    }
});

// Methods
browser.refresh();                    // Reload notes
browser.setFilter('format', 'pdf');   // Set filter
browser.setSort('views');             // Change sort order
browser.loadFavoriteNotes();          // Load favorites only

Analytics Dashboard

Display comprehensive statistics and charts.

const analytics = new OpenNotesAnalytics({
    container: '#analytics',
    showCharts: true,
    refreshInterval: 60000,  // Auto-refresh every minute
    theme: 'light'
});

// Get current stats
const stats = analytics.getStats();

// Export data
analytics.exportData('json');  // or 'csv'

Response Format

All API responses follow this structure:

Notes List Response

{
    "items": [
        {
            "id": 1,
            "name": "AP Calculus AB Notes.pdf",
            "title": "AP Calculus AB Notes",
            "format": "pdf",
            "v": 110,           // Views
            "d": 5,             // Downloads
            "auth": "Chenyu Li",
            "is_verified": true,
            "thumb": "https://...",  // Thumbnail URL
            "dl": "https://...",     // Download URL
            "size": "9.18 MiB"
        }
    ],
    "meta": {
        "views": 4734,
        "user": {
            "name": "Chenyu Li",
            "is_admin": true
        }
    }
}

Error Handling

Handle API errors gracefully using try-catch:

try {
    const notes = await openNotesAPI.getNotes();
} catch (error) {
    if (error instanceof OpenNotesAPIError) {
        if (error.is403()) {
            console.error('Access denied - check API key and origin');
        } else if (error.is404()) {
            console.error('Note not found');
        } else if (error.is500()) {
            console.error('Server error - try again later');
        }
    } else {
        console.error('Network error:', error);
    }
}

Common Error Codes

Status Meaning Solution
401UnauthorizedCheck X-Api-Key header
403ForbiddenVerify origin domain and API key
404Not FoundCheck note ID/name
429Rate LimitedSlow down requests
500Server ErrorRetry later

Rate Limiting

To ensure fair usage, the API implements rate limiting:

  • Maximum 60 requests per minute
  • Maximum 1000 requests per hour
  • Counter increment endpoints are limited to 10 per minute per note

The SDK includes built-in retry logic with exponential backoff to handle rate limiting gracefully.