Developer Guide

Your complete guide to using the API client, integrating with REST APIs, and working with code examples.


πŸ”Œ API Integration

Learn how to fetch and display data from REST APIs using our built-in JavaScript client.

Live Example 1: Random User Data

Live Example 2: GitHub Repository Info


πŸ“š API Client Reference

The window.api object is available on all pages. Here’s the complete API:

GET Request

// Simple GET request
const data = await window.api.get('https://api.example.com/data');

// With custom headers
const data = await window.api.get('https://api.example.com/data', {
    headers: {
        'Authorization': 'Bearer your-token-here'
    }
});

POST Request

// Send data to an API
const response = await window.api.post('https://api.example.com/submit', {
    name: 'John Doe',
    email: 'john@example.com'
});

PUT Request

// Update data
const response = await window.api.put('https://api.example.com/users/1', {
    name: 'John Smith'
});

DELETE Request

// Delete data
const response = await window.api.delete('https://api.example.com/users/1');

Helper Functions

  • showLoading(element) - Display a loading spinner
  • showError(element, message) - Display an error message
  • showSuccess(element, message) - Display a success message
  • fetchAPIData(url, elementId) - Quick fetch and display (JSON format)

Example Usage Pattern

<div id="my-api-data"></div>

<script>
async function loadMyData() {
    const element = document.getElementById('my-api-data');
    showLoading(element);
    
    try {
        const data = await window.api.get('https://your-api.com/endpoint');
        
        // Display your data
        element.innerHTML = `
            <div class="card">
                <h3>${data.title}</h3>
                <p>${data.description}</p>
            </div>
        `;
    } catch (error) {
        showError(element, 'Failed to load data');
    }
}

// Load on page load
window.addEventListener('DOMContentLoaded', loadMyData);
</script>

πŸ’» Code Syntax Examples

Beautiful syntax highlighting for multiple languages with one-click copy functionality.

JavaScript

// API Client with TypeScript
class APIClient {
    constructor(baseURL = '') {
        this.baseURL = baseURL;
    }

    async get(endpoint, options = {}) {
        const response = await fetch(`${this.baseURL}${endpoint}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        return await response.json();
    }
}

// Usage
const api = new APIClient('https://api.example.com');
const data = await api.get('/users');
console.log(data);

Python

from typing import List, Dict
import asyncio
from datetime import datetime

class DataProcessor:
    """Process and transform data efficiently."""
    
    def __init__(self, config: Dict):
        self.config = config
        self.results = []
    
    async def process_batch(self, items: List[Dict]) -> List[Dict]:
        """Process a batch of items asynchronously."""
        tasks = [self.process_item(item) for item in items]
        return await asyncio.gather(*tasks)
    
    async def process_item(self, item: Dict) -> Dict:
        """Process a single item."""
        result = {
            'id': item.get('id'),
            'name': item.get('name', '').upper(),
            'timestamp': datetime.now().isoformat()
        }
        return result

# Usage
processor = DataProcessor(config={'batch_size': 100})
results = await processor.process_batch(items)
print(f"Processed {len(results)} items")

Rust

use std::collections::HashMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    email: String,
}

impl User {
    fn new(id: u64, name: String, email: String) -> Self {
        User { id, name, email }
    }

    fn is_valid(&self) -> bool {
        !self.name.is_empty() && self.email.contains('@')
    }
}

fn main() {
    let mut users: HashMap<u64, User> = HashMap::new();
    
    let user = User::new(
        1,
        "John Doe".to_string(),
        "john@example.com".to_string()
    );
    
    if user.is_valid() {
        users.insert(user.id, user);
        println!("User added successfully!");
    }
}

HTML/CSS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Beautiful Web Design</title>
    <style>
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        .card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 1rem;
            padding: 2rem;
            color: white;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>Welcome!</h1>
            <p>Beautiful design with modern CSS</p>
        </div>
    </div>
</body>
</html>

SQL

-- Create users table with indexes
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_created_at ON users(created_at DESC);

-- Insert sample data
INSERT INTO users (username, email) VALUES
    ('john_doe', 'john@example.com'),
    ('jane_smith', 'jane@example.com'),
    ('bob_wilson', 'bob@example.com');

-- Query with JOIN
SELECT 
    u.username,
    u.email,
    COUNT(p.id) as post_count
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days'
GROUP BY u.id, u.username, u.email
ORDER BY post_count DESC
LIMIT 10;

Shell/Bash

#!/bin/bash

# Deploy script with error handling
set -e

ENVIRONMENT=${1:-production}
VERSION=$(git rev-parse --short HEAD)

echo "πŸš€ Deploying version $VERSION to $ENVIRONMENT"

# Build the application
echo "πŸ“¦ Building application..."
npm run build

# Run tests
echo "πŸ§ͺ Running tests..."
npm test

# Deploy to server
echo "πŸ“€ Deploying to server..."
rsync -avz --delete \
    --exclude 'node_modules' \
    --exclude '.git' \
    ./ deploy@server.com:/var/www/app/

# Restart services
echo "πŸ”„ Restarting services..."
ssh deploy@server.com "sudo systemctl restart nginx && sudo systemctl restart app"

echo "βœ… Deployment complete!"

TypeScript

interface User {
    id: number;
    name: string;
    email: string;
    role: 'admin' | 'user';
}

class UserManager {
    private users: Map<number, User> = new Map();

    addUser(user: User): void {
        if (this.users.has(user.id)) {
            throw new Error('User already exists');
        }
        this.users.set(user.id, user);
    }

    getUser(id: number): User | undefined {
        return this.users.get(id);
    }

    getAllUsers(): User[] {
        return Array.from(this.users.values());
    }
}

// Usage
const manager = new UserManager();
manager.addUser({
    id: 1,
    name: 'John Doe',
    email: 'john@example.com',
    role: 'admin'
});

✨ Code Features

  • Dark theme - Easy on the eyes with GitHub-inspired colors
  • Syntax highlighting - Beautiful colors for different languages
  • Copy button - Hover over code blocks to see the copy button
  • Line spacing - Comfortable line height for readability
  • Inline code - Like const result = await api.get('/data') with subtle styling

🎯 Quick Tips

API Client Tips

  1. Always handle errors with try/catch
  2. Use showLoading() for better UX
  3. Store API keys securely (never in client-side code)
  4. Use environment variables for API endpoints

Code Block Tips

  1. Specify language for better highlighting
  2. Use triple backticks with language name
  3. Hover to see the copy button
  4. Works with all major languages

πŸš€ What’s Next?